#!/bin/bash

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

# Default remote (production)
DEFAULT_REMOTE="pkgs.omarchy.org:omarchy-pkgs"
REMOTE="$DEFAULT_REMOTE"
SKIP_PROD_CHECK=false

# Parse arguments
if [ $# -eq 0 ] || [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]]; then
  echo "Usage: $0 <directory> [options]"
  echo ""
  echo "Options:"
  echo "  --remote <remote>      Rclone remote destination (default: $DEFAULT_REMOTE)"
  echo "  --skip-prod-check      Skip production sync confirmation"
  echo ""
  echo "Examples:"
  echo "  $0 pkgs.omarchy.org/x86_64                      # Sync to production (with confirmation)"
  echo "  $0 pkgs.omarchy.org/x86_64 --remote dev-pkgs:/  # Sync to dev remote"
  echo "  $0 pkgs.omarchy.org/x86_64 --skip-prod-check    # Sync without confirmation"
  exit 0
fi

DIRECTORY="$1"
shift

# Parse optional arguments
while [[ $# -gt 0 ]]; do
  case $1 in
  --remote)
    REMOTE="$2"
    shift 2
    ;;
  --skip-prod-check)
    SKIP_PROD_CHECK=true
    shift
    ;;
  *)
    print_error "Unknown option: $1"
    exit 1
    ;;
  esac
done

# Check if syncing to production and warn user
if [[ "$REMOTE" == "$DEFAULT_REMOTE" ]] && [[ "$SKIP_PROD_CHECK" != true ]]; then
  print_warning "You are about to sync to PRODUCTION ($REMOTE)"
  echo ""
  read -p "Are you sure you want to sync to production? (y/N) " -n 1 -r
  echo
  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    print_info "Sync cancelled"
    exit 0
  fi
fi

print_info "Syncing to: $REMOTE/$(basename $DIRECTORY)"

# First sync packages (excluding database files to ensure packages are uploaded first)
# Use --ignore-existing to not overwrite different versions already on remote
print_info "Syncing packages..."
rclone sync "$DIRECTORY" "$REMOTE/$(basename $DIRECTORY)" \
  --exclude "omarchy.db*" \
  --exclude "omarchy.files*" \
  --ignore-existing \
  --copy-links --delete-after -v

# Then sync database files last to ensure repository integrity
print_info "Updating repository database..."
rclone copy "$DIRECTORY" "$REMOTE/$(basename $DIRECTORY)/" \
  --include "omarchy.*" \
  --checksum --copy-links -v

print_success "Sync complete!"
