#!/bin/bash
set -e

# Configuration from environment variables
VAULT_REPO="${VAULT_REPO:-}"
VAULT_BRANCH="${VAULT_BRANCH:-main}"
SYNC_INTERVAL="${SYNC_INTERVAL:-30}"
CONTENT_DIR="/usr/src/app/content"

# Logging function
log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}

# Initialize vault content
init_vault() {
    log "Initializing vault from $VAULT_REPO (branch: $VAULT_BRANCH)"
    
    if [ -z "$VAULT_REPO" ]; then
        log "ERROR: VAULT_REPO not set. Using pre-existing content."
        return 0
    fi
    
    # Remove existing content if it exists and is a git repo
    if [ -d "$CONTENT_DIR/.git" ]; then
        log "Content directory is a git repo, pulling latest changes..."
        cd "$CONTENT_DIR"
        git fetch origin "$VAULT_BRANCH"
        git reset --hard "origin/$VAULT_BRANCH"
        cd /usr/src/app
    else
        log "Content directory is not a git repo, cloning..."
        rm -rf "$CONTENT_DIR"
        git clone --depth 1 --branch "$VAULT_BRANCH" "$VAULT_REPO" "$CONTENT_DIR"
    fi
    
    log "Vault synchronized successfully"
}

# Sync vault periodically in background
sync_vault_loop() {
    while true; do
        sleep "$SYNC_INTERVAL"
        log "Checking for vault updates..."
        
        if [ -d "$CONTENT_DIR/.git" ]; then
            cd "$CONTENT_DIR"
            # Check if there are remote changes
            git fetch origin "$VAULT_BRANCH" 2>/dev/null || continue
            
            LOCAL=$(git rev-parse HEAD)
            REMOTE=$(git rev-parse "origin/$VAULT_BRANCH")
            
            if [ "$LOCAL" != "$REMOTE" ]; then
                log "Vault changes detected, pulling..."
                git reset --hard "origin/$VAULT_BRANCH"
                log "Vault updated. Note: Quartz build may need restart for changes to appear."
            else
                log "Vault is up to date"
            fi
            cd /usr/src/app
        fi
    done
}

# Initialize once on startup
init_vault

# Start sync loop in background
sync_vault_loop &
SYNC_PID=$!

log "Starting Quartz..."
# Run Quartz with proper signal handling
trap "kill $SYNC_PID 2>/dev/null || true" EXIT TERM INT
exec npx quartz build --serve

