#!/bin/sh
# KuboRun published-image delivery. Run from your repository: sh pre-push.sh --install
set -eu
fail() { printf '%s\n' "$*" >&2; exit 1; }
manifest=.kubo/kubo.yaml
yaml() {
  if command -v yq >/dev/null && yq --version 2>/dev/null | grep -q 'mikefarah.*version v4'; then
    yq -er "$1" -
  else
    docker run --rm -i --network none -e KUBO_SERVICE mikefarah/yq:4.44.3 -er "$1" -
  fi
}
image_for() { yaml '.services[strenv(KUBO_SERVICE)].image'; }
if [ "${1:-}" = --install ]; then
  self=$(cd "$(dirname "$0")" && pwd)/$(basename "$0")
  root=$(git rev-parse --show-toplevel) || fail 'Open a Git repository first.'
  cd "$root"
  [ -f "$manifest" ] || fail 'Export your project YAML to .kubo/kubo.yaml first.'
  git remote get-url origin >/dev/null || fail 'Configure the origin remote first.'
  if git config --get core.hooksPath >/dev/null; then
    fail 'This repository uses a hook manager. Keep its configuration and ask its maintainer to integrate the KuboRun hook.'
  fi
  hooks=$(git rev-parse --git-path hooks)
  hook=$hooks/pre-push
  if [ -L "$hook" ] || { [ -e "$hook" ] && ! cmp -s "$self" "$hook"; }; then
    fail "Existing hook preserved: $hook. Ask its maintainer to integrate KuboRun."
  fi
  docker buildx version >/dev/null || fail 'Install Docker with Buildx, then try again.'
  services=$(yaml '.services | keys | .[]' < "$manifest")
  KUBO_SERVICE=${2:-$services}
  case "$KUBO_SERVICE" in
    *'
'*) printf 'Choose a service, then run: sh pre-push.sh --install SERVICE [BRANCH]\n%s\n' "$services" >&2; exit 1 ;;
  esac
  export KUBO_SERVICE
  image=$(image_for < "$manifest") || fail 'Choose a service with a tagged image.'
  case "${image##*/}" in *:latest|*:|*@*) fail 'Use a unique version tag in the manifest.' ;; *:*) ;; *) fail 'Set an explicit version tag on the service image.' ;; esac
  default_branch=$(git symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null || echo origin/main)
  branch=${3:-${default_branch#origin/}}
  git check-ref-format --branch "$branch" >/dev/null
  mkdir -p "$hooks"
  if [ ! -f "$hook" ]; then
    (set -C; cat "$self" > "$hook") || fail 'Could not create hook.'
  fi
  git config --local kubo.deliveryService "$KUBO_SERVICE"
  git config --local kubo.imageRepository "${image%:*}"
  git config --local kubo.deliveryBranch "$branch"
  chmod +x "$hook"
  printf 'Installed for origin/%s, service %s (%s).\n' "$branch" "$KUBO_SERVICE" "${image%:*}"
  exit 0
fi

[ "$#" -eq 2 ] || fail 'Usage: sh pre-push.sh --install [SERVICE [BRANCH]]'
[ "$1" = origin ] || exit 0
branch=$(git config --local --get kubo.deliveryBranch)
KUBO_SERVICE=$(git config --local --get kubo.deliveryService)
export KUBO_SERVICE
repository=$(git config --local --get kubo.imageRepository)
while read -r local_ref commit remote_ref previous; do
  [ "$remote_ref" = "refs/heads/$branch" ] || continue
  [ "$local_ref" != "(delete)" ] || continue
  image=$(git show "$commit:$manifest" | image_for)
  case "$image" in
    "$repository":latest|"$repository":|*@*) fail 'Use a unique version tag.' ;;
    "$repository":*) ;;
    *) fail "Expected a version tag in $repository" ;;
  esac
  if git cat-file -e "$previous:$manifest" 2>/dev/null; then
    old=$(git show "$previous:$manifest" | image_for)
    [ "$old" != "$image" ] || continue
  fi
  archive=$(mktemp)
  trap 'rm -f "$archive"' 0
  git archive --format=tar "$commit" > "$archive"
  platform=$(git config --local --get kubo.deliveryPlatform || echo linux/amd64)
  docker buildx build --platform "$platform" --tag "$image" --push - < "$archive"
  rm -f "$archive"
  trap - 0
done
