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

publish_manifests_usage() {
  cat <<'EOF_USAGE'
Verify release assets and publish the final Desktop six-package manifest.

Usage:
  ./publish-release-manifests.sh <version> [--verify-cdn]

The CI-owned daemon manifest is a temporary bridge for already-installed Linux
clients. This command verifies the two Linux archives plus two macOS DMGs and
two Windows EXEs, publishes one Desktop version manifest that lists all six
user-downloadable packages, then activates the Electron updater metadata for a
stable release. Electron Builder metadata and packaged artifacts must use the
supplied version.

The default command uploads and verifies all final metadata at the origin, then
prints the CDN URLs to refresh together. After the refresh, --verify-cdn checks
that the public CDN matches the origin without regenerating or uploading files.
EOF_USAGE
}

fail() {
  echo "error: $*" >&2
  exit 1
}

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=manual-owner-client-assets.lib.sh
source "${SCRIPT_DIR}/manual-owner-client-assets.lib.sh"

VERSION_ARG="${1:-}"
if [[ -z "${VERSION_ARG}" ]]; then
  publish_manifests_usage >&2
  exit 1
fi
if [[ "${VERSION_ARG}" == "-h" || "${VERSION_ARG}" == "--help" ]]; then
  publish_manifests_usage
  exit 0
fi
shift

VERIFY_CDN=0
while [[ $# -gt 0 ]]; do
  case "$1" in
    --verify-cdn)
      VERIFY_CDN=1
      ;;
    *)
      fail "unknown argument: $1"
      ;;
  esac
  shift
done

init_manual_owner_client_assets "${VERSION_ARG}"
if [[ "${VERIFY_CDN}" -eq 1 ]]; then
  verify_release_publication
  echo "CDN metadata matches the origin for ${VERSION}."
else
  ensure_ks3util_bin
  publish_release_manifests
  print_manifest_summary
  echo "Refresh these CDN URLs together:"
  release_metadata_refresh_urls
  echo "Then verify with: ./publish-release-manifests.sh ${VERSION} --verify-cdn"
fi
