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

REPOSITORY=https://github.com/weber21w/uzenet-main.git
CHECKOUT="${HOME}/uzenet-server"
usage(){
 cat <<'EOF'
Download this script, inspect it, then run:
  bash install-server.sh [--checkout DIRECTORY] --domain YOUR_DOMAIN --cert-email YOUR_EMAIL

Clones or fast-forwards the official main branch, then runs install-uzenet-core.sh.
Requires Git and an Ubuntu server supported by the core installer. The installer
requests sudo access. DNS and firewall rules must already point at this machine.
Use --no-www if you only have the primary hostname. Other options are passed to
the core installer. Local changes, different origins, and divergent history stop
the update. This does not join a federation or inherit the hosting site's trust.
EOF
}
die(){ printf 'ERROR: %s\n' "$*" >&2; exit 1; }
if [[ $# -eq 0 || "$1" == --help || "$1" == -h ]]; then usage; exit 0; fi
if [[ "$1" == --checkout ]]; then
 [[ $# -ge 3 && -n "$2" ]] || die '--checkout needs a directory and installer options'
 CHECKOUT="$2"
 shift 2
fi
command -v git >/dev/null || die 'Install Git first: sudo apt-get install git'
CHECKOUT="$(realpath -m -- "$CHECKOUT")"
if [[ -e "$CHECKOUT" ]]; then
 [[ -d "$CHECKOUT/.git" ]] || die 'Checkout directory exists but is not a Git checkout'
 [[ "$(git -C "$CHECKOUT" remote get-url origin)" == "$REPOSITORY" ]] || die 'Checkout origin is not the official repository'
 [[ "$(git -C "$CHECKOUT" symbolic-ref --short HEAD)" == main ]] || die 'Checkout must be on main'
 [[ -z "$(git -C "$CHECKOUT" status --porcelain)" ]] || die 'Checkout has local changes; preserve them before updating'
 git -C "$CHECKOUT" pull --ff-only origin main
else
 git clone --branch main --single-branch "$REPOSITORY" "$CHECKOUT"
fi
[[ -f "$CHECKOUT/install-uzenet-core.sh" ]] || die 'The public repository does not contain the server installer yet. No server installation was started.'
printf 'Installing UzeNet revision: %s\n' "$(git -C "$CHECKOUT" rev-parse HEAD)"
cd "$CHECKOUT"
exec bash ./install-uzenet-core.sh "$@"
