#!/usr/bin/python3

import os
import random
import subprocess
import sys
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
status, output = subprocess.getstatusoutput(f"unsquashfs -o {app_image_offset} -ll '{t.args.input}' | grep '.DirIcon -> '")

# Case where .DirIcon is an image or is missing
if status != 0:
    status, output = subprocess.getstatusoutput(f"unsquashfs -o {app_image_offset} -ll '{t.args.input}' | grep .DirIcon")
    icon_path = ".DirIcon" if status == 0 else None

# Case where .DirIcon is a symlink or symlink chain
else:
    while "-> " in output:
        icon_path = output.strip().split("-> ")[1]
        # Some appimages use local apppimage paths, e.g., ./usr/applications/...
        if icon_path[0:2] == "./":
            icon_path = icon_path[2:]
        output = subprocess.getoutput(f"unsquashfs -o {app_image_offset} -ll '{t.args.input}' | grep '{icon_path} -> '")

# 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)
    success = t.save_path(icon_path)
    os.system(f"rm -rf '{TMP_DIR}'")
    sys.exit(0 if success else 1)

sys.exit(1)
