#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
WORKSPACE_DIR="${1:-}"
OUTPUT_DIR="${OUTPUT_DIR:-$ROOT_DIR/var/prod-validation-archives}"
DATE_STAMP="${DATE_STAMP:-$(date +%Y-%m-%d)}"

if [[ -z "$WORKSPACE_DIR" ]]; then
  echo "Usage: $0 /path/to/prod-validation-workspace" >&2
  exit 1
fi

if [[ ! -d "$WORKSPACE_DIR" ]]; then
  echo "Workspace not found: $WORKSPACE_DIR" >&2
  exit 1
fi

WORKSPACE_NAME="$(basename "$WORKSPACE_DIR")"
ARCHIVE_BASE="$OUTPUT_DIR/${DATE_STAMP}-${WORKSPACE_NAME}"
ARCHIVE_FILE="$ARCHIVE_BASE.tar.gz"
MANIFEST_FILE="$ARCHIVE_BASE.manifest.txt"

mkdir -p "$OUTPUT_DIR"

tar -czf "$ARCHIVE_FILE" -C "$(dirname "$WORKSPACE_DIR")" "$WORKSPACE_NAME"

{
  echo "LineUp France - Prod Validation Archive"
  echo "Date: $DATE_STAMP"
  echo "Workspace: $WORKSPACE_DIR"
  echo "Archive: $ARCHIVE_FILE"
  echo
  echo "Files:"
  find "$WORKSPACE_DIR" -type f | sort
} > "$MANIFEST_FILE"

printf 'Archive ready: %s\n' "$ARCHIVE_FILE"
printf 'Manifest: %s\n' "$MANIFEST_FILE"
