#!/usr/bin/env bash
# Deploy one commit of the fleet API to a target by release folders (deploy/release.sh on the box). Run on the PC in
# Git Bash:
#   bash deploy/deploy-from-pc.sh <target> [commit] [--cutover [--allow-dirty]] [--no-reload] [--yes]
# <target>: a file deploy/targets/<target>.sh (prod, uat). [commit]: default origin/<BRANCH> of the target.
# --cutover: once per box, the old git tree becomes releases/legacy-<date> and its path the link; the commit must be
# the code the box runs, with no file edited by hand (--allow-dirty: they stay in the legacy folder only).
# --no-reload: no php-fpm reload nor reverb restart after the switch (in busy hours the reload saturated the php-fpm
# pool, 2026-11-02); the workers move to the new folder within ~2 min, the probes wait for it.
# --yes: no question before going on.
# 1. fetch; the commit must be on GitHub
# 2. guard: the live release is an ancestor of the commit (cutover: the box's tree holds that commit's code); the PRs
#    in between and the files that need care (migrations, composer.lock, config, routes, .env.example) are listed
# 3. git archive of the commit, sha256, upload to /tmp on the box
# 4. release.sh on the box with the target's settings (build, dump + migrate if needed, switch, probes, rollback)
# 5. probes from the PC
# Output copy: ~/server-runs/fleet-deploy-<target>-<date>.txt
set -euo pipefail
say() { printf '\n=== %s\n' "$*"; }
stop() { printf 'STOP: %s\n' "$*"; exit 1; }
KIT=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
REPO=$(cd "$KIT/.." && pwd)
TARGET=""; COMMIT=""; CUTOVER=no; YES=no; DIRTY_OK=no; RELOAD=yes
for a in "$@"; do
    case "$a" in
        --cutover) CUTOVER=yes ;;
        --allow-dirty) DIRTY_OK=yes ;;
        --no-reload) RELOAD=no ;;
        --yes) YES=yes ;;
        -*) stop "unknown option $a" ;;
        *) if [ -z "$TARGET" ]; then TARGET=$a; else COMMIT=$a; fi ;;
    esac
done
[ -n "$TARGET" ] || stop "usage: deploy-from-pc.sh <target> [commit] [--cutover [--allow-dirty]] [--no-reload] [--yes]"
TF="$KIT/targets/$TARGET.sh"
[ -f "$TF" ] || stop "no target file $TF"
# shellcheck disable=SC1090
. "$TF"
for v in BOX BRANCH APP BASE STORAGE OWNER PHP FPM QRESTART_USER URL PROBES EXPECT; do
    [ -n "${!v:-}" ] || stop "$v is empty in $TF"
done
STAMP=$(date +%Y%m%d_%H%M%S)
mkdir -p ~/server-runs ~/server-runs/fleet-builds
LOG=~/server-runs/fleet-deploy-$TARGET-$STAMP.txt
exec > >(tee "$LOG") 2>&1
echo "output copy: $LOG"
SSH=(ssh -o BatchMode=yes -o ConnectTimeout=15 "$BOX")

say "1. commit"
cd "$REPO"
git fetch --quiet origin
SHA=$(git rev-parse --verify "${COMMIT:-origin/$BRANCH}^{commit}") || stop "unknown commit ${COMMIT:-origin/$BRANCH}"
git branch -r --contains "$SHA" | grep -q 'origin/' || stop "$SHA is not on GitHub: push it first"
echo "new: $SHA $(git log -1 --format='%ci %s' "$SHA" | cut -c1-110)"

say "2. guard"
if [ "$CUTOVER" = yes ]; then
    KIND=$("${SSH[@]}" "if [ -L '$APP' ]; then echo link; elif [ -d '$APP/.git' ]; then echo tree; else echo other; fi")
    [ "$KIND" = tree ] || stop "cutover: $APP on the box is a $KIND, not the old git tree"
    DIFF=$("${SSH[@]}" "sudo -u $OWNER git -C '$APP' cat-file -e '$SHA^{commit}' 2>/dev/null || { echo UNKNOWN; exit 0; }; sudo -u $OWNER env GIT_OPTIONAL_LOCKS=0 git -C '$APP' diff --stat '$SHA' HEAD -- . ':(exclude)storage' ':(exclude)bootstrap/cache' | tail -n 5")
    [ "$DIFF" != UNKNOWN ] || stop "cutover: the box does not know $SHA; give the commit its tree runs"
    [ -z "$DIFF" ] || { echo "$DIFF"; stop "cutover: the box runs other code than $SHA (lines above)"; }
    # Edits made by hand in the tree are not in any commit: the release would not carry them (storage and the
    # generated package manifests in bootstrap/cache aside).
    EDITED=$("${SSH[@]}" "sudo -u $OWNER env GIT_OPTIONAL_LOCKS=0 git -C '$APP' status --porcelain --untracked-files=no -- . ':(exclude)storage' ':(exclude)bootstrap/cache' | head -n 40")
    if [ -n "$EDITED" ]; then
        echo "files edited by hand in the tree (not in $SHA):"; echo "$EDITED" | sed 's/^/  /'
        [ "$DIRTY_OK" = yes ] || stop "cutover: these edits would be lost; commit them, or pass --allow-dirty to leave them in the legacy folder"
        echo "--allow-dirty: they stay in the legacy folder only"
    fi
    echo "the box's tree holds the code of $SHA (storage and bootstrap/cache aside): it becomes the legacy folder"
else
    LIVEP=$("${SSH[@]}" "readlink -e '$APP' || true")
    case "$LIVEP" in "$BASE/releases/"?*) ;; *) stop "$APP on the box is not a link into $BASE/releases (${LIVEP:-nothing}): cut over first" ;; esac
    LIVE=${LIVEP##*/}
    echo "live: $LIVE"
    if [[ "$LIVE" =~ ^[0-9a-f]{40}$ ]]; then
        [ "$LIVE" != "$SHA" ] || { echo "already live, nothing to do"; exit 0; }
        git cat-file -e "$LIVE^{commit}" 2>/dev/null || stop "live commit $LIVE unknown here: fetch, or ask"
        git merge-base --is-ancestor "$LIVE" "$SHA" || stop "live $LIVE is not an ancestor of $SHA: ask before deploying"
        echo "-- merges in between (first parent):"
        git log --first-parent --format='  %h %ci %s' "$LIVE..$SHA" | cut -c1-130
        CARE=$(git diff --name-only "$LIVE" "$SHA" -- database/migrations composer.lock config routes .env.example)
        [ -z "$CARE" ] || { echo "-- files that need care (migrations run with a dump first; new settings go in the shared .env first):"; echo "$CARE" | sed 's/^/  /'; }
    else
        echo "live is $LIVE (the legacy folder): no ancestry to check"
    fi
fi
if [ "$YES" != yes ]; then
    read -r -p "Deploy $SHA to $TARGET? Type yes: " ANSWER </dev/tty
    [ "$ANSWER" = yes ] || stop "not confirmed, nothing sent"
fi

say "3. archive"
if [ "${BUILD_ON_BOX:-no}" = yes ]; then
    # Built on the box from its own mirror of GitHub (seconds), instead of 24 MB sent from the PC (14 min on
    # 2026-10-29). The commit id pins the content: git checks every object it holds against its hash.
    [ -n "${REMOTE:-}" ] || stop "BUILD_ON_BOX=yes needs REMOTE in $TF"
    SUM=$("${SSH[@]}" "set -e
        cd /tmp
        M='$BASE/repo.git'
        sudo install -d -o $OWNER -g www-data -m 755 '$BASE'
        if [ ! -d \"\$M\" ]; then
            # auto: the origin of the old git tree (the legacy folder once the box is cut over).
            R='$REMOTE'
            if [ \"\$R\" = auto ]; then
                L=\$(ls -d '$BASE'/releases/legacy-*/.git 2>/dev/null | head -n 1)
                [ -n \"\$L\" ] || L=\"\$(readlink -e '$APP')/.git\"
                R=\$(sudo -u $OWNER git --git-dir=\"\$L\" remote get-url origin)
            fi
            sudo -u $OWNER git clone --mirror --quiet \"\$R\" \"\$M\"
        fi
        sudo -u $OWNER git -C \"\$M\" fetch --quiet --prune
        sudo -u $OWNER git -C \"\$M\" cat-file -e '$SHA^{commit}'
        sudo rm -f '/tmp/fleet-$SHA.tgz'
        sudo -u $OWNER git -C \"\$M\" archive --format=tar.gz -o '/tmp/fleet-$SHA.tgz' '$SHA'
        sha256sum '/tmp/fleet-$SHA.tgz' | cut -d' ' -f1") || stop "could not build the archive on the box from $REMOTE"
    echo "built on the box from its mirror of $REMOTE, sha256 $SUM"
else
    T=~/server-runs/fleet-builds/fleet-$SHA.tgz
    git -c core.autocrlf=false archive --format=tar.gz -o "$T" "$SHA"
    SUM=$(sha256sum "$T" | cut -d' ' -f1)
    echo "$(du -h "$T" | cut -f1)  sha256 $SUM, sending it (no progress shown)"
    ls -1t ~/server-runs/fleet-builds/fleet-*.tgz | tail -n +4 | xargs -r rm -f
    "${SSH[@]}" "cat > /tmp/fleet-$SHA.tgz" < "$T"
fi

say "4. release on the box"
RC=0
{ cat "$TF"; printf 'SHA=%s\nSUM=%s\nTARGET=%s\nCUTOVER=%s\nRELOAD=%s\nDEPLOYER=%s\n' "$SHA" "$SUM" "$TARGET" "$CUTOVER" "$RELOAD" "$(git config user.email || echo unknown)"; cat "$KIT/release.sh"; } \
    | "${SSH[@]}" 'f=$(mktemp) && cat > "$f" && bash "$f"; rc=$?; rm -f "$f"; exit $rc' || RC=$?

say "5. probes from the PC"
for p in $PROBES; do
    echo "  $p -> $(curl -s -m 20 -o /dev/null -w '%{http_code}' -H 'Accept: application/json' "$URL$p") (expected $EXPECT)"
done
[ "$RC" = 0 ] || stop "release.sh ended with $RC (see above)"
echo "deployed: $SHA to $TARGET"
