#!/bin/bash
set -e

SOURCE_FILM="/home/seedbox-sync/film"
TARGET_FILM="/home/film/Fresh"
SORT_SCRIPT="/usr/local/bin/orion-sort-series"
REQUIRED_USER="film"
LOCK_FILE="/tmp/orion-media-sort.lock"

# 1. Help message
if [[ "$1" == "--help" ]] || [[ "$1" == "-h" ]]; then
    echo "Usage: $0"
    echo "Hardlinks media from $SOURCE_FILM to $TARGET_FILM"
    exit 0
fi

# 2. User check
if [ "$(whoami)" != "$REQUIRED_USER" ]; then
    echo "❌ ERROR: This script must be run as '$REQUIRED_USER'."
    exit 1
fi

# 3. Concurrency Lock
if [ -f "$LOCK_FILE" ]; then
    echo "⚠️  Sorting already in progress (lock exists). Skipping."
    exit 0
fi
trap 'rm -f "$LOCK_FILE"' EXIT
touch "$LOCK_FILE"

# 4. Change to neutral directory
cd /

echo "🔗 Starting media hardlinking as user 'film'..."

if [ -d "$SOURCE_FILM" ]; then
    mkdir -p "$TARGET_FILM"
    cd "$SOURCE_FILM"
    
    # We find files and check their hardlink count before linking
    find . -type f -print0 | while IFS= read -r -d '' EpisodePath
    do
        # Check hardlink count (stat -c %h)
        # If count > 1, it means it's already linked somewhere else (e.g. Series or manually moved)
        HL_COUNT=$(stat -c %h "$EpisodePath")
        if [ "$HL_COUNT" -gt 1 ]; then
            # Check if it exists in the target; if not, it means it was moved elsewhere
            # We skip it to avoid recreating it in 'Fresh'
            TargetFile="$TARGET_FILM/$EpisodePath"
            if [ ! -f "$TargetFile" ]; then
                echo "  -> Skipping $EpisodePath (already linked elsewhere)"
                continue
            fi
        fi
        
        # cp -al will safely skip if it already exists in the exact TargetFile location
        cp -al --parents "$EpisodePath" "$TARGET_FILM"/ 2>/dev/null || true
    done
    
    echo "⚖️  Fixing permissions on $TARGET_FILM..."
    chown -R film:film-admin "$TARGET_FILM"
    chmod -R 775 "$TARGET_FILM"
fi

if [ -x "$SORT_SCRIPT" ]; then
    "$SORT_SCRIPT"
fi

echo "✅ Media sorting completed."
exit 0
