#!/usr/bin/env bash
# Deploy Mfuko to a cPanel account over SSH.
#
#   scripts/deploy/deploy.sh [target] [command]
#
#   target   a file in scripts/deploy/targets/ without .conf (default: staging)
#   command  deploy        build the committed HEAD and release it (default)
#            rollback      point the site back at the previous release
#            status        list releases on the server and show the live one
#            install-cron  add the scheduler and queue cron jobs (once per target)
#
# Only committed code ships: the release is built from `git archive HEAD`, never the working tree.
# Assets are built here (the server has no Node on PATH); Composer runs on the server.
set -euo pipefail

TARGET=${1:-staging}
COMMAND=${2:-deploy}

APP_ROOT=$(cd "$(dirname "$0")/../.." && pwd)
REPO_ROOT=$(git -C "$APP_ROOT" rev-parse --show-toplevel)
APP_PREFIX=$(git -C "$APP_ROOT" rev-parse --show-prefix) # e.g. apps/laravel/
CONF="$APP_ROOT/scripts/deploy/targets/$TARGET.conf"
REMOTE_SCRIPT="$APP_ROOT/scripts/deploy/remote.sh"

[[ -f $CONF ]] || { echo "No target config: $CONF" >&2; exit 1; }
# shellcheck source=/dev/null
source "$CONF"

say() { printf '\n\033[1;34m==> %s\033[0m\n' "$*"; }

REMOTE_ENV="APP_DIR='$APP_DIR' WEB_LINK='$WEB_LINK' PHP='$PHP' COMPOSER_BIN='$COMPOSER_BIN' KEEP_RELEASES='$KEEP_RELEASES'"

# Copies remote.sh to the server, then runs it with the target's settings. The caller's stdin goes to it.
remote() {
    ssh "$SSH_HOST" "mkdir -p '$APP_DIR' && cat > '$APP_DIR/remote.sh'" < "$REMOTE_SCRIPT"
    ssh "$SSH_HOST" "$REMOTE_ENV bash '$APP_DIR/remote.sh' $*"
}

case $COMMAND in
    status | rollback | install-cron)
        remote "$COMMAND" < /dev/null
        exit
        ;;
    deploy) ;;
    *)
        echo "Unknown command: $COMMAND" >&2
        exit 1
        ;;
esac

SHA=$(git -C "$REPO_ROOT" rev-parse --short HEAD)
RELEASE="$(date -u +%Y%m%d%H%M%S)-$SHA"

if [[ -n $(git -C "$REPO_ROOT" status --porcelain -- "$APP_PREFIX") ]]; then
    echo "Note: uncommitted changes in $APP_PREFIX are NOT deployed; shipping HEAD ($SHA)."
fi

say "Checking SSH to $SSH_HOST"
ssh -o BatchMode=yes -o ConnectTimeout=15 "$SSH_HOST" true

BUILD=$(mktemp -d "${TMPDIR:-/tmp}/mfuko-build.XXXXXX")
BUNDLE="$BUILD.tar.gz"
trap 'rm -rf "$BUILD" "$BUNDLE"' EXIT

say "Exporting $SHA"
git -C "$REPO_ROOT" archive --format=tar "HEAD:${APP_PREFIX%/}" | tar -x -C "$BUILD"
echo "$SHA" > "$BUILD/REVISION"

say "Building assets"
(
    cd "$BUILD"
    # Wayfinder generates the route helpers at build time by booting the app and reading model columns,
    # so the build needs vendor, a key and a migrated database: a throwaway SQLite file, as in CI.
    composer install --no-dev --no-interaction --prefer-dist --no-progress --quiet
    cp .env.example .env
    php artisan key:generate --no-interaction --quiet
    export DB_CONNECTION=sqlite DB_DATABASE="$BUILD/database/build.sqlite"
    touch "$DB_DATABASE"
    php artisan migrate --force --no-interaction --quiet
    npm ci --no-audit --no-fund --loglevel=error
    npm run build
)

say "Packing release"
# COPYFILE_DISABLE and --no-xattrs keep macOS metadata (._ files, xattr headers) out of the bundle.
COPYFILE_DISABLE=1 tar --no-xattrs -C "$BUILD" -czf "$BUNDLE" \
    --exclude='./node_modules' --exclude='./packages/*/*/node_modules' \
    --exclude='./vendor' --exclude='./.env' --exclude='./storage' \
    --exclude='./tests' --exclude='./.github' --exclude='./public/hot' --exclude='./database/build.sqlite' \
    --exclude='./bootstrap/cache/*.php' .
du -h "$BUNDLE" | awk '{print "Bundle: " $1}'

say "Uploading and activating $RELEASE"
remote deploy "$RELEASE" < "$BUNDLE"

if [[ -n ${HEALTH_URL:-} ]]; then
    say "Health check $HEALTH_URL"
    code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 "$HEALTH_URL" || true)
    if [[ $code == 200 ]]; then
        echo "OK ($code)"
    else
        echo "Health check returned $code. Roll back with: scripts/deploy/deploy.sh $TARGET rollback" >&2
        exit 1
    fi
fi

say "Deployed $SHA to $TARGET"
