#!/usr/bin/env bash
# KVT fork: publish the AUR package kvt-rusty-teams (built from source) for a release tag.
# Job publish_aur_source in blue-ci-cd.yml. No build and no makepkg: it only fills in the
# tag and commit in PKGBUILD, writes .SRCINFO and pushes both. Same secrets and approach as
# packaging/kvt/publish-aur.sh (the -bin package):
#   AUR_SSH_PRIVATE_KEY or AUR_SSH_PRIVATE_KEY_B64   the AUR account's SSH key
#   AUR_GIT_AUTHOR_NAME, AUR_GIT_AUTHOR_EMAIL        name and e-mail in the AUR commit
# Without a key the script says so and exits 0.
#
# Usage: packaging/aur-source/publish.sh [tag [commit]]   (default: $CI_COMMIT_TAG, $CI_COMMIT_SHA)
#        packaging/aur-source/publish.sh --render <tag> <commit> <out-dir>   PKGBUILD and .SRCINFO only
set -euo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PKG="${AUR_PKG:-kvt-rusty-teams}"

# pkgver may not contain '-': v0.6.1-kvt.4 becomes 0.6.1.kvt.4 (vercmp still orders it).
pkgver_of_tag() {
  local version="${1#v}"
  [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][A-Za-z0-9.]+)?$ ]] || {
    echo "tag is not v<major>.<minor>.<patch>[-suffix]: $1" >&2
    return 1
  }
  printf '%s\n' "${version//-/.}"
}

render_pkgbuild() {
  local tag="$1" commit="$2" out="$3" pkgver
  [[ "$commit" =~ ^[0-9a-f]{40}$ ]] || { echo "commit must be a full sha" >&2; return 1; }
  pkgver="$(pkgver_of_tag "$tag")"
  mkdir -p "$out"
  sed -e "s/^pkgver=.*/pkgver=${pkgver}/" \
      -e "s/^pkgrel=.*/pkgrel=1/" \
      -e "s/^_tag=.*/_tag=${tag}/" \
      -e "s/^_commit=.*/_commit=${commit}/" \
      "$HERE/PKGBUILD" > "$out/PKGBUILD"
}

# .SRCINFO from a PKGBUILD without makepkg (the CI image has no Arch tooling). Same field
# order and format as `makepkg --printsrcinfo`; tests.sh compares it with the committed file.
srcinfo() {
  (
    set -eu
    # shellcheck disable=SC1090
    source "$1"
    echo "pkgbase = $pkgname"
    echo "	pkgdesc = $pkgdesc"
    echo "	pkgver = $pkgver"
    echo "	pkgrel = $pkgrel"
    echo "	url = $url"
    local key arr
    for key in arch license makedepends depends provides conflicts options source sha256sums; do
      declare -n arr="$key"
      for value in "${arr[@]}"; do echo "	$key = $value"; done
    done
    echo
    echo "pkgname = $pkgname"
  )
}

if [[ "${1:-}" == "--render" ]]; then
  out="${4:?out-dir}"
  render_pkgbuild "${2:?tag}" "${3:?commit}" "$out"
  srcinfo "$out/PKGBUILD" > "$out/.SRCINFO"
  exit 0
fi

TAG="${1:-${CI_COMMIT_TAG:-}}"
COMMIT="${2:-${CI_COMMIT_SHA:-}}"
[[ -n "$TAG" ]] || { echo "No tag: run this in a tag pipeline or pass the tag." >&2; exit 1; }
[[ -n "$COMMIT" ]] || { echo "No commit: pass it or run this in a tag pipeline." >&2; exit 1; }

if [[ -z "${AUR_SSH_PRIVATE_KEY:-}" && -z "${AUR_SSH_PRIVATE_KEY_B64:-}" ]]; then
  echo "AUR: geen AUR_SSH_PRIVATE_KEY of AUR_SSH_PRIVATE_KEY_B64 gezet; $PKG wordt overgeslagen."
  echo "Zet die (beschermde) geheimen op ict/rusty-teams en bescherm het tagpatroon v*."
  exit 0
fi

for cmd in git ssh ssh-keygen ssh-keyscan sed; do
  command -v "$cmd" >/dev/null || { echo "Missing command: $cmd" >&2; exit 1; }
done

WORKDIR="$(mktemp -d "${TMPDIR:-/tmp}/kvt-aur-source-XXXXXX")"
trap 'rm -rf "$WORKDIR"' EXIT

"$HERE/../kvt/aur-ssh-setup.sh"
export GIT_SSH_COMMAND="ssh -o StrictHostKeyChecking=yes -o BatchMode=yes"

dest="$WORKDIR/$PKG"
remote="ssh://aur@aur.archlinux.org/${PKG}.git"
echo "Cloning $remote"
if ! git clone -q "$remote" "$dest"; then
  echo "AUR repo $PKG does not exist yet; it is created on the first push"
  mkdir -p "$dest"
  git -C "$dest" init -q
  git -C "$dest" checkout -q -b master
  git -C "$dest" remote add origin "$remote"
fi
git config --global --add safe.directory '*'

render_pkgbuild "$TAG" "$COMMIT" "$dest"
srcinfo "$dest/PKGBUILD" > "$dest/.SRCINFO"
cat "$dest/.SRCINFO"

cd "$dest"
git config user.name "${AUR_GIT_AUTHOR_NAME:-KVT release bot}"
git config user.email "${AUR_GIT_AUTHOR_EMAIL:-hephaestus@noreply.kvt.nl}"
git add PKGBUILD .SRCINFO
if git rev-parse --verify -q HEAD >/dev/null && git diff --cached --quiet; then
  echo "AUR repo already up to date: $PKG $TAG"
  exit 0
fi
git commit -q -m "${TAG}"
git push -q origin HEAD:master
echo "AUR updated: $PKG $(pkgver_of_tag "$TAG")"
