#!/usr/bin/env bash
#
# Build a deploy tarball for pre-production. Run LOCALLY, from the repo root.
#
# Modalita':
#   ./deploy/build-package.sh [ref] [out_dir]
#       Pacchetto COMPLETO: tarball con prefisso (una nuova dir di release).
#
#   ./deploy/build-package.sh --since <base_ref> [ref] [out_dir]
#       Pacchetto DELTA (incrementale): SOLO i file cambiati da <base_ref> a <ref>,
#       SENZA prefisso -> si estrae "sopra" la dir di un release gia' deployato.
#       I file eliminati nel delta sono elencati nel file .APPLY.txt (rimozione manuale).
#
# Defaults: ref=HEAD, out_dir=./dist
#
# Usa `git archive`: include SOLO file committati/tracciati (no .git, vendor/,
# node_modules/, public/build|bundles/, .env.local, var/, dump SQL).
# Le build composer/npm si fanno sul server (vedi deploy-preprod.sh).
#
set -euo pipefail

SINCE=""
if [ "${1:-}" = "--since" ]; then
    SINCE="${2:-}"
    [ -n "$SINCE" ] || { echo "Uso: $0 --since <base_ref> [ref] [out_dir]"; exit 2; }
    shift 2
fi

REF="${1:-HEAD}"
OUT_DIR="${2:-./dist}"

cd "$(git rev-parse --show-toplevel)"
mkdir -p "$OUT_DIR"

if [ -n "$(git status --porcelain)" ]; then
    echo "ATTENZIONE: working tree non pulito. Verra' archiviato il commit '$REF', non le modifiche non committate."
fi

SHORT="$(git rev-parse --short=8 "$REF")"
DATE="$(date +%Y%m%d-%H%M)"

# ---------------------------------------------------------------------------
# Modalita' DELTA (incrementale, overlay)
# ---------------------------------------------------------------------------
if [ -n "$SINCE" ]; then
    BASE="$(git rev-parse --short=8 "$SINCE")"
    NAME="c4rgocloud-preprod-delta-${DATE}-${BASE}_to_${SHORT}"
    ARCHIVE="${OUT_DIR}/${NAME}.tar.gz"
    APPLY="${OUT_DIR}/${NAME}.APPLY.txt"

    mapfile -t CHANGED < <(git diff --name-only --diff-filter=ACMRT "$SINCE..$REF")
    if [ "${#CHANGED[@]}" -eq 0 ]; then
        echo "Nessun file modificato da $BASE a $SHORT: niente da pacchettizzare."
        exit 0
    fi
    DELETED="$(git diff --name-only --diff-filter=D "$SINCE..$REF" || true)"

    # overlay: nessun --prefix, percorsi relativi alla root del progetto
    git archive --format=tar.gz -o "$ARCHIVE" "$REF" -- "${CHANGED[@]}"

    {
        echo "Delta deploy ${BASE} -> ${SHORT} — ${DATE}"
        echo
        echo "File aggiornati/aggiunti:"
        printf '  %s\n' "${CHANGED[@]}"
        if [ -n "$DELETED" ]; then
            echo
            echo "File DA ELIMINARE a mano nel release deployato:"
            echo "$DELETED" | sed 's/^/  rm /'
        fi
        echo
        echo "Applicazione sul server, DENTRO la dir del release gia' deployato:"
        echo "  tar -xzf ${NAME}.tar.gz -C /percorso/al/release/"
        echo
        echo "NB: se il delta tocca composer.json/lock o gli asset, ricorda di rilanciare"
        echo "    i passi relativi (composer install / cache / assets:install / npm build)."
        echo "    Per modifiche di sole doc/versione non serve nulla."
    } > "$APPLY"

    echo "Delta:   $ARCHIVE"
    du -h "$ARCHIVE"
    echo "File:    ${#CHANGED[@]}"
    echo "Istruzioni: $APPLY"
    exit 0
fi

# ---------------------------------------------------------------------------
# Modalita' COMPLETA (release autonomo)
# ---------------------------------------------------------------------------
BRANCH="$(git rev-parse --abbrev-ref "$REF" 2>/dev/null || echo detached)"
NAME="c4rgocloud-preprod-${DATE}-${SHORT}"
ARCHIVE="${OUT_DIR}/${NAME}.tar.gz"

echo "Ref:     $REF ($BRANCH @ $SHORT)"
echo "Output:  $ARCHIVE"

git archive --format=tar.gz --prefix="${NAME}/" -o "$ARCHIVE" "$REF"
git rev-parse "$REF" > "${OUT_DIR}/${NAME}.commit.txt"

echo
echo "Fatto."
du -h "$ARCHIVE"
echo "File nel pacchetto: $(tar -tzf "$ARCHIVE" | wc -l)"
echo
echo "Trasferiscilo sul server (es.):"
echo "    scp '$ARCHIVE' utente@cloud-preprod:/path/releases/"
echo "Poi sul server segui deploy/DEPLOY_PREPROD.md (o lancia deploy/deploy-preprod.sh)."
