#!/usr/bin/env python3
"""Build KeePassXC 2.8.x AppImage on Ubuntu 20.04 (Focal).

Produces an AppImage compatible with RHEL 9 (glibc 2.34).

Usage:
    ./do_kpxc_appimage.py              # build default version
    ./do_kpxc_appimage.py 2.8.1        # build specific version
    ./do_kpxc_appimage.py --latest     # auto-detect latest 2.8.x tag
    ./do_kpxc_appimage.py --head       # build from develop HEAD (CI test)

Prerequisites (run once):
    sudo add-apt-repository -y ppa:savoury1/build-tools
    sudo add-apt-repository -y ppa:savoury1/backports
    sudo add-apt-repository -y ppa:savoury1/python
    sudo add-apt-repository -y ppa:savoury1/fonts
    sudo add-apt-repository -y ppa:savoury1/graphics
    sudo add-apt-repository -y ppa:savoury1/multimedia
    sudo add-apt-repository -y ppa:savoury1/ffmpeg4
    sudo add-apt-repository -y ppa:savoury1/display
    sudo add-apt-repository -y ppa:savoury1/llvm-defaults-13
    sudo add-apt-repository -y ppa:savoury1/qt-6-2
    sudo apt-get install -y g++-10 cmake ninja-build git \
      qt6-base-dev qt6-base-dev-tools qt6-base-private-dev \
      qt6-tools-dev qt6-tools-dev-tools qt6-l10n-tools \
      qt6-svg-dev qt6-wayland qt6-wayland-dev qt6-wayland-dev-tools \
      qt6-websockets-dev qt6-image-formats-plugins qt6-translations-l10n \
      libargon2-dev libqrencode-dev libreadline-dev libxi-dev libxtst-dev \
      libyubikey-dev libykpers-1-dev libusb-1.0-0-dev libpcsclite-dev \
      libminizip-dev libkeyutils-dev libxkbcommon-dev asciidoctor \
      zlib1g-dev fuse libfuse2 libgl1-mesa-dev

    Also build Botan >= 2.19.1:  ~/src/build_botan.sh

$Id$
"""

import glob
import os
import re
import shutil
import subprocess
import sys
from datetime import date
from multiprocessing import cpu_count
from pathlib import Path

######################################################################
# Configuration
######################################################################
KPXC_DEFAULT_VERSION = "2.8.0"
KPXC_REPO = Path.home() / "src" / "keepassxc"
# Remote (scp) copy targets — host:path
DEST_SCP = [
    ("imladris", "/var/tmp/DUMP-Unsorted"),
    ("imladris", "/export/home/raistlin/opt"),
    ("imladris", "/export/home/raistlin/World/Vincent/WebSite/www/dist/keepassxc"),
]

# Build tools to copy alongside the AppImage to the website dist dir
DIST_TOOLS = ["do_kpxc_appimage.py", "build_botan.sh", "README.md"]

PATCH_MARKER = "# RHEL9-APPIMAGE-PATCH"

# Python code to insert before the appimagetool invocation
PATCH_ICON_AND_TRANSLATIONS = """\
        {marker}
        root_icon = app_dir / "keepassxc.png"
        if not root_icon.exists():
            import shutil as _shutil
            _shutil.copy2(icon_file, root_icon)
        (app_dir / "usr" / "translations").mkdir(parents=True, exist_ok=True)
""".format(marker=PATCH_MARKER)


def run(cmd, check=True, **kwargs):
    """Run a command, printing it first. Exit on failure unless check=False."""
    print(f"+ {cmd}" if isinstance(cmd, str) else f"+ {' '.join(cmd)}")
    result = subprocess.run(cmd, shell=isinstance(cmd, str), **kwargs)
    if check and result.returncode != 0:
        sys.exit(result.returncode)
    return result


def git(*args, capture=False, check=True):
    """Run a git command in KPXC_REPO."""
    cmd = ["git"] + list(args)
    if capture:
        r = subprocess.run(cmd, cwd=KPXC_REPO, capture_output=True, text=True)
        if check and r.returncode != 0:
            print(r.stderr, file=sys.stderr)
            sys.exit(r.returncode)
        return r
    else:
        return run(cmd, check=check, cwd=KPXC_REPO)


def detect_latest_version():
    """Find the newest 2.8.x release tag (no beta/rc)."""
    r = git("tag", "-l", "2.8.*", "--sort=-v:refname", capture=True)
    for line in r.stdout.splitlines():
        tag = line.strip()
        if tag and "beta" not in tag and "rc" not in tag:
            return tag
    print("ERROR: No 2.8.x release tags found")
    sys.exit(1)


def detect_head_version():
    """Derive a version string from develop HEAD.

    Uses the latest stable tag as the base version, then counts
    commits ahead on develop and appends today's date.
    Produces e.g. '2.8.0-HEAD-42.20261031'.
    """
    base = detect_latest_version()
    today = date.today().strftime("%Y%m%d")

    # Count commits between the stable tag and develop HEAD
    r = git("rev-list", "--count", f"{base}..origin/develop",
            capture=True, check=False)
    commits = r.stdout.strip() if r.returncode == 0 else "0"

    build_version = f"{base}-HEAD-{commits}.{today}"
    return base, build_version


def setup_environment():
    """Set compiler and Qt environment variables, clear proxy."""
    env_vars = {
        "CC": "gcc-10",
        "CXX": "g++-10",
        "QMAKE": "/usr/bin/qmake6",
        "PKG_CONFIG_PATH": "/usr/lib/pkgconfig:/usr/lib/x86_64-linux-gnu/pkgconfig",
        "EXTRA_QT_PLUGINS": "waylandcompositor;svg",
        "EXTRA_PLATFORM_PLUGINS": "libqwayland-egl.so;libqwayland-generic.so",
    }
    os.environ.update(env_vars)
    os.environ["PATH"] = "/usr/local/bin:" + os.environ["PATH"]

    for var in ("http_proxy", "https_proxy", "ftp_proxy"):
        os.environ.pop(var, None)


def clean_checkout(ref, branch_name):
    """Nuclear-clean the tree and create a fresh build branch."""
    print(f"=== Clean checkout of {ref} ===")
    git("checkout", "-f", ref, check=False)
    git("clean", "-fdx")
    git("branch", "-D", branch_name, check=False)
    git("checkout", "-b", branch_name)


def patch_release_tool():
    """Patch release-tool.py for local AppImage builds.

    1. Copy icon to AppDir root (required by newer appimagetool)
    2. Create usr/translations dir (avoids symlink warnings)
    3. Add --no-appstream to appimagetool (skip metadata validation)
    """
    release_tool = KPXC_REPO / "release-tool.py"
    content = release_tool.read_text()

    if PATCH_MARKER in content:
        print("=== Patches already applied ===")
        return

    print("=== Applying release-tool.py patches ===")

    # Patch 1+2: insert icon copy + translations dir before appimagetool
    content = content.replace(
        "        logger.debug('Running appimagetool...')",
        PATCH_ICON_AND_TRANSLATIONS
        + "        logger.debug('Running appimagetool...')",
    )

    # Patch 3: add --no-appstream to appimagetool invocation
    content = content.replace(
        "_run([appimagetool.as_posix(),\n",
        "_run([appimagetool.as_posix(),\n"
        "              '--no-appstream',\n",
    )

    release_tool.write_text(content)

    git("add", "release-tool.py")
    git("commit", "-m",
        "RHEL9 AppImage: fix icon, translations dir, skip appstream validation")
    print("=== Patches committed ===")


def build(version):
    """Run the KeePassXC release-tool build."""
    print(f"=== Building KeePassXC {version} AppImage ===")
    run([
        "python3", "release-tool.py", "build", version,
        "--use-system-deps",
        "--appimage",
        "--snapshot",
        "--override-version", version,
        "-j", str(cpu_count()),
        "-y",
        "-c", "-DWITH_XC_ALL=ON",
        "-DWITH_XC_DOCS=OFF",
        "-DCMAKE_LIBRARY_PATH=/usr/lib",
    ], cwd=KPXC_REPO)


def rename_and_copy():
    """Rename AppImage with RHEL9 suffix and copy to destination."""
    appimages = sorted((KPXC_REPO / "release").glob("KeePassXC-*.AppImage"))
    if not appimages:
        print("ERROR: No AppImage found in release/")
        sys.exit(1)

    appimage = appimages[0]
    final_name = appimage.name.replace("-x86_64", "-RHEL9-x86_64")
    final_path = appimage.parent / final_name
    appimage.rename(final_path)

    print(f"=== AppImage built: {final_name} ===")
    size_mb = final_path.stat().st_size / (1024 * 1024)
    print(f"    {final_path}  ({size_mb:.1f} MB)")

    # scp to all destinations
    src_dir = KPXC_REPO.parent
    for host, remote_dir in DEST_SCP:
        result = run(["scp", str(final_path), f"{host}:{remote_dir}/"],
                     check=False)
        if result.returncode == 0:
            print(f"=== scp'd AppImage to {host}:{remote_dir} ===")
        else:
            print(f"WARNING: scp to {host}:{remote_dir} failed")

    # Copy build tools to the website dist dir (last scp target)
    dist_host, dist_dir = DEST_SCP[-1]
    tools_to_copy = [str(src_dir / t) for t in DIST_TOOLS if (src_dir / t).exists()]
    if tools_to_copy:
        result = run(["scp"] + tools_to_copy + [f"{dist_host}:{dist_dir}/"],
                     check=False)
        if result.returncode == 0:
            print(f"=== scp'd build tools to {dist_host}:{dist_dir} ===")


def main():
    setup_environment()
    os.chdir(KPXC_REPO)

    git("fetch", "--all", "--tags", "--force")

    head_mode = False

    if len(sys.argv) > 1 and sys.argv[1] == "--latest":
        version = detect_latest_version()
        build_version = f"{version}-1"
        print(f"=== Auto-detected latest version: {version} ===")
    elif len(sys.argv) > 1 and sys.argv[1] == "--head":
        head_mode = True
        _base_tag, build_version = detect_head_version()
        print(f"=== Building from develop HEAD: {build_version} ===")
    elif len(sys.argv) > 1:
        version = sys.argv[1]
        build_version = f"{version}-1"
    else:
        version = KPXC_DEFAULT_VERSION
        build_version = f"{version}-1"

    if head_mode:
        clean_checkout("origin/develop", "rhel9-build-develop")
    else:
        clean_checkout(version, f"rhel9-build-{version}")

    patch_release_tool()
    build(build_version)
    rename_and_copy()


if __name__ == "__main__":
    main()
