#!/usr/bin/env bash

usage() {
    echo "Usage: $(basename "$0") file_name start end"
}

extract_images() {
    local video_file=$1
    local start=$2
    local end=$3
    local start_in_seconds
    local end_in_seconds
    local date_diff

    start_in_seconds=$(date --date "${start}" +%s)
    end_in_seconds=$(date --date "${end}" +%s)
    date_diff=$((end_in_seconds - start_in_seconds))

    ffmpeg -ss "${start}" -t ${date_diff} -i "${video_file}" -qscale:v 2 output_%03d.jpg
}

if [[ $# -ne 3 ]]; then
    usage
    exit 0
fi

if ! command -v ffmpeg >/dev/null 2>&1; then
    echo "ffmpeg: command not found"
    exit 1
fi

FILENAME=$1
START=$2
END=$3

if [ ! -f "${FILENAME}" ]; then
    echo "${FILENAME}: not a file"
    exit 1
fi
if ! { [[ ${START} =~ ^([0-9]{2}:)?[0-9]{2}:[0-9]{2}$ ]] && date -d "${START}" >/dev/null 2>&1; }; then
    echo "${START}: incorrect time"
    exit 1
fi
if ! { [[ ${END} =~ ^([0-9]{2}:)?[0-9]{2}:[0-9]{2}$ ]] && date -d "${END}" >/dev/null 2>&1; }; then
    echo "${END}: incorrect time"
    exit 1
fi

extract_images "${FILENAME}" "${START}" "${END}"
