#!/bin/bash
# Sign all packages in build-output

set -e

BUILD_ROOT=$(realpath "${BASH_SOURCE[0]%/*}/..")
source "$BUILD_ROOT/helpers/message-helpers.sh"
source "$BUILD_ROOT/helpers/docker-helpers.sh"
source "$BUILD_ROOT/helpers/paths.sh"

print_header "Sign Packages"

# Parse arguments
while [[ $# -gt 0 ]]; do
  case $1 in
  --arch)
    ARCH="$2"
    update_arch_paths
    shift 2
    ;;
  --mirror)
    MIRROR="$2"
    update_arch_paths
    shift 2
    ;;
  -h | --help)
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  --arch <arch>      Target architecture (x86_64 or aarch64, default: x86_64)"
    echo "  --mirror <mirror>  Mirror to use (edge, rc, or stable, default: edge)"
    echo "  -h, --help         Show this help message"
    echo ""
    echo "This script signs all packages in build-output/"
    exit 0
    ;;
  *)
    print_error "Unknown option: $1"
    exit 1
    ;;
  esac
done

print_info "Target architecture: $ARCH"
print_info "Mirror: $MIRROR"
print_info "Build output: $BUILD_OUTPUT_DIR"

# Check if build output exists
if [[ ! -d "$BUILD_OUTPUT_DIR" ]]; then
  print_error "Build output directory not found: $BUILD_OUTPUT_DIR"
  print_warning "Run bin/repo build first"
  exit 1
fi

# Check the selected container engine is available
check_engine

# Check GPG credentials are in environment
if [[ -z "$GPG_PRIVATE_KEY" ]]; then
  print_error "GPG_PRIVATE_KEY environment variable not set"
  exit 1
fi

if [[ -z "$GPG_PASSPHRASE" ]]; then
  print_error "GPG_PASSPHRASE environment variable not set"
  exit 1
fi

# Signing is architecture-independent, so run its utility container natively
# on either an x86_64 or ARM host.
TOOL_ARCH=$(docker_native_arch) || {
  print_error "Unsupported host architecture: $(uname -m)"
  exit 1
}
build_docker_image "$BUILD_DIR" "$TOOL_ARCH" "$MIRROR"

print_info "Running package signing..."

# Rootless Podman uses keep-id and leaves host ownership/modes intact.
if [[ "$CONTAINER_ENGINE" == "docker" ]]; then
  make_dir_writable "$BUILD_OUTPUT_DIR"
fi

# Run the signing script in the host-native image.
"$CONTAINER_ENGINE" run "${CONTAINER_RUN_ARGS[@]}" --rm "$(get_platform_arg "$TOOL_ARCH")" \
  -e ARCH="$ARCH" \
  -e MIRROR="$MIRROR" \
  -e GPG_PRIVATE_KEY="$GPG_PRIVATE_KEY" \
  -e GPG_PASSPHRASE="$GPG_PASSPHRASE" \
  -v "$BUILD_ROOT/build-output:/build-output" \
  -v "$BUILD_DIR:/build:ro" \
  "omarchy-pkg-builder:latest-$TOOL_ARCH-$MIRROR" /build/sign.sh

SIGN_RESULT=$?

# Summary
echo ""
if [[ $SIGN_RESULT -eq 0 ]]; then
  print_success "Package signing completed successfully!"
else
  print_error "Package signing failed"
  exit $SIGN_RESULT
fi
