#!/bin/bash

# Video chop script - extracts a portion of a video file using ffmpeg
# Usage: video-chop.sh <video_file> <start_seconds> <end_seconds>

set -e

# Check if all required parameters are provided
if [ $# -ne 3 ]; then
    echo "Usage: $0 <video_file> <start_seconds> <end_seconds>"
    echo "Example: $0 /path/to/video.mp4 10 30"
    echo "  This will extract from second 10 to second 30"
    exit 1
fi

VIDEO_FILE="$1"
START_SECONDS="$2"
END_SECONDS="$3"

# Validate that the video file exists
if [ ! -f "$VIDEO_FILE" ]; then
    echo "Error: Video file '$VIDEO_FILE' not found"
    exit 1
fi

# Validate that start and end are numbers
if ! [[ "$START_SECONDS" =~ ^[0-9]+\.?[0-9]*$ ]]; then
    echo "Error: Start seconds must be a valid number"
    exit 1
fi

if ! [[ "$END_SECONDS" =~ ^[0-9]+\.?[0-9]*$ ]]; then
    echo "Error: End seconds must be a valid number"
    exit 1
fi

# Validate that end is greater than start
if (( $(echo "$END_SECONDS <= $START_SECONDS" | bc -l) )); then
    echo "Error: End seconds must be greater than start seconds"
    exit 1
fi

# Get the directory and filename
DIRNAME=$(dirname "$VIDEO_FILE")
BASENAME=$(basename "$VIDEO_FILE")

# Get the file extension
EXTENSION="${BASENAME##*.}"
FILENAME="${BASENAME%.*}"

# Generate timestamp prefix (YYYYMMDD_HHMMSS)
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")

# Create output filename with timestamp prefix
OUTPUT_FILE="${DIRNAME}/${TIMESTAMP}_${FILENAME}.${EXTENSION}"
AUDIO_OUTPUT_FILE="${DIRNAME}/${TIMESTAMP}_${FILENAME}.mp3"

# Calculate duration
DURATION=$(echo "$END_SECONDS - $START_SECONDS" | bc)

echo "Input file: $VIDEO_FILE"
echo "Start: ${START_SECONDS}s"
echo "End: ${END_SECONDS}s"
echo "Duration: ${DURATION}s"
echo "Output file: $OUTPUT_FILE"
echo "Audio output file: $AUDIO_OUTPUT_FILE"
echo ""

# Run ffmpeg to extract the portion
# Using -ss before -i for fast seeking, and -t for duration
ffmpeg -y -ss "$START_SECONDS" -i "$VIDEO_FILE" -t "$DURATION" -c copy "$OUTPUT_FILE"

# Extract audio only
ffmpeg -y -ss "$START_SECONDS" -i "$VIDEO_FILE" -t "$DURATION" -vn -q:a 2 "$AUDIO_OUTPUT_FILE"

echo ""
echo "Done! Output saved to: $OUTPUT_FILE"
echo "Audio saved to: $AUDIO_OUTPUT_FILE"
