#!/usr/bin/env bash
#
# bootstrap-tower - the one file to copy onto a tower: it fetches everything
# else. Run it ON the tower, as the tower's user (ggs):
#
#   scp scripts/bootstrap-tower ggs@<tower>:        # from a machine with this repo
#   scp -3 ggs@10.11.12.111:.ssh/id_ed25519_deploy_gitea ggs@<tower>:.ssh/   # the key, via this machine
#   ssh ggs@<tower> bash bootstrap-tower [install-tower options]
#
# It needs the tower's deploy key for the Gitea (~/.ssh/id_ed25519_deploy_gitea,
# the same key tower 111 uses). Then it:
#   1. sets up ~/.ssh/config "Host gitea" (git.ggs-solutions.eu, port 2222) and
#      records the server's host key;
#   2. clones fwt_software and fwt_firmware side by side under ~/projects/fwt_2a/,
#      or brings existing clones up to date (fast-forward only);
#   3. runs software/scripts/install-tower with whatever options it was given
#      (e.g. --dry-run, --answers FILE).
#
# Nothing is overwritten: a checkout with local changes, or a directory that is
# not a clone, stops it with the reason.
#
set -euo pipefail

BASE="${FGC_BASE:-$HOME/projects/fwt_2a}"   # FGC_BASE: rehearse somewhere else
KEY="$HOME/.ssh/id_ed25519_deploy_gitea"
HOST=git.ggs-solutions.eu
PORT=2222

say() { printf '>> %s\n' "$*"; }
die() { printf 'bootstrap-tower: %s\n' "$*" >&2; exit 1; }

[[ $EUID -ne 0 ]] || die "run as the tower's user (ggs), not root"

for tool in git ssh ssh-keyscan; do
    command -v "$tool" >/dev/null || {
        say "installing git and the ssh client"
        sudo apt-get update -qq && sudo apt-get install -y -qq git openssh-client
        break
    }
done

# ---- the deploy key and the gitea alias ------------------------------------
[[ -r $KEY ]] || die "no deploy key at $KEY. Copy it from tower 111:
    scp -3 ggs@10.11.12.111:.ssh/id_ed25519_deploy_gitea ggs@<this tower>:.ssh/   (from your laptop)
(or put this tower's own key there, registered read-only on both repositories)"
chmod 600 "$KEY"
mkdir -p "$HOME/.ssh" && chmod 700 "$HOME/.ssh"
touch "$HOME/.ssh/config" && chmod 600 "$HOME/.ssh/config"
if ! grep -qE '^Host[[:space:]]+gitea([[:space:]]|$)' "$HOME/.ssh/config"; then
    say "adding 'Host gitea' to ~/.ssh/config"
    printf '\nHost gitea\n    Hostname %s\n    User git\n    Port %s\n    IdentityFile %s\n' \
        "$HOST" "$PORT" "$KEY" >> "$HOME/.ssh/config"
fi
if ! ssh-keygen -F "[$HOST]:$PORT" >/dev/null 2>&1; then
    say "recording the host key of $HOST:$PORT"
    ssh-keyscan -p "$PORT" "$HOST" 2>/dev/null >> "$HOME/.ssh/known_hosts"
    ssh-keygen -F "[$HOST]:$PORT" -l | sed 's/^/   /'
fi
git ls-remote gitea:GGS/fwt_software.git >/dev/null 2>&1 ||
    die "the deploy key cannot read gitea:GGS/fwt_software.git - is port $PORT reachable from here, and is the key registered on the repository?"

# ---- both repositories, side by side ----------------------------------------
fetch() {   # repo-name directory
    local repo="$1" dir="$BASE/$2"
    if [[ -d $dir/.git ]]; then
        [[ -z $(git -C "$dir" status --porcelain) ]] ||
            die "$dir has local changes; commit or set them aside first"
        say "updating $dir"
        git -C "$dir" pull --ff-only -q
    elif [[ -e $dir ]]; then
        die "$dir exists but is not a git clone (a tree copied by deploy.sh?). Move it aside, then run this again."
    else
        say "cloning $repo into $dir"
        git clone -q "gitea:GGS/$repo.git" "$dir"
    fi
    say "  $2 at $(git -C "$dir" log --oneline -1)"
}
mkdir -p "$BASE"
fetch fwt_software software
fetch fwt_firmware firmware

# ---- the installer ---------------------------------------------------------
# It runs from the software checkout, so a file named relative to where this was
# started (--answers staeffelsberg.answers) is made absolute first.
args=()
while [[ $# -gt 0 ]]; do
    args+=("$1")
    if [[ $1 == --answers && $# -gt 1 ]]; then
        shift
        [[ $1 == /* ]] && args+=("$1") || args+=("$PWD/$1")
    fi
    shift
done
say "starting the installer"
cd "$BASE/software"
exec scripts/install-tower "${args[@]}"
