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

BUNDLE_ROOT=""
ALLOW_DEVELOPMENT="false"
TRUSTED_PUBLIC_KEY=""

usage() {
  echo "Usage: $0 --bundle-root <path> [--trusted-public-key <path>] [--allow-development-bundle]" >&2
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --bundle-root)
      BUNDLE_ROOT="${2:?missing bundle root}"
      shift 2
      ;;
    --allow-development-bundle)
      ALLOW_DEVELOPMENT="true"
      shift
      ;;
    --trusted-public-key)
      TRUSTED_PUBLIC_KEY="${2:?missing trusted public key}"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage
      exit 2
      ;;
  esac
done

[[ -n "$BUNDLE_ROOT" ]] || { usage; exit 2; }
BUNDLE_ROOT="$(cd "$BUNDLE_ROOT" && pwd)"
CHECKSUM_FILE="$BUNDLE_ROOT/SHA256SUMS"

if [[ ! -f "$CHECKSUM_FILE" ]]; then
  if [[ "$ALLOW_DEVELOPMENT" == "true" ]]; then
    echo "WARNING: development bundle has no SHA256SUMS"
    exit 0
  fi
  echo "Missing bundle checksum file: $CHECKSUM_FILE" >&2
  exit 1
fi

command -v sha256sum >/dev/null 2>&1 || {
  echo "sha256sum is required" >&2
  exit 1
}

(
  cd "$BUNDLE_ROOT"
  sha256sum --check SHA256SUMS
)

SIGNATURE_FILE="$BUNDLE_ROOT/SHA256SUMS.sig"
if [[ -f "$SIGNATURE_FILE" ]]; then
  if [[ -n "$TRUSTED_PUBLIC_KEY" ]]; then
    [[ -f "$TRUSTED_PUBLIC_KEY" ]] || {
      echo "Trusted release public key does not exist: $TRUSTED_PUBLIC_KEY" >&2
      exit 1
    }
    BUNDLE_REAL="$(realpath "$BUNDLE_ROOT")"
    KEY_REAL="$(realpath "$TRUSTED_PUBLIC_KEY")"
    case "$KEY_REAL" in
      "$BUNDLE_REAL"/*)
        echo "Trusted public key must be provisioned outside the bundle trust boundary" >&2
        exit 1
        ;;
    esac
    command -v cosign >/dev/null 2>&1 || {
      echo "cosign is required to verify the signed bundle" >&2
      exit 1
    }
    cosign verify-blob \
      --key "$KEY_REAL" \
      --signature "$SIGNATURE_FILE" \
      "$CHECKSUM_FILE"
  elif [[ "$ALLOW_DEVELOPMENT" != "true" ]]; then
    echo "Formal deployment requires --trusted-public-key outside the bundle" >&2
    exit 1
  else
    echo "WARNING: signature was not verified because no trusted public key was supplied"
  fi
elif [[ "$ALLOW_DEVELOPMENT" != "true" ]]; then
  echo "Unsigned bundle is not allowed" >&2
  exit 1
else
  echo "WARNING: development bundle is not signed"
fi

echo "Bundle verification passed: $BUNDLE_ROOT"
