#!/usr/bin/env bash
set +x
set -euo pipefail
umask 077

fail() { printf '%s\n' "$*" >&2; exit 1; }

(( $# == 1 )) || fail 'Usage: ./bin/publish COMMIT'
source_sha=$1
[[ $source_sha =~ ^[0-9a-f]{40}$ ]] || fail 'Expected a full 40-character Git commit SHA.'

package=omp-instance-control
repository=klondikemarlen/$package
origin=https://github.com/$repository.git
workflow=prepare-obs-source.yml
project=home:klondikemarlen:$package
api=https://api.opensuse.org
source=/source/$project/$package
root=$(CDPATH='' cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)

scratch=$(mktemp -d)
trap 'rm -rf -- "$scratch"' EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM

# Use isolated refs so a local branch or concurrent local fetch cannot supply provenance.
git init --bare --quiet "$scratch/repository"
release_git() { git -C "$scratch/repository" "$@"; }
release_git fetch --no-tags "$origin" refs/heads/main:refs/heads/main
release_git rev-list --first-parent refs/heads/main | grep -Fx "$source_sha" >/dev/null ||
  fail 'The requested commit is not on canonical main.'
version=$(release_git show "$source_sha:debian/changelog" | dpkg-parsechangelog -l- -SVersion)
[[ $version =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]] ||
  fail "Expected a stable X.Y.Z Debian version in the tested commit, got $version."
dsc=${package}_$version.dsc
tarball=${package}_$version.tar.xz

workflow_runs=$(gh api --hostname github.com --method GET "repos/$repository/actions/workflows/$workflow/runs" \
  -f branch=main -f event=push -f head_sha="$source_sha" -f status=success) ||
  fail "Could not read GitHub's test runs for $source_sha."
tested_run=$(jq -er --arg repository "$repository" --arg path ".github/workflows/$workflow" --arg commit "$source_sha" '
  def positive_integer: type == "number" and floor == . and . > 0;
  [.workflow_runs[] | select(
    .repository.full_name == $repository and .head_repository.full_name == $repository and
    .path == $path and .event == "push" and .head_branch == "main" and .head_sha == $commit and
    .status == "completed" and .conclusion == "success" and
    (.id | positive_integer) and (.run_attempt | positive_integer)
  )] | max_by(.id) | select(. != null) | "\(.id) \(.run_attempt)"
' <<<"$workflow_runs") ||
  fail "No successful Ubuntu source test run on main for $source_sha."
read -r run_id run_attempt <<<"$tested_run"

mkdir "$scratch/release"
gh run download "$run_id" --repo "github.com/$repository" \
  --name "tested-ubuntu-source-$source_sha-$run_attempt" --dir "$scratch/release" ||
  fail "Could not download tested Ubuntu sources from GitHub run $run_id attempt $run_attempt. The artifact may have expired."

shopt -s nullglob dotglob
release_files=("$scratch/release/"*)
[[ ${#release_files[@]} == 3 ]] || fail 'The tested artifact must contain exactly the source pair and SHA256SUMS.'
for file in "$dsc" "$tarball" SHA256SUMS; do
  path=$scratch/release/$file
  [[ -f $path && ! -L $path ]] || fail "Missing expected regular file in the tested artifact: $file"
done

dsc_hash=$(sha256sum -- "$scratch/release/$dsc")
dsc_hash=${dsc_hash%% *}
tar_hash=$(sha256sum -- "$scratch/release/$tarball")
tar_hash=${tar_hash%% *}
printf '# tested-source-sha: %s\n%s  %s\n%s  %s\n' "$source_sha" "$dsc_hash" "$dsc" "$tar_hash" "$tarball" |
  cmp -s - "$scratch/release/SHA256SUMS" ||
  fail 'The tested artifact does not match the requested commit and both source digests in SHA256SUMS.'

pair_matches() {
  printf '%s  %s\n%s  %s\n' "$dsc_hash" "$dsc" "$tar_hash" "$tarball" | sha256sum --check --status -
}

lock_dir=${XDG_RUNTIME_DIR:-${XDG_CACHE_HOME:-$HOME/.cache}}/omp-instance-control/publish.lock
mkdir -p -- "$lock_dir"
exec {publication_lock}<"$lock_dir"
flock -n "$publication_lock" ||
  fail 'Could not lock local publishing; check for another ./bin/publish running in this account.'

run_osc() {
  osc -A "$api" "$@"
}

source_identity() {
  python3 -c '
import re
import sys
from xml.etree import ElementTree as ET

root = ET.parse(sys.stdin).getroot()
revision = root.get("rev", "")
srcmd5 = root.get("srcmd5", "")
if (
    root.tag != "directory"
    or root.find("linkinfo") is not None
    or root.find("serviceinfo") is not None
    or not re.fullmatch(r"[1-9][0-9]*", revision)
    or not re.fullmatch(r"[0-9a-f]{32}", srcmd5)
):
    raise SystemExit("Expected a direct committed OBS source revision.")
print(revision, srcmd5)
'
}

canonical_versions() {
  run_osc api "$source/_history" | python3 -c '
import sys
from xml.etree import ElementTree as ET

root = ET.parse(sys.stdin).getroot()
versions = [revision.findtext("version") for revision in root.findall("revision")]
if root.tag != "revisionlist" or not versions or not all(versions):
    raise SystemExit("Canonical OBS revision history is incomplete.")
print(*versions, sep="\n")
'
}

worktree=$scratch/package
printf 'Checking production OBS for Ubuntu version %s tested at %s.\n' "$version" "$source_sha"
run_osc checkout --unexpand-link --output-dir "$worktree" "$project" "$package" ||
  fail 'Could not check out the canonical OBS package. Check your local osc login and package access.'
cd "$worktree"
checked_out=$(source_identity < .osc/_files)
read -r previous_revision _ <<<"$checked_out"

descriptors=("${package}_"*.dsc)
[[ ${#descriptors[@]} == 1 ]] || fail 'The canonical OBS package does not contain exactly one source descriptor.'
previous_dsc=${descriptors[0]}
previous_version=$(awk '/^Version: / {print $2}' "$previous_dsc")
previous_tar=${package}_$previous_version.tar.xz
files=(*)
[[ ${#files[@]} == 3 && $previous_dsc == "${package}_$previous_version.dsc" && -f $previous_tar ]] ||
  fail 'The canonical OBS package does not contain just the expected direct source pair.'

history=$(canonical_versions)
while IFS= read -r published_version; do
  dpkg --compare-versions "$version" ge "$published_version" ||
    fail "Refusing stale version $version; canonical OBS has already reached $published_version."
  if dpkg --compare-versions "$version" eq "$published_version" &&
    ! dpkg --compare-versions "$version" eq "$previous_version"; then
    fail "Refusing to republish historical version $version after a canonical OBS rollback."
  fi
done <<<"$history"

if dpkg --compare-versions "$version" eq "$previous_version"; then
  pair_matches || fail "Refusing to replace version $version with changed source bytes."
  committed=$checked_out
  result='Already present with identical source bytes'
else
  dpkg --compare-versions "$version" gt "$previous_version" ||
    fail "Refusing stale version $version; canonical OBS currently contains $previous_version."
  run_osc rm "$previous_dsc" "$previous_tar" || fail 'Could not mark the superseded OBS pair for removal.'
  mv "$scratch/release/$dsc" "$scratch/release/$tarball" .
  run_osc add "$dsc" "$tarball" || fail 'Could not mark the exact release pair for addition.'

  # One native OSC transaction. Do not update or retry an outdated checkout: rerun from fresh state.
  run_osc commit --skip-local-service-run -m "Release $version from $source_sha" ||
    fail 'OBS commit failed (the checkout may be outdated). Inspect the canonical revision before retrying this release.'
  committed=$(source_identity < .osc/_files)
  read -r committed_revision _ <<<"$committed"
  [[ $committed_revision == "$((previous_revision + 1))" ]] ||
    fail 'A concurrent OBS revision intervened during commit; inspect the canonical package before retrying.'
  result='Submitted exact source bytes'
fi

read -r revision srcmd5 <<<"$committed"
for file in "$dsc" "$tarball"; do
  run_osc api "$source/$file?rev=$srcmd5" > "$scratch/release/$file" ||
    fail "Could not read back $file at committed OBS source $srcmd5."
done
(cd "$scratch/release" && pair_matches) || fail 'Committed OBS source bytes do not match the tested source pair.'
current=$(run_osc api "$source?rev=latest" | source_identity)
[[ $current == "$committed" ]] || fail 'The canonical OBS revision changed during publication.'

printf '%s: %s (%s) at OBS revision %s (%s).\n' "$result" "$version" "$source_sha" "$revision" "$srcmd5"
printf 'Verifying the signed Ubuntu APT package from that revision; this may take several minutes.\n'
python3 "$root/dev/verify-ubuntu-publication.py" "$version" "$dsc_hash" "$tar_hash" "$revision" "$srcmd5" ||
  fail "Ubuntu APT publication was not verified. Rerun ./bin/publish $source_sha to recheck the same source without replacing it."
