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

readonly HLCC_VERSION="16.0.1"
readonly RELAY_ROOT="/home/ubuntu/guanghu/release-relay/hlcc-v${HLCC_VERSION}"
readonly BINARY_NAME="forgejo-${HLCC_VERSION}-linux-amd64"
readonly RELEASE_URL="https://code.forgejo.org/forgejo/forgejo/releases/download/v${HLCC_VERSION}/${BINARY_NAME}"
readonly RELEASE_KEY="EB114F5E6C0DC2BCDD183550A4B61A2DC5923710"
readonly GPG_HOME="${RELAY_ROOT}/gpg"
readonly UPSTREAM_REPOSITORY="/home/ubuntu/guanghu/upstream-parts/forgejo-official.git"
readonly PRODUCT_REPOSITORY="/home/ubuntu/guanghu/products/guanghu-code-channel"

if [[ "$(id -un)" != "ubuntu" ]]; then
  echo "Refusing to prepare overseas release material as any user other than ubuntu." >&2
  exit 2
fi

for command_name in curl git gpg sha256sum; do
  if ! command -v "${command_name}" >/dev/null 2>&1; then
    echo "Missing required command: ${command_name}" >&2
    exit 3
  fi
done

if [[ ! -d "${UPSTREAM_REPOSITORY}" || ! -d "${PRODUCT_REPOSITORY}/.git" ]]; then
  echo "Required Forgejo upstream mirror or Guanghu product worktree is missing." >&2
  exit 3
fi

umask 077
mkdir -p "${RELAY_ROOT}" "${GPG_HOME}"
chmod 700 "${GPG_HOME}"

curl --fail --location --proto '=https' --tlsv1.2 \
  --output "${RELAY_ROOT}/${BINARY_NAME}" \
  "${RELEASE_URL}"
curl --fail --location --proto '=https' --tlsv1.2 \
  --output "${RELAY_ROOT}/${BINARY_NAME}.asc" \
  "${RELEASE_URL}.asc"

GNUPGHOME="${GPG_HOME}" gpg \
  --batch \
  --keyserver hkps://keys.openpgp.org \
  --recv-keys "${RELEASE_KEY}"

if ! GNUPGHOME="${GPG_HOME}" gpg \
  --batch \
  --with-colons \
  --fingerprint "${RELEASE_KEY}" \
  | grep -Fq "fpr:::::::::${RELEASE_KEY}:"; then
  echo "Forgejo release key fingerprint mismatch." >&2
  exit 4
fi

GNUPGHOME="${GPG_HOME}" gpg \
  --batch \
  --verify "${RELAY_ROOT}/${BINARY_NAME}.asc" "${RELAY_ROOT}/${BINARY_NAME}"
GNUPGHOME="${GPG_HOME}" gpg \
  --batch \
  --armor \
  --export "${RELEASE_KEY}" > "${RELAY_ROOT}/forgejo-release-key.asc"

git -C "${UPSTREAM_REPOSITORY}" bundle create \
  "${RELAY_ROOT}/forgejo-upstream-all.bundle" \
  --all
git -C "${PRODUCT_REPOSITORY}" bundle create \
  "${RELAY_ROOT}/guanghu-code-channel.bundle" \
  guanghu/main
git -C "${UPSTREAM_REPOSITORY}" bundle verify \
  "${RELAY_ROOT}/forgejo-upstream-all.bundle"
git -C "${PRODUCT_REPOSITORY}" bundle verify \
  "${RELAY_ROOT}/guanghu-code-channel.bundle"

(
  cd "${RELAY_ROOT}"
  sha256sum \
    "${BINARY_NAME}" \
    "${BINARY_NAME}.asc" \
    forgejo-release-key.asc \
    forgejo-upstream-all.bundle \
    guanghu-code-channel.bundle \
    > MANIFEST.sha256
)

echo "Verified HLCC release material prepared at ${RELAY_ROOT}"
echo "The offline package contains full upstream and Guanghu product Git bundles."
echo "No service was started and no transfer to a domestic node was attempted."
