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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DEPLOY_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
ARTIFACT_CACHE=""
OUTPUT_DIR=""
ALLOW_UNVALIDATED="false"

usage() {
  echo "Usage: $0 --artifact-cache <path> --output <path> [--allow-unvalidated]" >&2
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --artifact-cache) ARTIFACT_CACHE="${2:?missing artifact cache}"; shift 2 ;;
    --output) OUTPUT_DIR="${2:?missing output path}"; shift 2 ;;
    --allow-unvalidated) ALLOW_UNVALIDATED="true"; shift ;;
    -h|--help) usage; exit 0 ;;
    *) echo "Unknown argument: $1" >&2; usage; exit 2 ;;
  esac
done

[[ -d "$ARTIFACT_CACHE" && -n "$OUTPUT_DIR" ]] || { usage; exit 2; }
command -v python3 >/dev/null 2>&1 || { echo "python3 is required" >&2; exit 1; }
command -v sha256sum >/dev/null 2>&1 || { echo "sha256sum is required" >&2; exit 1; }

VALIDATED="$(python3 -c 'import sys,yaml; print(str(yaml.safe_load(open(sys.argv[1], encoding="utf-8"))["validated"]).lower())' "$DEPLOY_ROOT/versions.lock.yaml")"
if [[ "$VALIDATED" != "true" && "$ALLOW_UNVALIDATED" != "true" ]]; then
  echo "versions.lock.yaml is not validated" >&2
  exit 1
fi

OUTPUT_PARENT="$(cd "$(dirname "$OUTPUT_DIR")" && pwd)"
OUTPUT_NAME="$(basename "$OUTPUT_DIR")"
STAGING="$(mktemp -d "$OUTPUT_PARENT/.${OUTPUT_NAME}.staging.XXXXXX")"
cleanup() {
  rm -rf "$STAGING"
}
trap cleanup EXIT INT TERM

mkdir -p "$STAGING/$OUTPUT_NAME"
cp -a "$DEPLOY_ROOT" "$STAGING/$OUTPUT_NAME/deploy"
cp -a "$ARTIFACT_CACHE/." "$STAGING/$OUTPUT_NAME/"

(
  cd "$STAGING/$OUTPUT_NAME"
  find . -type f \
    ! -name SHA256SUMS \
    ! -name SHA256SUMS.sig \
    -print0 |
    sort -z |
    xargs -0 sha256sum > SHA256SUMS
)

if [[ -e "$OUTPUT_DIR" ]]; then
  echo "Output already exists; refusing to overwrite: $OUTPUT_DIR" >&2
  exit 1
fi
mv "$STAGING/$OUTPUT_NAME" "$OUTPUT_DIR"
echo "Offline bundle created: $OUTPUT_DIR"
echo "Sign SHA256SUMS before release, for example:"
echo "  cosign sign-blob --key <private-key> --output-signature $OUTPUT_DIR/SHA256SUMS.sig $OUTPUT_DIR/SHA256SUMS"
echo "Provision the matching public key to the deployment controller outside the bundle."
