#!/bin/bash
#
# Regenerate Proxy Videos for Last 60 Days
#
# This script submits all recordings from the last 60 days to pyProxy
# for re-encoding with updated ffmpeg settings (faststart + keyframe interval).
#
# Usage:
#   screen -S proxy-regen
#   cd /var/www/html/brettZone/backend
#   ./regenerateProxies.sh 2>&1 | tee regenerate.log
#
# The script is idempotent - safe to restart if interrupted.
# Uses reprocess=true flag to force re-encoding of existing videos.
#

set -e

# Configuration
DB_USER="root"
DB_PASS="mclab1024"
DB_NAME="matchdb"
PROXY_API="https://live.nhrl.io/proxyMaker/api/jobs"
DELAY_MS=100  # Delay between submissions in milliseconds (0 for no delay)

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo "=========================================="
echo "  Proxy Video Regeneration Script"
echo "=========================================="
echo ""
echo "Start time: $(date)"
echo ""

# Query for distinct s3paths from last 60 days
echo "Querying database for videos from last 60 days..."

QUERY="SELECT DISTINCT s3path FROM recordings WHERE s3http = 200 AND FROM_UNIXTIME(matchStart) >= DATE_SUB(NOW(), INTERVAL 60 DAY) ORDER BY matchStart DESC"

# Get the list of video URLs
VIDEO_URLS=$(mysql -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" -N -e "$QUERY" 2>/dev/null)

if [ -z "$VIDEO_URLS" ]; then
    echo -e "${RED}No videos found in the last 60 days.${NC}"
    exit 1
fi

# Count total videos
TOTAL=$(echo "$VIDEO_URLS" | wc -l)
echo -e "${GREEN}Found $TOTAL unique videos to regenerate.${NC}"
echo ""

# Counters
CURRENT=0
SUCCESS=0
FAILED=0
ALREADY_PROCESSING=0

# Process each video
while IFS= read -r VIDEO_URL; do
    CURRENT=$((CURRENT + 1))
    
    # Extract filename for display
    FILENAME=$(basename "$VIDEO_URL")
    
    # Show progress
    echo -n "[$CURRENT/$TOTAL] $FILENAME ... "
    
    # Submit to proxyMaker with reprocess=true
    RESPONSE=$(curl -s -X POST "$PROXY_API" \
        -H "Content-Type: application/json" \
        -d "{\"videoUrl\": \"$VIDEO_URL\", \"reprocess\": true}" \
        -w "\n%{http_code}" 2>/dev/null)
    
    # Extract HTTP status code (last line)
    HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
    # Extract JSON response (all but last line)
    JSON_RESPONSE=$(echo "$RESPONSE" | sed '$d')
    
    # Check response
    if [ "$HTTP_CODE" = "201" ]; then
        echo -e "${GREEN}Queued (new)${NC}"
        SUCCESS=$((SUCCESS + 1))
    elif [ "$HTTP_CODE" = "200" ]; then
        # Check if it's processing or was resubmitted
        STATUS=$(echo "$JSON_RESPONSE" | grep -o '"status":"[^"]*"' | cut -d'"' -f4)
        if [ "$STATUS" = "processing" ] || [ "$STATUS" = "pending" ]; then
            echo -e "${YELLOW}Already $STATUS${NC}"
            ALREADY_PROCESSING=$((ALREADY_PROCESSING + 1))
        else
            echo -e "${GREEN}Resubmitted${NC}"
            SUCCESS=$((SUCCESS + 1))
        fi
    else
        echo -e "${RED}Failed (HTTP $HTTP_CODE)${NC}"
        echo "  Response: $JSON_RESPONSE"
        FAILED=$((FAILED + 1))
    fi
    
    # Optional delay between submissions
    if [ "$DELAY_MS" -gt 0 ]; then
        sleep $(echo "scale=3; $DELAY_MS/1000" | bc)
    fi
    
done <<< "$VIDEO_URLS"

echo ""
echo "=========================================="
echo "  Regeneration Complete"
echo "=========================================="
echo ""
echo "End time: $(date)"
echo ""
echo "Summary:"
echo "  Total videos:        $TOTAL"
echo -e "  ${GREEN}Successfully queued:   $SUCCESS${NC}"
echo -e "  ${YELLOW}Already processing:    $ALREADY_PROCESSING${NC}"
echo -e "  ${RED}Failed:                $FAILED${NC}"
echo ""
echo "Monitor progress at: https://live.nhrl.io/proxyMaker/"
echo ""



