#!/bin/bash

# Abort if anything fails
set -e

# Source common functions
BUILD_ROOT=$(realpath "${BASH_SOURCE[0]%/*}/..")
source "$BUILD_ROOT/lib/common.sh"

# Prepare build directories
ARCH_DIR="$BUILD_ROOT/x86_64"
SRC_DIR="$BUILD_ROOT/src"
BUILD_DIR="$BUILD_ROOT/build"

# Create directories if they don't exist
mkdir -p "$ARCH_DIR" "$SRC_DIR"

# Check for Docker
if ! command -v docker &>/dev/null; then
  print_error "Docker is not installed"
  exit 1
fi

# Check if Docker daemon is running
if ! docker info &>/dev/null; then
  print_error "Docker daemon is not running"
  print_warning "Start Docker with: sudo systemctl start docker"
  exit 1
fi

print_header "Omarchy AUR Package Builder"

# Parse command line arguments
while [[ $# -gt 0 ]]; do
  case $1 in
  -h | --help)
    echo "Usage: $0"
    echo ""
    echo "This script builds AUR packages from:"
    echo "  build/packages/omarchy-aur.packages"
    echo ""
    exit 0
    ;;
  *)
    print_error "Unknown option: $1"
    exit 1
    ;;
  esac
done

# Check if AUR package list exists
if [[ ! -f "$BUILD_DIR/packages/omarchy-aur.packages" ]]; then
  print_error "omarchy-aur.packages not found at $BUILD_DIR/packages/"
  exit 1
fi

# Get GPG key from 1Password or environment for signing
if [[ -z "$GPG_PRIVATE_KEY" ]]; then
  print_info "Fetching GPG signing key from 1Password..."
  GPG_PRIVATE_KEY=$(op document get "Omarchy GPG Private Key" --account=omarchy.1password.com) || {
    print_error "Failed to fetch GPG key from 1Password or environment"
    exit 1
  }
else
  print_info "Using existing GPG signing key from environment"
fi
export GPG_PRIVATE_KEY="$GPG_PRIVATE_KEY"

# Get passphrase from 1Password or environment
if [[ -z "$GPG_PASSPHRASE" ]]; then
  print_info "Fetching GPG key passphrase from 1Password..."
  GPG_PASSPHRASE=$(op item get "Omarchy GPG Private Key" --account=omarchy.1password.com --fields password --reveal) || {
    print_error "Failed to fetch GPG passphrase from 1Password or environment"
    exit 1
  }
else
  print_info "Using existing GPG passphrase from environment"
fi
export GPG_PASSPHRASE
print_success "GPG signing key and passphrase loaded"

# Build/update the Docker image
print_info "Building Docker image..."
docker build -t omarchy-aur-builder:latest -f "$BUILD_DIR/Dockerfile" "$BUILD_DIR"

print_info "Running AUR package build..."
# Build Docker arguments
DOCKER_ARGS=(
  --rm
  -e GPG_PRIVATE_KEY
  -e GPG_PASSPHRASE
  -v "$ARCH_DIR:/output"
  -v "$SRC_DIR:/src"
  -v "$BUILD_DIR:/build:ro"
)

# Use local pacman cache if you already have one on host to speed up repeat runs
if [ -d "/var/cache/pacman/pkg" ]; then
  DOCKER_ARGS+=(-v "/var/cache/pacman/pkg:/var/cache/pacman/pkg")
fi

# Run the builder with assembled args
docker run "${DOCKER_ARGS[@]}" omarchy-aur-builder:latest /build/build.sh

# Clear the GPG key and passphrase from environment
unset GPG_PRIVATE_KEY
unset GPG_PASSPHRASE

BUILD_RESULT=$?

# Summary
echo ""
if [[ $BUILD_RESULT -eq 0 ]]; then
  print_success "AUR build completed successfully!"
  echo ""
  print_info "Next steps:"
  echo "  1. Run ./bin/update-repo to update the repository"
  echo "  2. Commit and push changes"
else
  print_warning "Some AUR packages failed (see details above)"
  exit $BUILD_RESULT
fi
