#!/usr/bin/env python3
"""
解包AppImage脚本 - 通过系统通知提示结果。
用法: extractappimage <APPIMAGE文件路径>
"""

import sys
import os
import subprocess


def notify(title, message, icon="emblem-checked"):
    subprocess.run([
        "notify-send",
        "--app-name=解压AppImage",
        title,
        message,
        f"--icon={icon}"
    ])


def main():
    try:
        if len(sys.argv) < 2:
            notify("", "失败", "dialog-error")
            sys.exit(1)

        name = sys.argv[1]
        if name.startswith("file://"):
            name = name[7:]

        if os.path.isdir(name):
            sys.exit(0)

        os.chmod(name, 0o755)

        appdir = os.path.dirname(name)
        basename = os.path.basename(name)
        # 去掉 .AppImage / .appimage 等后缀（大小写不敏感）
        dirname = basename
        for ext in (".AppImage", ".appimage", ".APPIMAGE"):
            if dirname.endswith(ext):
                dirname = dirname[:-len(ext)]
                break

        destdir = os.path.join(appdir, dirname)
        os.makedirs(destdir, exist_ok=True)

        subprocess.run([name, "--appimage-extract"],
                       cwd=destdir, check=True)

        notify("", "成功", "emblem-checked")

    except Exception:
        notify("", "失败", "dialog-error")
        sys.exit(1)


if __name__ == "__main__":
    main()
