#!/bin/bash
set -e

# Configuration
REMOTE_USER="seedbox-ssh"
REMOTE_HOST="seedbox.notsosoft.fr"
REMOTE_PATH="/home/downloader"
LOCAL_BASE="/home/seedbox-sync"
LOCK_FILE="/tmp/seedbox-sync.lock"
REQUIRED_USER="seedbox-sync"

# 1. Help message
if [[ "$1" == "--help" ]] || [[ "$1" == "-h" ]]; then
    echo "Usage: $0"
    echo "Syncs media from $REMOTE_HOST to $LOCAL_BASE"
    echo "Manual trigger: sudo systemctl start orion-seedbox-sync.service"
    exit 0
fi

# 2. User check
if [ "$(whoami)" != "$REQUIRED_USER" ]; then
    echo "❌ ERROR: This script must be run as '$REQUIRED_USER'."
    echo "👉 Recommended: sudo systemctl start orion-seedbox-sync.service"
    echo "👉 Alternative: sudo -u $REQUIRED_USER $0"
    exit 1
fi

# 3. Change to a neutral directory
cd /

# 4. Find any available SSH private key
SSH_KEY=$(find "$LOCAL_BASE/.ssh" -maxdepth 1 -name "id_*" ! -name "*.pub" 2>/dev/null | head -n 1)

# 5. Check for SSH Key
if [ -z "$SSH_KEY" ] || [ ! -f "$SSH_KEY" ]; then
    echo "❌ ERROR: No SSH private key found in $LOCAL_BASE/.ssh/"
    exit 1
fi

# 6. Check for Lock File
if [ -f "$LOCK_FILE" ]; then
    echo "⚠️  Sync already in progress."
    exit 0
fi

trap 'rm -f "$LOCK_FILE"' EXIT
touch "$LOCK_FILE"

# 7. Sync Media Function
sync_files() {
    local pass_name=$1
    echo "🚀 Starting $pass_name sync from $REMOTE_HOST..."
    
    # We do NOT use --delete here to avoid deleting unsorted local files
    rsync -avz \
        --chmod=g+r \
        --exclude 'Downloads' \
        --exclude '.*' \
        --exclude 'scripts' \
        -e "ssh -i $SSH_KEY -o BatchMode=yes -o ConnectTimeout=10" \
        "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH/" \
        "$LOCAL_BASE/"
}

# --- PRIMARY PASS ---
sync_files "primary"

# --- VERIFICATION PASS ---
sync_files "verification"

# 8. Selective Cleanup
# We only delete local files if they are GONE from remote AND have a local hardlink
echo "🧹 Checking for sorted files to clean up..."
# Use dry-run --delete to find what remote wants to delete
rsync -rz --dry-run --delete \
    --exclude 'Downloads' --exclude '.*' --exclude 'scripts' \
    -e "ssh -i $SSH_KEY -o BatchMode=yes -o ConnectTimeout=10" \
    "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH/" \
    "$LOCAL_BASE/" | grep "^deleting " | while read -r line; do
    
    # Extract relative path (line is "deleting path/to/file")
    RelPath=${line#deleting }
    FullPath="$LOCAL_BASE/$RelPath"
    
    if [ -f "$FullPath" ]; then
        HL_COUNT=$(stat -c %h "$FullPath")
        if [ "$HL_COUNT" -gt 1 ]; then
            echo "  -> Removing $RelPath (deleted on remote & already linked locally)"
            rm "$FullPath"
            # Optional: try to remove parent directories if they are now empty
            ParentDir=$(dirname "$FullPath")
            rmdir -p --ignore-fail-on-non-empty "$ParentDir" 2>/dev/null || true
        else
            echo "  -> Preserving $RelPath (deleted on remote but NOT linked yet)"
        fi
    fi
done

echo "✅ Sync and cleanup completed successfully."
exit 0
