#!/usr/bin/env bash
# Deploy a build of Steid to a running instance.
#
#     ./deploy.sh                     # build, upload, upgrade, verify
#     ./deploy.sh --skip-build        # use whatever is already in dist/
#     ./deploy.sh --host steid --domain jpgill.dev
#     ./deploy.sh --publish           # also publish dist/ for strangers to download
#
# This is the operator's script, not the stranger's — `install.sh` is what someone
# else runs to install Steid for the first time. This one assumes an instance
# already exists and you want it running a newer build.
#
# WHY IT DOES MORE THAN scp-AND-RUN. An upgrade replaces the binary of a live
# service. Three things can go wrong and each is silent: the new build might not
# boot, the state might not survive, and a mistake leaves nothing to go back to.
# So it snapshots the database and the current binary first, upgrades, then
# *checks the site actually works* — and restores if it does not.
#
# MIGRATIONS RUN THEMSELVES, ON BOOT, AND THIS SCRIPT CANNOT UNDO THEM. The
# rollback below restores the binary, never the schema — so a migration that the
# previous release cannot read leaves a rolled-back instance broken. Expand,
# deploy, contract: see "Migrations" in plans/architecture.md.
#
# WHY --publish IS OFF BY DEFAULT. This box has two jobs: it runs jpgill.dev, and
# it is the host every `install.sh` downloads from. Those are not the same event.
# A deploy happens whenever a build is worth running; a publish changes what
# strangers get, permanently and for a version number that can never be re-cut.
# Publishing on every deploy would put half-finished builds behind a version
# other people install, and would publish only the one architecture a deploy
# happens to have built. So it is opt-in — and, so it stops being forgotten, it
# is one flag on the command that was going to be run anyway.

set -euo pipefail

HOST="steid"                  # an ssh alias or user@address
DOMAIN="jpgill.dev"
TARGET="x86_64-unknown-linux-gnu"
SKIP_BUILD=0
PUBLISH=0
VERSION=""

# Where the artefacts are served from on the box. NOT under /var/lib/steid: that
# directory is the instance's state and its whole backup surface — the snapshot
# below tars it on every deploy, so release tarballs living there would be copied
# into every backup forever. It is also mode 750 steid:steid, and Caddy runs as
# `caddy`, so serving from inside it would mean loosening the directory that
# protects steid.db. Caddy's `handle_path` blocks point here; see deploy/Caddyfile.
DIST_DIR="/srv/steid-dist"

die() { echo "deploy.sh: $*" >&2; exit 1; }
say() { echo "==> $*"; }

while [ $# -gt 0 ]; do
    case "$1" in
        --host)       HOST="${2:?--host needs a value}"; shift 2 ;;
        --domain)     DOMAIN="${2:?--domain needs a value}"; shift 2 ;;
        --target)     TARGET="${2:?--target needs a triple}"; shift 2 ;;
        --version)    VERSION="${2:?--version needs a value}"; shift 2 ;;
        --skip-build) SKIP_BUILD=1; shift ;;
        --publish)    PUBLISH=1; shift ;;
        -h|--help)    sed -n '2,18p' "$0" | sed 's/^#\{1,2\} \{0,1\}//'; exit 0 ;;
        *) die "unknown argument: $1" ;;
    esac
done

cd "$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)"

[ -n "$VERSION" ] || VERSION="$(grep -m1 '^version *= *"' Cargo.toml | sed 's/.*"\(.*\)".*/\1/')"
NAME="steid-${VERSION}-${TARGET}"
TARBALL="dist/${NAME}.tar.gz"

# Refuse to deploy a working tree that is not what is committed. The instance
# should always be running a commit you can point at, or debugging it later means
# guessing what was on the machine that built it.
if [ -n "$(git status --porcelain)" ]; then
    die "working tree is dirty — commit first, so the deployed build has a commit to name"
fi
COMMIT="$(git rev-parse --short HEAD)"

if [ "$SKIP_BUILD" = 0 ]; then
    say "building ${NAME} from ${COMMIT}"
    ./release.sh --target "$TARGET" --version "$VERSION" >/dev/null
else
    say "skipping build (--skip-build)"
fi
[ -f "$TARBALL" ] || die "no ${TARBALL} — build it, or drop --skip-build"

say "checking the instance is reachable"
ssh -o BatchMode=yes "$HOST" true || die "cannot ssh to ${HOST}"

# --- snapshot, so there is something to go back to --------------------------

STAMP="$(date +%Y%m%d-%H%M%S)"
say "snapshotting state and the current binary (${STAMP})"
ssh -o BatchMode=yes "$HOST" "
    set -e
    sudo mkdir -p /var/backups/steid
    sudo tar czf /var/backups/steid/state-${STAMP}.tar.gz -C /var/lib steid
    sudo tar czf /var/backups/steid/binary-${STAMP}.tar.gz -C /opt steid
    sudo find /var/backups/steid -name '*.tar.gz' -mtime +14 -delete
"

# --- upgrade ----------------------------------------------------------------

say "uploading"
scp -q -o BatchMode=yes "$TARBALL" "${TARBALL}.sha256" install.sh "${HOST}:"

say "upgrading"
ssh -o BatchMode=yes "$HOST" "sudo sh ./install.sh --domain '${DOMAIN}' --tarball './${NAME}.tar.gz'" \
    | grep -E '^==>|is running' || true

# --- verify, and roll back if it is not actually serving --------------------

say "verifying https://${DOMAIN}"
OK=0
for _ in $(seq 1 15); do
    sleep 2
    if [ "$(curl -s -o /dev/null -m 10 -w '%{http_code}' "https://${DOMAIN}/healthz")" = "200" ]; then
        OK=1; break
    fi
done

if [ "$OK" = 1 ]; then
    say "healthy — ${VERSION} (${COMMIT}) is live at https://${DOMAIN}"
    ssh -o BatchMode=yes "$HOST" "systemctl is-active steid caddy | paste -sd' ' -" | sed 's/^/    steid caddy: /'
else
    echo "deploy.sh: the new build is NOT serving. Rolling back." >&2
    ssh -o BatchMode=yes "$HOST" "
        set -e
        sudo systemctl stop steid
        sudo rm -rf /opt/steid
        sudo tar xzf /var/backups/steid/binary-${STAMP}.tar.gz -C /opt
        sudo systemctl start steid
    "
    sleep 4
    ROLLED="$(curl -s -o /dev/null -m 10 -w '%{http_code}' "https://${DOMAIN}/healthz")"
    echo "deploy.sh: rolled back to the previous binary (healthz ${ROLLED})." >&2
    echo "deploy.sh: state was NOT restored — the database is untouched by an upgrade," >&2
    echo "  and /var/backups/steid/state-${STAMP}.tar.gz holds it if you need it." >&2
    exit 1
fi

# --- publish, so the release the box is running is the one strangers get -----

if [ "$PUBLISH" = 1 ]; then
    say "publishing v${VERSION} to ${HOST}:${DIST_DIR}"

    # Every target install.sh can ask for, which is what `release.sh --all`
    # builds. A missing one is not fatal — publishing the architecture you have
    # beats publishing nothing — but it is called out, because the failure lands
    # on a stranger as a 404 halfway through an install that looked fine, and it
    # reads as a broken host rather than a missing file.
    PUBLISH_TARGETS="x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu"
    FILES=""
    for t in $PUBLISH_TARGETS; do
        f="dist/steid-${VERSION}-${t}.tar.gz"
        if [ -f "$f" ] && [ -f "${f}.sha256" ]; then
            FILES="${FILES} ${f} ${f}.sha256"
        else
            echo "deploy.sh: no ${f} — anyone whose 'uname -m' picks ${t} gets a 404." >&2
            echo "  Build it first: ./release.sh --target ${t} --version ${VERSION}" >&2
        fi
    done
    [ -n "$FILES" ] || die "nothing to publish for ${VERSION}"

    # Upload to the login user's home, then `sudo install` into place: the served
    # directory is root-owned and scp cannot elevate. `install` rather than `mv`
    # so the mode is stated outright instead of inherited from whatever umask the
    # upload happened to run under — these files are world-readable on purpose.
    # shellcheck disable=SC2086  # FILES is a deliberate word-split list.
    scp -q -o BatchMode=yes $FILES install.sh "${HOST}:"
    REMOTE="set -e; sudo install -d -m 755 -o root -g root ${DIST_DIR}/v${VERSION};"
    for f in $FILES; do
        REMOTE="${REMOTE} sudo install -m 644 -o root -g root ./$(basename "$f") ${DIST_DIR}/v${VERSION}/;"
    done
    # install.sh sits at the root of the served directory: the URL a stranger is
    # handed is https://<domain>/install.sh and there is nowhere else for it.
    REMOTE="${REMOTE} sudo install -m 644 -o root -g root ./install.sh ${DIST_DIR}/install.sh"
    ssh -o BatchMode=yes "$HOST" "$REMOTE"

    # Fetched back over HTTPS rather than trusted from the filesystem. What
    # matters is not that the bytes are on the box but that Caddy serves them,
    # and the two distribution blocks in /etc/caddy/Caddyfile are easy to not
    # have enabled — a silent 404 there is the failure this flag exists to stop.
    say "verifying the published URLs"
    for f in $FILES; do
        URL="https://${DOMAIN}/jamesgill/repos/steid/releases/v${VERSION}/$(basename "$f")"
        CODE="$(curl -s -o /dev/null -m 60 -w '%{http_code}' "$URL")"
        [ "$CODE" = "200" ] || die "published but not served: ${URL} (HTTP ${CODE}).
  Are the distribution handle_path blocks in /etc/caddy/Caddyfile? See deploy/Caddyfile."
        echo "    ${CODE}  ${URL}"
    done
    CODE="$(curl -s -o /dev/null -m 30 -w '%{http_code}' "https://${DOMAIN}/install.sh")"
    [ "$CODE" = "200" ] || die "published but not served: https://${DOMAIN}/install.sh (HTTP ${CODE})"
    echo "    ${CODE}  https://${DOMAIN}/install.sh"

    say "published. A stranger now installs this version with:"
    echo "    curl -fsSL https://${DOMAIN}/install.sh | sh -s -- --domain <their-host> --version ${VERSION}"
fi
