#!/bin/bash
set -euo pipefail

root_dir="$(cd "$(dirname "$0")/.." && pwd)"
release_archive="${1:-}"
if [[ -z "$release_archive" || ! -f "$release_archive" ]]; then
  echo "Usage: $0 /chemin/vers/globinours.tar.gz" >&2
  exit 2
fi
if [[ ! -f "$root_dir/public/index.php" || ! -f "$root_dir/VERSION" ]]; then
  echo "Installation Globinours invalide: $root_dir" >&2
  exit 2
fi

stage_dir="$(mktemp -d /tmp/globinours-update-XXXXXX)"
trap 'rm -rf "$stage_dir"; rm -f "$root_dir/storage/maintenance.flag"' EXIT
if tar -tzf "$release_archive" | grep -Eq '(^/|(^|/)\.\.(/|$))'; then
  echo "Archive refusée: chemin dangereux." >&2
  exit 3
fi
tar -xzf "$release_archive" -C "$stage_dir"
source_dir="$stage_dir"
if [[ ! -f "$source_dir/public/index.php" ]]; then
  first_dir="$(find "$stage_dir" -mindepth 1 -maxdepth 1 -type d | head -n 1)"
  source_dir="$first_dir"
fi
if [[ ! -f "$source_dir/public/index.php" || ! -f "$source_dir/VERSION" ]]; then
  echo "Archive Globinours invalide." >&2
  exit 3
fi

mkdir -p "$root_dir/storage/releases"
current_version="$(tr -d '[:space:]' < "$root_dir/VERSION")"
new_version="$(tr -d '[:space:]' < "$source_dir/VERSION")"
rollback_archive="$root_dir/storage/releases/code-${current_version}-$(date +%Y%m%d-%H%M%S).tar.gz"
php "$root_dir/scripts/backup.php" pre-upgrade
tar --exclude='./data' --exclude='./storage' --exclude='./public/media' --exclude='./.env' -czf "$rollback_archive" -C "$root_dir" .
touch "$root_dir/storage/maintenance.flag"
rsync -a --delete --exclude=data --exclude=storage --exclude=public/media --exclude=.env "$source_dir/" "$root_dir/"
php "$root_dir/scripts/migrate.php"
rm -f "$root_dir/storage/maintenance.flag"
echo "Globinours $current_version -> $new_version"
echo "Retour arrière du code: $rollback_archive"
