#!/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
#     ./deploy.sh --publish-s3-only   # publish to releases.steid.dev and nothing else
#
# 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. And a previous
# release older than 0.8.1 refuses to boot on ANY migration it does not know, so
# rolling back across a migration onto 0.8.0 or earlier never comes up.
#
# WHY --publish IS OFF BY DEFAULT. Deploying and publishing 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.
#
# WHERE A PUBLISH GOES, AND WHY IT IS TWO PLACES. Since 0.6.0 the release host
# is **https://releases.steid.dev** — an S3 bucket (`steid-releases`) behind
# CloudFront, which is what `install.sh` defaults to and what the control plane's
# cloud-init downloads from headlessly. Before that, releases came off this box:
# jpgill.dev is the author's own Steid instance and served its own artefacts, and
# every link handed out since 0.4.0 points there. So a publish writes both, and
# the box keeps its copy as a **mirror**. That mirror is temporary: it goes when
# milestone 2 of the control plane moves the author's instance onto the managed
# fleet and jpgill.dev stops being a hand-run box. See
# plans/decisions/0009-releases-from-releases-steid-dev.md.
#
# `--publish-s3-only` publishes to the releases host without touching this box at
# all — no deploy, no ssh, no mirror. That is the one to run when the box is
# somebody's live site and the release has nothing to do with it.
#
# THE PUBLISH CREDENTIAL IS A NAMED AWS PROFILE AND NEVER A VALUE. `--profile
# ${STEID_AWS_PROFILE:-steid}` on every call; the profile assumes a role into the
# Steid Cloud account and is configured on the operator's laptop. Nothing in this
# repository holds a key, an account id or a role ARN, and this repository is
# public.

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
DEPLOY=1
MIRROR=1
VERSION=""

# The releases host: bucket, public hostname, and the distribution in front of
# it. The distribution id is LOOKED UP by alias rather than written down —
# hard-coding it would mean this script silently publishes into the wrong (or a
# deleted) distribution after any rebuild of the estate, and the lookup is one
# call. --distribution, or STEID_RELEASES_DISTRIBUTION, skips it.
AWS_PROFILE_NAME="${STEID_AWS_PROFILE:-steid}"
RELEASES_BUCKET="${STEID_RELEASES_BUCKET:-steid-releases}"
RELEASES_HOST="${STEID_RELEASES_HOST:-releases.steid.dev}"
DISTRIBUTION="${STEID_RELEASES_DISTRIBUTION:-}"

# 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 ;;
        # Publish to the releases host and do nothing else: no deploy, no ssh,
        # no mirror. Separating these is the point — the mirror lives on a box
        # that is also a live website, and cutting a release must not need it.
        --publish-s3-only) PUBLISH=1; DEPLOY=0; MIRROR=0; shift ;;
        --no-mirror)  MIRROR=0; shift ;;
        --distribution) DISTRIBUTION="${2:?--distribution needs an id}"; shift 2 ;;
        -h|--help)    sed -n '2,19p' "$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"

# --- deploy, unless this run is only cutting a release ----------------------

if [ "$DEPLOY" = 0 ]; then
    say "not deploying (--publish-s3-only): this box is not touched"
else
    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
fi

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

if [ "$PUBLISH" = 1 ]; then

    # 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}"

    # --- the releases host: S3 behind CloudFront -----------------------------

    command -v aws >/dev/null 2>&1 || die "no aws CLI, and the releases host is S3.
  Install it, or pass --host/--no-mirror flags to publish only the mirror."

    say "publishing v${VERSION} to s3://${RELEASES_BUCKET} (profile ${AWS_PROFILE_NAME})"

    # An explicit content type on every object, and --no-guess-mime-type so the
    # CLI does not add one of its own. Python's mimetypes — which is what the
    # guess is — reports `.tar.gz` as type application/x-tar *with encoding gzip*,
    # and the CLI turns that into `Content-Encoding: gzip`. A browser then
    # silently gunzips the download, so the file on disk is a .tar wearing a
    # .tar.gz name and its sha256 no longer matches the .sha256 beside it. That
    # failure looks exactly like a tampered artefact, which is the one thing a
    # checksum exists to tell you about.
    for f in $FILES; do
        case "$f" in
            *.sha256) CT="text/plain" ;;
            *)        CT="application/gzip" ;;
        esac
        KEY="v${VERSION}/$(basename "$f")"
        aws --profile "$AWS_PROFILE_NAME" s3 cp "$f" "s3://${RELEASES_BUCKET}/${KEY}" \
            --no-guess-mime-type --content-type "$CT" --only-show-errors \
            || die "upload failed: ${KEY}"
        echo "    s3://${RELEASES_BUCKET}/${KEY}"
    done

    # install.sh sits at the root: the URL a stranger is handed is
    # https://<host>/install.sh and there is nowhere else for it.
    aws --profile "$AWS_PROFILE_NAME" s3 cp install.sh "s3://${RELEASES_BUCKET}/install.sh" \
        --no-guess-mime-type --content-type "text/x-shellscript" --only-show-errors \
        || die "upload failed: install.sh"
    echo "    s3://${RELEASES_BUCKET}/install.sh"

    # The distribution is found by its alias rather than written down here. An
    # id in the repository is a fact about one estate that rots the first time
    # the estate is rebuilt, and the wrong id means a publish that "succeeded"
    # and a host still serving the old install.sh.
    if [ -z "$DISTRIBUTION" ]; then
        DISTRIBUTION="$(aws --profile "$AWS_PROFILE_NAME" cloudfront list-distributions \
            --query "DistributionList.Items[?contains(Aliases.Items, '${RELEASES_HOST}')].Id | [0]" \
            --output text 2>/dev/null || true)"
    fi
    [ -n "$DISTRIBUTION" ] && [ "$DISTRIBUTION" != "None" ] \
        || die "no CloudFront distribution has the alias ${RELEASES_HOST}.
  Pass --distribution <id>, or set STEID_RELEASES_DISTRIBUTION."

    # The cache policy is CloudFront's managed CachingOptimized: up to 24 hours.
    # install.sh is overwritten on every publish, so without an invalidation the
    # world keeps installing the previous version for a day — and the version
    # prefix is invalidated too, because a re-upload of an artefact that already
    # existed has the same problem and costs nothing to cover. Invalidations are
    # free for the first 1,000 paths a month; these are two.
    say "invalidating /install.sh and /v${VERSION}/* on ${DISTRIBUTION}"
    INVALIDATION="$(aws --profile "$AWS_PROFILE_NAME" cloudfront create-invalidation \
        --distribution-id "$DISTRIBUTION" \
        --paths "/install.sh" "/v${VERSION}/*" \
        --query 'Invalidation.Id' --output text)" || die "could not create an invalidation"
    echo "    ${INVALIDATION}"
    # Waited for, not fired and forgotten: the verification below is worthless
    # against a cached copy of the previous publish.
    aws --profile "$AWS_PROFILE_NAME" cloudfront wait invalidation-completed \
        --distribution-id "$DISTRIBUTION" --id "$INVALIDATION" \
        || die "invalidation ${INVALIDATION} did not complete"

    # Fetched back over HTTPS rather than trusted from the bucket listing. What
    # matters is not that the bytes are in S3 but that the host serves them: the
    # bucket is private and reachable only through the distribution's origin
    # access control, and a policy that denies a prefix is a silent 403 rather
    # than an error at upload time.
    say "verifying the published URLs"
    for f in $FILES; do
        URL="https://${RELEASES_HOST}/v${VERSION}/$(basename "$f")"
        CODE="$(curl -s -o /dev/null -m 120 -w '%{http_code}' "$URL")"
        [ "$CODE" = "200" ] || die "published but not served: ${URL} (HTTP ${CODE}).
  Does the bucket policy let the distribution read this prefix?"
        echo "    ${CODE}  ${URL}"
    done
    CODE="$(curl -s -o /dev/null -m 30 -w '%{http_code}' "https://${RELEASES_HOST}/install.sh")"
    [ "$CODE" = "200" ] || die "published but not served: https://${RELEASES_HOST}/install.sh (HTTP ${CODE})"
    echo "    ${CODE}  https://${RELEASES_HOST}/install.sh"

    # --- the mirror on the author's own instance -----------------------------
    #
    # Temporary, and kept because every link handed out between 0.4.0 and 0.6.0
    # points at it. It needs ssh to a box that is also a live website, so it is
    # skippable on its own: --no-mirror, or --publish-s3-only.
    if [ "$MIRROR" = 1 ]; then
        say "mirroring v${VERSION} to ${HOST}:${DIST_DIR}"

        # 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
        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 for the same reason as above: the two
        # distribution blocks in /etc/caddy/Caddyfile are easy to not have
        # enabled, and a silent 404 there is the failure this checks for.
        say "verifying the mirrored 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 "mirrored 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 "mirrored but not served: https://${DOMAIN}/install.sh (HTTP ${CODE})"
        echo "    ${CODE}  https://${DOMAIN}/install.sh"
    else
        say "skipping the ${DOMAIN} mirror"
    fi

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