#!/usr/bin/env bash
# Example post-receive hook for git repositories
# Copy this to your repository's hooks/post-receive and make it executable
#
# This hook uses systemd-run to execute gitmal generation in the background
# with automatic notifications via ntfy when the job completes.
#
# Optionally, it can also trigger remote builds on aomi.

set -euo pipefail

# Configuration
GITMAL_ENABLED="true"
GITMAL_THEME="github-dark"  # Options: github-dark, github-light, dark, light, auto
REMOTE_BUILD_ENABLED="false"  # Set to "true" to enable remote builds on aomi
BUILD_TYPE="nixos"             # Options: nixos, make, docker, go, custom, auto

REPO_PATH="$(pwd)"
REPO_NAME=$(basename "$REPO_PATH" .git)
TIMESTAMP=$(date +%Y%m%d-%H%M%S)

# 1. Generate gitmal (local static site on kerkouane)
if [ "$GITMAL_ENABLED" = "true" ]; then
  UNIT_NAME="git-gitmal-${REPO_NAME}-${TIMESTAMP}"
  echo "Queuing gitmal generation for $REPO_NAME with theme: $GITMAL_THEME..."

  sudo /run/current-system/sw/bin/systemd-run \
    --unit="$UNIT_NAME" \
    --description="Gitmal generation for $REPO_NAME" \
    --property="OnSuccess=git-notify@${UNIT_NAME}.service" \
    --property="OnFailure=git-notify@${UNIT_NAME}.service" \
    --property="User=vincent" \
    --property="Group=users" \
    --working-directory="$REPO_PATH" \
    /etc/git-hooks/generate-gitmal.sh "$REPO_PATH" "$GITMAL_THEME"

  echo "✓ Gitmal generation queued as: $UNIT_NAME"
  echo "  View status: systemctl status $UNIT_NAME"
  echo "  View logs:   journalctl -u $UNIT_NAME"
fi

# 2. Trigger remote build (on aomi)
if [ "$REMOTE_BUILD_ENABLED" = "true" ]; then
  /etc/git-hooks/forward-build.sh "$REPO_NAME" "$BUILD_TYPE"
fi
