#!/bin/bash

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

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

# Print header
print_header "Sync Repository to Remote"

# 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
    ;;
  --remote)
    REMOTE="$2"
    shift 2
    ;;
  --skip-prod-check)
    SKIP_PROD_CHECK=true
    shift
    ;;
  -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 or stable, default: edge)"
    echo "  --remote <remote>  Rclone remote destination (default: $DEFAULT_REMOTE)"
    echo "  --skip-prod-check  Skip production sync confirmation"
    echo "  -h, --help         Show this help message"
    exit 0
    ;;
  *)
    print_error "Unknown option: $1"
    exit 1
    ;;
  esac
done

print_info "Mirror: $MIRROR"
print_info "Architecture: $ARCH"
print_info "Local Repository: $REPO_DIR"
print_info "Remote: $REMOTE"
echo ""

# Check if local repo exists
if [[ ! -d "$REPO_DIR" ]]; then
  print_error "Local repository directory not found: $REPO_DIR"
  exit 1
fi

DESTINATION_DIRECTORY="$MIRROR/$ARCH"

# 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/$DESTINATION_DIRECTORY)"
  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/$DESTINATION_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 "$REPO_DIR" "$REMOTE/$DESTINATION_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 "$REPO_DIR" "$REMOTE/$DESTINATION_DIRECTORY" \
  --include "omarchy.*" \
  --checksum --copy-links -v

print_success "Sync complete!"
