#!/usr/bin/python3

import os
import random
import subprocess
from elftools.elf.elffile import ELFFile

import XappThumbnailers
t = XappThumbnailers.Thumbnailer()

rand_int = random.randint(0, 1000)
TMP_DIR = f"/tmp/appimage{rand_int}.thumbnail"
os.system(f"mkdir -p '{TMP_DIR}'")
os.system(f"rm -rf '{TMP_DIR}'/*")
os.chdir(TMP_DIR)

# Find the section header offset within the ELF file
f = open(t.args.input, 'rb')
elf = ELFFile(f)
app_image_offset = elf['e_shoff'] + (elf['e_shentsize'] * elf['e_shnum'])
f.close()

# Find the location of the icon inside the squashfs
icon_path = None
output = subprocess.getoutput(f"unsquashfs -o {app_image_offset} -ll '{t.args.input}' | grep .DirIcon")
for line in output.split("\n"):
    if "-> " in line:
        icon_path = line.strip().split("-> ")[1]
        break

# Extract the icon
if icon_path != None:
    subprocess.getoutput(f"echo '{icon_path}' > files")
    cmd = f"unsquashfs -o {app_image_offset} -e files '{t.args.input}'"
    output = subprocess.getoutput(cmd)
    icon_path = os.path.join(TMP_DIR, "squashfs-root", icon_path)
    t.save_path(icon_path)
    os.system(f"rm -rf '{TMP_DIR}'")

