#!/bin/sh
# Mirasim's apt source: the ONE writer of /etc/apt/sources.list.d/mirasim.list (T-1871).
#
#   mirasim-apt source  <stable|beta|preview>               point the source at a suite
#   mirasim-apt upgrade <stable|beta|preview> [--reinstall]  …then install the newest Mirasim in it
#
# Both need root. The deb's postinst runs `source` (unless /etc/default/mirasim sets
# repo_add=false); the app runs `upgrade` through pkexec when its update button is pressed on a
# deb install, naming the suite of the update line the user follows (stable → stable, beta →
# beta, a project-team member's internal line → preview). Everything is fetched by apt itself,
# which verifies the suite's InRelease against the keyring beside this script — the trust root a
# downloaded .deb never had (electron/updates.ts, installLinux).
#
# This directory holds the two facts it needs, both put there at packaging time: the archive
# keyring (mirasim-archive-keyring.gpg, from the repo) and the archive root (repo-url, the
# directory of the build's update feed, written by scripts/after-pack.mjs). A build without
# either (a dev or test package) registers nothing.
#
# Exit codes the app reads (electron/apt-update.ts): 3 not set up here (no keyring/URL, or the
# source was removed by the admin), 4 the suite could not be fetched (the previous source is put
# back), 64 usage, 77 not root; anything else is apt-get's own.
set -eu

LIST=/etc/apt/sources.list.d/mirasim.list
PKG=mirasim
here=$(dirname "$(readlink -f "$0")")
KEYRING="$here/mirasim-archive-keyring.gpg"
URL_FILE="$here/repo-url"

die() {
  echo "mirasim-apt: $2" >&2
  exit "$1"
}

cmd=${1:-}
suite=${2:-}
reinstall=${3:-}
case "$cmd" in source | upgrade) ;; *) die 64 "usage: mirasim-apt source|upgrade stable|beta|preview [--reinstall]" ;; esac
case "$suite" in stable | beta | preview) ;; *) die 64 "unknown suite '$suite' (stable, beta or preview)" ;; esac
case "$reinstall" in '' | --reinstall) ;; *) die 64 "unknown option '$reinstall'" ;; esac
[ "$(id -u)" -eq 0 ] || die 77 "must run as root"
[ -s "$KEYRING" ] || die 3 "this build carries no archive keyring"
[ -s "$URL_FILE" ] || die 3 "this build carries no archive URL"
url=$(head -n 1 "$URL_FILE")
case "$url" in https://*) ;; *) die 3 "archive URL is not https: $url" ;; esac
case "$url" in *[!A-Za-z0-9./:_-]*) die 3 "unexpected characters in the archive URL" ;; esac
case "$here" in *[!A-Za-z0-9./_-]*) die 3 "unexpected characters in the install path: $here" ;; esac

write_source() {
  tmp="$LIST.tmp.$$"
  {
    echo "# Mirasim desktop updates — written by $here/mirasim-apt, removed with the package."
    echo "# To keep it from being added back on the next install, set repo_add=false in /etc/default/mirasim."
    echo "deb [arch=amd64,arm64 signed-by=$KEYRING] $url $suite main"
  } >"$tmp"
  chmod 0644 "$tmp"
  mv -f "$tmp" "$LIST"
}

if [ "$cmd" = source ]; then
  [ -d "$(dirname "$LIST")" ] || die 3 "no $(dirname "$LIST") here"
  write_source
  exit 0
fi

# upgrade: never re-adds a source the admin removed — that is what `source` on install is for.
[ -f "$LIST" ] || die 3 "the Mirasim apt source is not registered ($LIST)"
prev=$(mktemp)
log=$(mktemp)
cp -p "$LIST" "$prev"
write_source
# Refresh OUR source only: quick, and an unrelated broken repository cannot fail this update.
# apt-get update exits 0 on a BAD SIGNATURE (a warning; it keeps the old index), so any W:/E:
# line fails it too — only our source is in play, so every such line is about it.
# Error-Mode=any says the same to an apt that knows it (2.1.16+); older ones ignore the key.
if ! apt-get update -o Dir::Etc::sourcelist="$LIST" -o Dir::Etc::sourceparts=- -o APT::Get::List-Cleanup=0 \
  -o APT::Update::Error-Mode=any >"$log" 2>&1 || grep -qE '^(W|E):' "$log"; then
  cat "$log" >&2
  rm -f "$log"
  cp -p "$prev" "$LIST"
  rm -f "$prev"
  die 4 "could not fetch the $suite suite from $url"
fi
cat "$log"
rm -f "$log" "$prev"
set -- -y -o DPkg::Lock::Timeout=120 -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold
if [ "$reinstall" = --reinstall ]; then
  DEBIAN_FRONTEND=noninteractive exec apt-get "$@" install --reinstall "$PKG"
fi
# --only-upgrade: never installs what is not there, never moves back (a suite behind the
# installed build — a beta install on the stable source — is a no-op, not a downgrade).
DEBIAN_FRONTEND=noninteractive exec apt-get "$@" install --only-upgrade "$PKG"
