#!/bin/bash
set -euo pipefail

ROOT="$(cd "$(dirname "$0")" && pwd)"
TS="$(date +"%Y%m%d-%H%M%S")"
OUTDIR="${ROOT}/../_release_out_archicratie"
STAGE="${OUTDIR}/archicratie-web-${TS}"
ARCHIVE="${OUTDIR}/archicratie-web-${TS}.tar.gz"

rm -rf "${OUTDIR}"
mkdir -p "${STAGE}"

# Copie "propre" via rsync (évite ._* et .DS_Store et gros répertoires inutiles)
rsync -a --delete \
  --exclude 'node_modules' \
  --exclude 'dist' \
  --exclude '.DS_Store' \
  --exclude '._*' \
  --exclude 'PaxHeader' \
  --exclude '.git' \
  --exclude '.vscode' \
  --exclude '*.log' \
  --exclude '_release_out' \
  "${ROOT}/" "${STAGE}/"

# Sécurité supplémentaire : purge des scories Apple si jamais elles ont fuité
find "${STAGE}" -name '.DS_Store' -delete || true
find "${STAGE}" -name '._*' -delete || true
find "${STAGE}" -type d -name 'PaxHeader' -prune -exec rm -rf {} + 2>/dev/null || true

# Pack tar.gz SANS metadata Apple (COPYFILE_DISABLE)
cd "${OUTDIR}"
COPYFILE_DISABLE=1 tar -czf "${ARCHIVE}" "$(basename "${STAGE}")"

# Empreinte
shasum -a 256 "${ARCHIVE}" | tee "${ARCHIVE}.sha256"

echo
echo "✅ Archive prête : ${ARCHIVE}"
echo "✅ SHA256        : ${ARCHIVE}.sha256"
