#!/usr/bin/env bash
# Publiceer bluegit naar de AUR vanuit een lokale checkout.
# Gebruikt de sleutel in ~/.ssh of ssh-agent. Geen CI-variabelen.
#
# De checkout moet op master staan, schoon zijn en gelijk aan origin/master.
# De gepubliceerde sha is die van origin/master. Staat die al als _commit
# in de AUR-PKGBUILD, dan stopt het script zonder push.
#
# Werkmap: ~/.cache/bluegit-aur, of BLUEGIT_AUR_CACHE.
# --check-only [repo] controleert de checkout en print de sha. Geen clone, geen push.
set -euo pipefail

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

require_publishable_checkout() {
  local repo="$1"
  local branch head origin dirty
  branch="$(git_safe "$repo" symbolic-ref --short HEAD 2>/dev/null || true)"
  if [[ "$branch" != "master" ]]; then
    echo "De checkout staat niet op master." >&2
    exit 1
  fi
  dirty="$(git_safe "$repo" status --porcelain)" || exit 1
  if [[ -n "$dirty" ]]; then
    echo "De checkout is niet schoon." >&2
    exit 1
  fi
  git_safe "$repo" fetch origin master
  head="$(git_safe "$repo" rev-parse HEAD)" || exit 1
  origin="$(git_safe "$repo" rev-parse origin/master)" || exit 1
  if [[ "$head" != "$origin" ]]; then
    echo "De checkout wijkt af van origin/master." >&2
    exit 1
  fi
  [[ "$origin" =~ ^[0-9a-f]{40}$ ]] || { echo "origin/master is geen volledige sha." >&2; exit 1; }
  printf '%s\n' "$origin"
}

have_local_ssh() {
  if command -v ssh-add >/dev/null 2>&1 && ssh-add -l >/dev/null 2>&1; then
    return 0
  fi
  local f base
  [[ -d "$HOME/.ssh" ]] || return 1
  shopt -s nullglob
  for f in "$HOME"/.ssh/*; do
    [[ -f "$f" ]] || continue
    base="$(basename "$f")"
    case "$base" in
      *.pub|known_hosts|known_hosts.old|config|authorized_keys|authorized_keys2) continue ;;
    esac
    if grep -q 'PRIVATE KEY' "$f" 2>/dev/null; then
      shopt -u nullglob
      return 0
    fi
  done
  shopt -u nullglob
  return 1
}

copy_packaging_aur() {
  local src="$1" dest="$2"
  local dotglob=0 nullglob=0
  if shopt -q dotglob; then
    dotglob=1
  fi
  if shopt -q nullglob; then
    nullglob=1
  fi
  shopt -s dotglob nullglob
  local files=("$src"/*)
  if [[ "$nullglob" -eq 0 ]]; then
    shopt -u nullglob
  fi
  if [[ "$dotglob" -eq 0 ]]; then
    shopt -u dotglob
  fi
  if [[ ${#files[@]} -eq 0 ]]; then
    echo "Geen bestanden in $src" >&2
    exit 1
  fi
  local f
  for f in "${files[@]}"; do
    cp -a "$f" "$dest/"
  done
}

sync_aur_workdir() {
  local dest="$1"
  local remote="ssh://aur@aur.archlinux.org/bluegit.git"
  if [[ -d "$dest/.git" ]]; then
    echo "Werk AUR-checkout bij: $dest"
    git_safe "$dest" remote set-url origin "$remote"
    git_safe "$dest" fetch origin master
    git_safe "$dest" checkout -f -B master origin/master
    return 0
  fi
  if [[ -d "$dest" ]] && [[ -n "$(ls -A "$dest" 2>/dev/null || true)" ]]; then
    echo "Werkmap $dest bestaat al en is geen git-checkout." >&2
    exit 1
  fi
  mkdir -p "$(dirname "$dest")"
  clone_or_init_aur_repo bluegit "$dest"
}

main() {
  local CHECK_ONLY=0
  local REPO="$ROOT"
  if [[ "${1:-}" == "--check-only" ]]; then
    CHECK_ONLY=1
    shift
  fi
  if [[ $# -gt 0 ]]; then
    if [[ "$CHECK_ONLY" -ne 1 || $# -ne 1 ]]; then
      echo "Gebruik: $0 [--check-only [repo]]" >&2
      exit 1
    fi
    REPO="$(cd "$1" && pwd)"
  fi

  local COMMIT
  COMMIT="$(require_publishable_checkout "$REPO")"
  echo "Publiceren: $COMMIT"
  if [[ "$CHECK_ONLY" -eq 1 ]]; then
    exit 0
  fi

  if [[ "$(id -u)" -eq 0 ]]; then
    echo "Draai dit script als de gebruiker met de AUR-sleutel, niet als root." >&2
    exit 1
  fi
  : "${HOME:?HOME is niet gezet}"
  if ! have_local_ssh; then
    echo "Geen AUR-sleutel: start ssh-agent en doe ssh-add, of zet een private sleutel in ~/.ssh." >&2
    exit 1
  fi

  local cmd
  for cmd in git sed updpkgsums makepkg; do
    command -v "$cmd" >/dev/null || {
      echo "Ontbrekend commando: $cmd. updpkgsums zit in pacman-contrib (pacman -S pacman-contrib)." >&2
      exit 1
    }
  done

  local CACHE="${BLUEGIT_AUR_CACHE:-$HOME/.cache/bluegit-aur}"
  sync_aur_workdir "$CACHE"
  if aur_commit_published "$CACHE/PKGBUILD" "$COMMIT"; then
    echo "Deze sha staat al op de AUR ($COMMIT). Niets te doen."
    exit 0
  fi

  copy_packaging_aur "$ROOT/packaging/aur" "$CACHE"
  local VERSION
  VERSION="$(TZ=UTC git_safe "$REPO" show -s --date=format-local:%Y%m%d%H%M%S --format=%cd "$COMMIT")" || exit 1
  [[ "$VERSION" =~ ^[0-9]{14}$ ]] || { echo "pkgver uit de commit is geen tijdstempel: $VERSION" >&2; exit 1; }
  set_pkgver_commit "$CACHE/PKGBUILD" "$VERSION" "$COMMIT"

  mkdir -p "$CACHE/.makepkg/src" "$CACHE/.makepkg/build"
  (
    cd "$CACHE"
    export SRCDEST="$CACHE/.makepkg/src"
    export BUILDDIR="$CACHE/.makepkg/build"
    export WORKDIR="$CACHE"
    updpkgsums PKGBUILD
    generate_srcinfo
  )

  cd "$CACHE"
  git add PKGBUILD .SRCINFO bluegit.install
  if git diff --cached --quiet; then
    echo "AUR-checkout is al gelijk. Niets te doen."
    exit 0
  fi
  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 bijgewerkt: bluegit ${VERSION} (${COMMIT})"
}

if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
  main "$@"
fi
