import os
import shutil
import subprocess
import tarfile
import tempfile
from pathlib import Path

from dev_tools.build.utility import get_first_file_found
from dev_tools.utility.path import ROOT

HERE = os.path.abspath(os.path.dirname(__file__))


def build_appimage(development: bool, frozen_dir: Path, frozen_version: str):
    app_image_tool = get_first_file_found("appimagetool", "appimagetool.AppImage")
    temp_dir_path = tempfile.mkdtemp()
    try:
        build_dir = os.path.join(temp_dir_path, "clarabot-nano.AppDir")
        shutil.copytree(os.path.join(HERE, "clarabot-nano.AppDir"), build_dir)
        for item in frozen_dir.iterdir():
            if item.is_dir():
                shutil.copytree(item, os.path.join(build_dir, item.name))
            else:
                shutil.copy(item, os.path.join(build_dir, item.name))
        # TODO: would like signing, but no support for PKCS11...
        subprocess.check_call([app_image_tool, "--no-appstream", build_dir], cwd=temp_dir_path)
        app_images = [item for item in Path(temp_dir_path).iterdir() if item.name.endswith(".AppImage")]
        if len(app_images) != 1:
            raise Exception(f"Multiple appimages: {app_images}")
        shutil.move(app_images[0], Path(ROOT, "build", f"clarabot-nano-{frozen_version}.AppImage"))
    finally:
        shutil.rmtree(temp_dir_path)


def build_archive(development: bool, frozen_dir: Path, frozen_version: str):
    archive_root = frozen_dir.parent
    with tarfile.open(frozen_dir.parent / f"{frozen_dir.name}.tar.gz", "w:gz", format=tarfile.GNU_FORMAT) as tf:
        for item in frozen_dir.iterdir():
            tf.add(item, str(item.relative_to(archive_root)))
