#!/bin/bash
set -e  # Exit immediately if any command fails

# Capture the Maestro Cloud URL from logs
export MAESTRO_CLOUD_URL=$(grep -o 'https://app\.robintest\.com/[^ ]*' $WORKSPACE/build/testservercontroller/workspace/lastMaestroRun.log | tail -1)  #tail -1 grabs only the last url of the output

# Fail if URL is not found
if [ -z "$MAESTRO_CLOUD_URL" ]; then
    echo "Error: Could not find Maestro Cloud URL from previous Maestro run."
    exit 1
fi

echo "Detected Maestro Cloud URL: $MAESTRO_CLOUD_URL"

# Ensure download directory exists and is clean
DOWNLOAD_DIR="cypress/downloads"
URL_FILE="$DOWNLOAD_DIR/video_urls.txt"
mkdir -p "$DOWNLOAD_DIR"
rm -f "$URL_FILE" # Remove old file to ensure fresh run

# Run Cypress ---

echo "Starting Cypress to extract video URLs..."

# Run Cypress
npm install
npx cypress run --browser chrome --env \
maestroEmail="${MAESTRO_EMAIL}",\
projectUrl="$MAESTRO_CLOUD_URL",\
recivoApiKey="${RECIVO_API_KEY}",\
recivoOrgId="${RECIVO_ORG_ID}"


# Check Cypress Exit Code
EXIT_CODE=$?
if [ $EXIT_CODE -ne 0 ]; then
    echo "Cypress tests failed with exit code $EXIT_CODE"
    exit $EXIT_CODE
fi

#  Download Videos using Wget ---

if [ -f "$URL_FILE" ]; then
    echo "------------------------------------------------"
    echo "Video URL file found. Starting downloads..."
    echo "------------------------------------------------"

    # Loop through each line of the file
    while IFS= read -r line; do
        # Skip empty lines
        [ -z "$line" ] && continue

        # Extract URL (matches http...)
        url=$(echo "$line" | grep -o 'http.*')

        # Extract Name (everything before the : http part)
        clean_name=$(echo "$line" | sed "s/: http.*//")

        echo "Downloading: $clean_name"

        #Define Output Filename
         outfile="$DOWNLOAD_DIR/${clean_name}.mp4"

        # Download (Use || true to prevent script exit if one video fails)
        wget -q -O "$outfile" "$url" || echo "Warning: Failed to download $clean_name"

    done < "$URL_FILE"

    echo "------------------------------------------------"
    echo "Downloads completed in $DOWNLOAD_DIR"
    ls -lh "$DOWNLOAD_DIR"/*.mp4 2>/dev/null || echo "No mp4 files found."

else
    echo "Warning: $URL_FILE was not generated by Cypress. No videos to download."
fi

echo "Process completed successfully."