#!/usr/bin/env bash
# Server half of scripts/deploy/deploy.sh. It is uploaded and run on each deploy; don't run it by hand.
#
# Layout under ~/$APP_DIR:
#   releases/<utc-time>-<sha>/   one directory per deploy
#   current -> releases/...      the live release (switched atomically)
#   shared/.env, shared/storage  kept across releases and linked into each one
# ~/$WEB_LINK is a symlink to current, so the domain's document root (WEB_LINK/public) follows it.
set -euo pipefail
cd ~

: "${APP_DIR:?}" "${WEB_LINK:?}" "${PHP:?}" "${COMPOSER_BIN:?}" "${KEEP_RELEASES:=5}"
BASE="$HOME/$APP_DIR"
SHARED="$BASE/shared"
WEB="$HOME/$WEB_LINK"

say() { printf '  - %s\n' "$*"; }
artisan() { "$PHP" artisan --no-interaction "$@" < /dev/null; }

live_release() { [[ -L $BASE/current ]] && basename "$(readlink "$BASE/current")" || true; }

switch_to() { # Atomically point current at a release; on first deploy, replace the hand-uploaded web dir.
    ln -sfn "releases/$1" "$BASE/current.new"
    mv -Tf "$BASE/current.new" "$BASE/current"
    if [[ ! -L $WEB ]]; then
        if [[ -e $WEB ]]; then
            local backup="$BASE/pre-deploy-$(date -u +%Y%m%d%H%M%S)"
            mv "$WEB" "$backup"
            say "moved the previous copy of ~/$WEB_LINK to $backup"
        fi
        ln -s "$BASE/current" "$WEB"
    fi
}

case ${1:-} in
deploy)
    RELEASE=${2:?release name}
    DIR="$BASE/releases/$RELEASE"
    mkdir -p "$BASE/releases"

    mkdir "$BASE/.lock" 2> /dev/null || { echo "Another deploy is running (remove ~/$APP_DIR/.lock if not)." >&2; exit 1; }
    ok=0
    trap '[[ $ok == 1 ]] || rm -rf "$DIR"; rmdir "$BASE/.lock"' EXIT

    say "unpacking"
    mkdir "$DIR"
    tar -xzf - -C "$DIR"

    # Shared state. On the first deploy it is taken from the copy currently served at WEB_LINK.
    mkdir -p "$SHARED"
    if [[ ! -e $SHARED/.env ]]; then
        if [[ -f $WEB/.env && ! -L $WEB ]]; then
            cp -p "$WEB/.env" "$SHARED/.env"
            say "copied .env from ~/$WEB_LINK"
        else
            echo "Missing $SHARED/.env: create it (cp .env.example, set APP_KEY, APP_URL, DB_*, MAIL_*) and deploy again." >&2
            exit 1
        fi
    fi
    if [[ ! -e $SHARED/storage ]]; then
        if [[ -d $WEB/storage && ! -L $WEB ]]; then
            cp -a "$WEB/storage" "$SHARED/storage"
            say "copied storage from ~/$WEB_LINK"
        fi
    fi
    mkdir -p "$SHARED"/storage/{app/public,app/private,framework/cache/data,framework/sessions,framework/views,logs}
    ln -sfn "$SHARED/.env" "$DIR/.env"
    ln -sfn "$SHARED/storage" "$DIR/storage"
    chmod 755 "$DIR"

    cd "$DIR"
    # Start from the live release's vendor so Composer only applies what changed. The account's disk
    # write limit makes a full copy take minutes, so package files are hard-linked: Composer replaces
    # a changed package with new files and leaves the linked originals alone. The files it rewrites in
    # place (vendor/composer, autoload.php, bin proxies) are copied for real, so the old release stays
    # intact for rollback. Path-package symlinks in vendor are relative and resolve inside this release.
    from=""
    if [[ -d $BASE/current/vendor ]]; then
        from="$BASE/current/vendor"
    elif [[ -d $WEB/vendor && ! -L $WEB ]]; then
        from="$WEB/vendor"
    fi
    if [[ -n $from ]]; then
        cp -al "$from" vendor
        rm -rf vendor/composer vendor/bin vendor/autoload.php
        cp -a "$from/composer" vendor/composer
        [[ -d $from/bin ]] && cp -a "$from/bin" vendor/bin
        cp -p "$from/autoload.php" vendor/autoload.php
    fi
    say "composer install"
    COMPOSER_MEMORY_LIMIT=-1 "$PHP" "$COMPOSER_BIN" install --no-dev --optimize-autoloader \
        --no-interaction --prefer-dist --no-progress --quiet < /dev/null

    say "migrations"
    artisan migrate --force
    if grep -qE '^TENANCY_MODE=("?)database\1$' .env; then
        artisan tenants:migrate --force
    fi

    say "caches and storage link"
    artisan storage:link --force > /dev/null
    artisan optimize > /dev/null

    say "switching live release to $RELEASE"
    switch_to "$RELEASE"
    ok=1
    artisan queue:restart > /dev/null

    # Keep the newest releases; never remove the live one.
    live=$(live_release)
    ls -1 "$BASE/releases" | sort -r | tail -n +$((KEEP_RELEASES + 1)) | while read -r old; do
        [[ $old == "$live" ]] || rm -rf "${BASE:?}/releases/$old"
    done

    crontab -l 2> /dev/null | grep -q "$APP_DIR/current" ||
        echo "  ! No cron jobs yet: the scheduler and queue won't run. Run: scripts/deploy/deploy.sh <target> install-cron"
    ;;

rollback)
    live=$(live_release)
    previous=$(ls -1 "$BASE/releases" | sort -r | grep -A1 -x "$live" | sed -n 2p)
    [[ -n $previous ]] || { echo "No release older than $live to roll back to." >&2; exit 1; }
    switch_to "$previous"
    cd "$BASE/current" && artisan queue:restart > /dev/null
    say "live release is now $previous (was $live). Database migrations were not reversed."
    ;;

status)
    live=$(live_release)
    echo "Releases in ~/$APP_DIR/releases (* = live):"
    ls -1 "$BASE/releases" 2> /dev/null | sort -r | while read -r r; do
        [[ $r == "$live" ]] && echo "  * $r" || echo "    $r"
    done
    echo "~/$WEB_LINK -> $(readlink "$WEB" 2> /dev/null || echo 'not linked yet (first deploy will link it)')"
    ;;

install-cron)
    marker="# mfuko:$APP_DIR"
    cd_app="cd $BASE/current &&"
    {
        crontab -l 2> /dev/null | grep -v "$marker" || true
        echo "* * * * * $cd_app $PHP artisan schedule:run >> /dev/null 2>&1 $marker"
        echo "* * * * * $cd_app $PHP artisan queue:work --stop-when-empty --max-time=55 --tries=3 >> /dev/null 2>&1 $marker"
    } | crontab -
    say "cron jobs installed:"
    crontab -l | grep "$marker"
    ;;

*)
    echo "Usage: remote.sh deploy <release> | rollback | status | install-cron" >&2
    exit 1
    ;;
esac
