#!/usr/bin/env bash
set -euo pipefail

repo="${AGENTSTRAP_GITHUB_REPO:-Agent-Technologies/Agentstrap}"
asset_name="agentstrap-linux-x86_64.tar.gz"
expected_v010_sha256="288acb02ad951511418352faae4a4bee62f8e77c695642bffe54e7a5c5023dbe"
local_archive=""
version=""
launch=0

usage() {
  cat <<'HELP'
Agentstrap Linux installer

Usage:
  curl -fsSL https://raw.githubusercontent.com/Agent-Technologies/Agentstrap/main/Agentstrap-Linux/install.sh | bash
  install.sh --archive agentstrap-linux-x86_64.tar.gz [--version v0.1.0] [--launch]

The online installer selects a GitHub release with the Linux archive, verifies
its SHA-256, and installs only for the current user.
HELP
}

while (($#)); do
  case "$1" in
    --archive) local_archive="${2:?missing archive path}"; shift 2 ;;
    --version) version="${2:?missing version}"; shift 2 ;;
    --launch) launch=1; shift ;;
    --help|-h) usage; exit 0 ;;
    *) echo "Unknown option: $1" >&2; usage >&2; exit 2 ;;
  esac
done

for tool in tar python3 sha256sum; do
  command -v "$tool" >/dev/null 2>&1 || { echo "Required command not found: $tool" >&2; exit 1; }
done
[[ "$(uname -m)" == x86_64 ]] || { echo "This installer currently supports x86_64 Linux only." >&2; exit 1; }

tmp="$(mktemp -d)"
cleanup() {
  python3 - "$tmp" <<'PY'
import os, shutil, sys, tempfile
path = os.path.realpath(sys.argv[1])
base = os.path.realpath(tempfile.gettempdir())
if os.path.commonpath([path, base]) == base and os.path.basename(path).startswith("tmp."):
    shutil.rmtree(path)
PY
}
trap cleanup EXIT

if [[ -z "$local_archive" ]]; then
  command -v curl >/dev/null 2>&1 || { echo "Required command not found: curl" >&2; exit 1; }
  api="https://api.github.com/repos/$repo/releases?per_page=100"
  curl --fail --location --silent --show-error "$api" -o "$tmp/releases.json"
  python3 - "$tmp/releases.json" "$asset_name" "$expected_v010_sha256" > "$tmp/asset-info" <<'PY'
import json, sys
data = json.load(open(sys.argv[1], encoding="utf-8"))
wanted = sys.argv[2]
known_hash = sys.argv[3]
for release in data:
    assets = {a["name"].lower(): a["browser_download_url"] for a in release.get("assets", [])}
    actual_name = next((a["name"] for a in release.get("assets", []) if a["name"].lower() == wanted.lower()), None)
    if actual_name:
        archive_url = assets[actual_name.lower()]
        checksum_url = assets.get((actual_name + ".sha256").lower())
        # The first published Linux release predates checksum release assets. Pin
        # its verified archive hash until a checksum file is attached to the release.
        checksum_value = known_hash if not checksum_url and release["tag_name"] == "V2.3.2_Win11_._._LinuxV.0.1.0" else ""
        if not checksum_url and not checksum_value:
            continue
        print(release["tag_name"])
        print(archive_url)
        print(checksum_url or checksum_value)
        break
else:
    raise SystemExit("No GitHub release contains a supported Agentstrap Linux archive and checksum.")
PY
  mapfile -t asset_info < "$tmp/asset-info"
  version="${version:-${asset_info[0]}}"
  curl --fail --location --silent --show-error "${asset_info[1]}" -o "$tmp/$asset_name"
  if [[ "${asset_info[2]}" == https://* ]]; then
    curl --fail --location --silent --show-error "${asset_info[2]}" -o "$tmp/$asset_name.sha256"
  else
    printf '%s  %s\n' "${asset_info[2]}" "$asset_name" > "$tmp/$asset_name.sha256"
  fi
  (cd "$tmp" && sha256sum --check "$asset_name.sha256")
  local_archive="$tmp/$asset_name"
else
  [[ -f "$local_archive" ]] || { echo "Archive not found: $local_archive" >&2; exit 1; }
  version="${version:-local-$(date +%Y%m%d%H%M%S)}"
fi

# Reject absolute paths and parent traversal before extracting the archive.
python3 - "$local_archive" <<'PY'
import sys, tarfile
with tarfile.open(sys.argv[1], "r:gz") as archive:
    for member in archive.getmembers():
        parts = member.name.split("/")
        if member.name.startswith("/") or ".." in parts:
            raise SystemExit("Unsafe path found in installation archive")
PY

mkdir -p "$tmp/unpacked"
tar --no-same-owner -xzf "$local_archive" -C "$tmp/unpacked"
[[ -x "$tmp/unpacked/Agentstrap" ]] || { echo "Archive is missing the Agentstrap executable." >&2; exit 1; }
[[ -f "$tmp/unpacked/agentstrap.png" ]] || { echo "Archive is missing the Agentstrap icon." >&2; exit 1; }
for required_library in libSkiaSharp.so libHarfBuzzSharp.so; do
  [[ -f "$tmp/unpacked/$required_library" ]] || {
    echo "Archive is missing required Linux UI library: $required_library" >&2
    exit 1
  }
done

data_home="${XDG_DATA_HOME:-$HOME/.local/share}"
bin_dir="$HOME/.local/bin"
app_root="$data_home/agentstrap"
release_root="$app_root/releases"
mkdir -p "$release_root" "$bin_dir" "$data_home/applications" "$data_home/icons/hicolor/256x256/apps"

if [[ -e "$app_root/current" && ! -L "$app_root/current" ]]; then
  echo "Refusing to replace non-symlink path: $app_root/current" >&2; exit 1
fi
if [[ -e "$bin_dir/agentstrap" && ! -L "$bin_dir/agentstrap" ]]; then
  echo "Refusing to replace existing file: $bin_dir/agentstrap" >&2; exit 1
fi
if [[ -L "$bin_dir/agentstrap" ]]; then
  old_target="$(readlink -f "$bin_dir/agentstrap" || true)"
  app_root_real="$(readlink -f "$app_root" || printf '%s' "$app_root")"
  [[ "$old_target" == "$app_root_real/"* ]] || { echo "Refusing to replace unrelated symlink: $bin_dir/agentstrap" >&2; exit 1; }
fi
desktop="$data_home/applications/agentstrap-linux.desktop"
if [[ -e "$desktop" ]] && ! grep -q '^X-Agentstrap-Managed=true$' "$desktop"; then
  echo "Refusing to replace unrelated desktop entry: $desktop" >&2; exit 1
fi

safe_version="$(printf '%s' "$version" | tr -c 'A-Za-z0-9._-' '_')"
release_dir="$release_root/$safe_version"
if [[ -e "$release_dir" ]]; then release_dir="$release_root/${safe_version}-$(date +%s)"; fi
mkdir "$release_dir"
cp -a "$tmp/unpacked/." "$release_dir/"
chmod 755 "$release_dir/Agentstrap"
tmp_link="$app_root/.current.$$"
ln -s "$release_dir" "$tmp_link"
mv -Tf "$tmp_link" "$app_root/current"
ln -sfn "$app_root/current/Agentstrap" "$bin_dir/agentstrap"

python3 - "$desktop" "$bin_dir/agentstrap" <<'PY'
import sys
path, executable = sys.argv[1:]
escape = lambda value: value.replace("\\", "\\\\").replace('"', '\\"')
with open(path, "w", encoding="utf-8") as output:
    output.write("[Desktop Entry]\nType=Application\nName=Agentstrap Linux\nComment=Roblox experience library and launcher\n")
    output.write(f'Exec="{escape(executable)}"\nIcon=agentstrap-linux\nTerminal=false\nCategories=Game;Utility;\nX-Agentstrap-Managed=true\n')
PY
install -Dm644 "$release_dir/agentstrap.png" "$data_home/icons/hicolor/256x256/apps/agentstrap-linux.png"

echo "Agentstrap $version installed for this user."
case ":$PATH:" in *":$bin_dir:"*) ;; *) echo "Add $bin_dir to PATH to run 'agentstrap' from a terminal." ;; esac
echo "Launch it from your desktop menu or run: $bin_dir/agentstrap"
if ((launch)); then
  if [[ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ]]; then "$bin_dir/agentstrap" >/dev/null 2>&1 &
  else echo "No graphical session detected; start Agentstrap when you sign in."; fi
fi
