#!/usr/bin/env bash
# Ajna installer for Debian/Ubuntu amd64 and arm64. Review before running.
set -euo pipefail
fail() { printf 'Ajna: %s\n' "$*" >&2; exit 1; }
[ "$(uname -s)" = Linux ] || fail 'This installer requires Linux.'
case "$(uname -m)" in
  x86_64|amd64) package_arch=amd64 ;;
  aarch64|arm64) package_arch=arm64 ;;
  *) fail "Ajna DEB supports amd64 and arm64; detected $(uname -m)." ;;
esac
package_file="ajna_latest_linux_${package_arch}.deb"
for tool in curl sha256sum dpkg-deb dpkg apt-get mktemp; do
  command -v "$tool" >/dev/null 2>&1 || fail "Missing $tool. Install it on Debian/Ubuntu and retry."
done
[ "$(dpkg --print-architecture)" = "$package_arch" ] || fail "The Debian/Ubuntu userspace must use $package_arch to match this system."
if [ "$(id -u)" -ne 0 ]; then
  command -v sudo >/dev/null 2>&1 || fail 'sudo is required; install sudo or run as root.'
fi
work_dir="$(mktemp -d)"
trap 'rm -rf -- "$work_dir"' EXIT
release_url='https://gitcode.com/fablesol/ajna/releases/download/latest'
printf 'Downloading Ajna and checksum manifest...\n'
curl --fail --show-error --silent --location --proto '=https' --proto-redir '=https' --retry 3 "$release_url/$package_file" -o "$work_dir/$package_file"
curl --fail --show-error --silent --location --proto '=https' --proto-redir '=https' --retry 3 "$release_url/SHA256SUMS" -o "$work_dir/SHA256SUMS"
expected="$(awk -v file="$package_file" '$2 == file || $2 == "*" file || $2 == "./" file {print $1}' "$work_dir/SHA256SUMS")"
[[ "$expected" =~ ^[[:xdigit:]]{64}$ ]] || fail 'Missing or ambiguous checksum in SHA256SUMS.'
actual="$(sha256sum "$work_dir/$package_file")"
[ "${actual%% *}" = "${expected,,}" ] || fail 'SHA256 verification failed. Nothing was installed; retry after release completes.'
[ "$(dpkg-deb -f "$work_dir/$package_file" Architecture)" = "$package_arch" ] || fail 'Downloaded package architecture does not match this system.'
[ "$(dpkg-deb -f "$work_dir/$package_file" Package)" = ajna ] || fail 'Downloaded package is not Ajna.'
# apt drops privileges to _apt while reading local packages.
chmod 755 "$work_dir"
chmod 644 "$work_dir/$package_file"
printf 'Checksum verified. Installing Ajna (administrator access required)...\n'
if [ "$(id -u)" -eq 0 ]; then
  apt-get install -y "$work_dir/$package_file"
else
  sudo apt-get install -y "$work_dir/$package_file" </dev/tty
fi
printf 'Ajna installed. Open it from the application menu, or run: ajna\n'
