#!/bin/bash
# Process sync for a specific mirror if state file exists
# Usage: process-sync <mirror>
# Example: process-sync edge

set -e

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

MIRROR="${1:-}"
STATE_DIR="${OMARCHY_STATE_DIR:-/root/.state}"

if [[ -z "$MIRROR" ]]; then
  print_error "Usage: $0 <mirror>"
  echo "  mirror: edge or stable"
  exit 1
fi

if [[ "$MIRROR" != "edge" && "$MIRROR" != "stable" ]]; then
  print_error "Invalid mirror: $MIRROR (must be 'edge' or 'stable')"
  exit 1
fi

STATE_FILE="$STATE_DIR/.sync-needed-$MIRROR"

print_header "Processing Sync for $MIRROR"

# Check if state file exists
if [[ ! -f "$STATE_FILE" ]]; then
  print_info "No sync needed for $MIRROR (state file not found)"
  exit 0
fi

print_info "State file found: $STATE_FILE"
print_info "Starting release workflow for $MIRROR..."

# Run the release workflow
if "$BUILD_ROOT/bin/repo" release --mirror "$MIRROR" --skip-prod-check; then
  print_success "Release completed successfully for $MIRROR"
  
  # Remove state file on success
  rm -f "$STATE_FILE"
  print_success "State file removed: $STATE_FILE"
else
  print_error "Release failed for $MIRROR"
  print_warning "State file retained for retry: $STATE_FILE"
  exit 1
fi
