#!/bin/bash
# Omarchy Repository Database Manager
# Updates the repository database with all packages

set -e

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

ARCH=${ARCH:-x86_64}
BUILD_DIR="$BUILD_ROOT/build"
ARCH_DIR="$BUILD_ROOT/pkgs.omarchy.org/$ARCH"

# Function to update repository database using Docker
update_database() {
  print_info "Updating repository database in Docker container..."

  # Check Docker is available
  check_docker

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

  # Make output directory writable for container
  if [ "$(id -u)" -eq 0 ]; then
    chmod -R 777 "$ARCH_DIR"
  else
    sudo chown -R $(id -u):$(id -g) "$ARCH_DIR" 2>/dev/null || chmod -R 777 "$ARCH_DIR"
  fi

  # Build Docker image
  build_docker_image "$BUILD_DIR"

  # Run repo-add in Docker container
  docker run --rm \
    -e ARCH="$ARCH" \
    -v "$BUILD_ROOT/pkgs.omarchy.org:/output" \
    -v "$BUILD_DIR:/build:ro" \
    omarchy-aur-builder:latest /build/update-repo.sh
}

# Main execution
main() {
  print_header "Omarchy Repository Database Manager"

  # Parse command line arguments
  while [[ $# -gt 0 ]]; do
    case $1 in
    --arch)
      ARCH="$2"
      shift 2
      ;;
    -h | --help)
      echo "Usage: $0 [OPTIONS]"
      echo ""
      echo "Options:"
      echo "  --arch <arch>  Target architecture (x86_64 or aarch64, default: x86_64)"
      echo "  -h, --help     Show this help message"
      exit 0
      ;;
    *)
      print_error "Unknown option: $1"
      exit 1
      ;;
    esac
  done

  print_info "Target architecture: $ARCH"
  print_info "Output directory: $ARCH_DIR"

  update_database

  echo ""
  print_success "Repository update complete!"
}

# Run main function
main "$@"
