#!/bin/bash

# Path to the PHP script
PHP_SCRIPT="/var/www/wordpress/weather.php"

# Path to the output image
IMAGE_PATH="/var/www/wordpress/weather_report.png"

# Path to the output video
VIDEO_PATH="/var/lib/ffplayout/tv-media/weather/weather_report.mp4"
NOAA_MAP_URL="https://www.wpc.ncep.noaa.gov/noaa/noaad1.gif?1639641009"
NOAA_MAP_GIF="/var/lib/ffplayout/scripts/noaa_map.gif"
NOAA_MAP_PNG="/var/lib/ffplayout/scripts/noaa_map.png"  # Converted PNG file
MUSIC_FILE="/var/lib/ffplayout/scripts/music.mp3"

# Run the PHP script to generate the image
php "$PHP_SCRIPT"

# Step 2: Download the NOAA map image
curl -o "$NOAA_MAP_GIF" "$NOAA_MAP_URL"

# Step 3: Convert the GIF to a single-frame PNG
ffmpeg -i "$NOAA_MAP_GIF" -vf "select=eq(n\,0),scale=1280:720,setsar=1" -vframes 1 -y "$NOAA_MAP_PNG"

# Step 4: Check if both images were generated/downloaded successfully
if [ -f "$IMAGE_PATH" ] && [ -f "$NOAA_MAP_PNG" ]; then
    # Step 5: Create individual videos
    ffmpeg -loop 1 -i "$IMAGE_PATH" -t 15 -c:v libx264 -pix_fmt yuv420p -y /var/lib/ffplayout/tv-media/weather/part1.mp4
    ffmpeg -loop 1 -i "$NOAA_MAP_PNG" -t 15 -c:v libx264 -pix_fmt yuv420p -y /var/lib/ffplayout/tv-media/weather/part2.mp4

    # Step 6: Concatenate the videos
    ffmpeg -i /var/lib/ffplayout/tv-media/weather/part1.mp4 -i /var/lib/ffplayout/tv-media/weather/part2.mp4 -filter_complex "[0:v][1:v]concat=n=2:v=1:a=0[v]" -map "[v]" -y /var/lib/ffplayout/tv-media/weather/combined.mp4

    # Step 7: Add audio
    ffmpeg -i /var/lib/ffplayout/tv-media/weather/combined.mp4 -i "$MUSIC_FILE" -c:v copy -c:a aac -shortest -y "$VIDEO_PATH"

    # Check if the video was created successfully
    if [ -f "$VIDEO_PATH" ]; then
        echo "Video generated successfully: $VIDEO_PATH"
    else
        echo "Failed to generate video."
    fi
else
    echo "Failed to generate/download one or both images."
fi

rm /var/lib/ffplayout/tv-media/weather/part1.mp4
rm /var/lib/ffplayout/tv-media/weather/part2.mp4
rm /var/lib/ffplayout/tv-media/weather/combined.mp4
