#!/usr/bin/env bash
# Update an AUR package from the BlueGit source archive of this commit.
# AUR_PKG=bluegit (default, packaging/aur), AUR_PKG=bluegit-runner
# (packaging/aur-runner) or AUR_PKG=bluegit-backup (packaging/aur-backup). Pushes ssh://aur@aur.archlinux.org/$AUR_PKG.git
# master. AUR only accepts master.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
# shellcheck source=aur-common.sh
source "$(dirname "$0")/aur-common.sh"

# pkgver_of_commit is YYYYMMDDHHMMSS in UTC, from the committer time.
# CI_COMMIT_TIMESTAMP is ISO 8601. Without it, git show -s --format=%cI
# is the same instant the self-updater uses. The job clock is not a version.
# BusyBox date does not parse the Z or an offset, so the offset is applied here.
pkgver_of_commit() {
  local root="$1"
  local commit="${2:-}"
  if [[ -z "$commit" ]]; then
    commit="$(git_safe "$root" rev-parse HEAD)" || return 1
  fi
  [[ "$commit" =~ ^[0-9a-f]{40}$ ]] || { echo "CI_COMMIT_SHA or HEAD is not a full sha" >&2; return 1; }
  local stamp version
  if [[ -n "${CI_COMMIT_TIMESTAMP:-}" ]]; then
    stamp="$CI_COMMIT_TIMESTAMP"
  else
    # Zonder || blijft stamp leeg: set -e stopt niet op een falende
    # command substitution, en utc_digits meldt dan een lege stempel.
    stamp="$(git_safe "$root" show -s --format=%cI "$commit")" || return 1
  fi
  version="$(utc_digits "$stamp")" || return 1
  [[ "$version" =~ ^[0-9]{14}$ ]] || { echo "pkgver is not a timestamp: ${version:-empty} from ${stamp:-empty}" >&2; return 1; }
  printf '%s\n' "$version"
}

# utc_digits turns ISO 8601 into YYYYMMDDHHMMSS in UTC.
# Accepted forms: 2026-10-22T23:32:33Z, 2026-10-22T23:32:33+01:00, 2026-10-22T23:32:33+0100.
utc_digits() {
  local stamp="$1" core off sign hh mm epoch adj
  if [[ "$stamp" == *Z ]]; then
    core="${stamp%Z}"
    off="+00:00"
  elif [[ "$stamp" =~ ^(.+)([+-][0-9]{2}:[0-9]{2})$ ]]; then
    core="${BASH_REMATCH[1]}"
    off="${BASH_REMATCH[2]}"
  elif [[ "$stamp" =~ ^(.+)([+-][0-9]{4})$ ]]; then
    core="${BASH_REMATCH[1]}"
    off="${BASH_REMATCH[2]:0:3}:${BASH_REMATCH[2]:3:2}"
  else
    core="$stamp"
    off="+00:00"
  fi
  core="${core%%.*}"
  core="${core/T/ }"
  [[ "$core" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}\ [0-9]{2}:[0-9]{2}:[0-9]{2}$ ]] || {
    echo "pkgver stamp is not ISO 8601: $stamp" >&2
    return 1
  }
  sign="${off:0:1}"
  hh="${off:1:2}"
  mm="${off:4:2}"
  epoch="$(TZ=UTC date -u -d "$core" +%s)" || return 1
  adj=$((10#$hh * 3600 + 10#$mm * 60))
  if [[ "$sign" == "+" ]]; then
    epoch=$((epoch - adj))
  else
    epoch=$((epoch + adj))
  fi
  TZ=UTC date -u -d "@$epoch" +%Y%m%d%H%M%S
}

if [[ "${1:-}" == "--rewrite-only" ]]; then
  rewrite_pkgbuild "$2" "$3" "$4" "$5"
  exit 0
fi

if [[ "${1:-}" == "--print-pkgver" ]]; then
  pkgver_of_commit "$ROOT" "${CI_COMMIT_SHA:-}"
  exit
fi

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

if [[ -n "${CI_COMMIT_SHA:-}" ]]; then
  COMMIT="$CI_COMMIT_SHA"
else
  COMMIT="$(git_safe "$ROOT" rev-parse HEAD)" || exit 1
fi
VERSION="$(pkgver_of_commit "$ROOT" "$COMMIT")"

PKG="${AUR_PKG:-bluegit}"
case "$PKG" in
  bluegit) PKGDIR="$ROOT/packaging/aur" ;;
  bluegit-runner) PKGDIR="$ROOT/packaging/aur-runner" ;;
  bluegit-backup) PKGDIR="$ROOT/packaging/aur-backup" ;;
  *) echo "Unknown AUR_PKG: $PKG" >&2; exit 1 ;;
esac
INSTALL_FILE="${PKG}.install"

TMPDIR="${TMPDIR:-/tmp}"
WORKDIR="$(mktemp -d "$TMPDIR/bluegit-aur-XXXXXX")"
cleanup() { rm -rf "$WORKDIR"; }
trap cleanup EXIT

SOURCE_URL="https://git.timfalken.com/timfa/bluegit/-/archive/${COMMIT}/bluegit-${COMMIT}.tar.gz"
TMP_SOURCE="$WORKDIR/source.tar.gz"
echo "Checking source tarball: $SOURCE_URL"
if ! curl -fsSL "$SOURCE_URL" -o "$TMP_SOURCE"; then
  echo "Could not download $SOURCE_URL" >&2
  exit 1
fi
SOURCE_SHA="$(sha256sum "$TMP_SOURCE" | awk '{print $1}')"

dest="$WORKDIR/$PKG"
clone_or_init_aur_repo "$PKG" "$dest"
cd "$dest"
git config user.name "${AUR_GIT_AUTHOR_NAME:-BlueGit release bot}"
git config user.email "${AUR_GIT_AUTHOR_EMAIL:-noreply@example.invalid}"
cp "$PKGDIR/PKGBUILD" PKGBUILD
cp "$PKGDIR/$INSTALL_FILE" "$INSTALL_FILE"
rewrite_pkgbuild "$VERSION" "$COMMIT" "$SOURCE_SHA" PKGBUILD
generate_srcinfo

if git diff --quiet -- PKGBUILD .SRCINFO "$INSTALL_FILE" 2>/dev/null && git rev-parse --verify HEAD >/dev/null 2>&1; then
  echo "AUR repo already up to date: ${PKG} ${VERSION}"
  exit 0
fi

git add PKGBUILD .SRCINFO "$INSTALL_FILE"
if git rev-parse --verify HEAD >/dev/null 2>&1; then
  git commit -m "upstream ${VERSION}"
else
  git commit -m "initial import ${VERSION}"
fi
git push -u origin master
echo "AUR updated: ${PKG} ${VERSION}"
