#!/bin/bash
#
# Copyright (C) 2023-2025 Eugene 'Vindex' Stulin
# Distributed under the Boost Software License 1.0.

set -eu -o pipefail

# The function prints help information.
Print_Help() {
cat <<EndOfHelp
The script saves single frame from the specified video.
The frame is saved to the current directory.

Usage:
    ${0##*/} <input/video/path> <time1> [-o <path>]
Time format: HH:MM:SS (hours, minutes, seconds). Hours are optional.

Help and version:
    ${0##*/} --help|-h
    ${0##*/} --version|-v
EndOfHelp
}


# The function prints the script version.
Print_Version() {
    local VERSION_SCRIPT="$(dirname -- "${BASH_SOURCE[0]}")/bbsi-version"
    "$VERSION_SCRIPT"
}


# The function prints information about wrong usage to stderr.
Wrong_Usage() {
    echo "Wrong usage. See: ${0##*/} --help" >&2
}


# parse command line arguments
CUSTOM_PATH=""
OPT_TEMP=$(getopt -o 'o:hv' --long 'help,version' -n "$0" -- "$@")
eval set -- "$OPT_TEMP"
while true; do
    case "$1" in
        '-o')
            CUSTOM_PATH="$2"
            shift 2
            continue
            ;;
        '-h'|'--help')
            # getopt adds "--" as argument
            if [[ $# -ne 2 ]]; then
                Wrong_Usage
                exit 1
            fi
            Print_Help
            exit 0
            ;;
        '-v'|'--version')
            # getopt adds "--" as argument
            if [[ $# -ne 2 ]]; then
                Wrong_Usage
                exit 1
            fi
            Print_Version
            exit 0
            ;;
        '--')
            shift
            break
            ;;
        *)
            echo "Internal error" >&2
            exit 1
    esac
done

if [[ $# -ne 2 ]]; then
    Wrong_Usage
    exit 1
fi


readonly MEDIAFILE="$1"
readonly TIME="$2"


Check_Time_Format() {
    local TF='^([0-9]{1,2}:)?[0-5]?[0-9]:[0-5][0-9](\.[0-9]{1,5})?$'
    if ! [[ "$1" =~ $TF ]]; then
        Wrong_Usage
        exit 1
    fi
}
Check_Time_Format "${TIME}"

NAME="$(basename "$MEDIAFILE")"
NAME_WITHOUT_EXT="${NAME%.*}"

if [[ -z "$CUSTOM_PATH" ]]; then
    FRAME_FILE="${NAME_WITHOUT_EXT}.${TIME//:/}.png"
else
    FRAME_FILE="$CUSTOM_PATH"
fi


Interrupt_Execution() {
    set +x
    echo "The script has been interrupted." 2>&1
    rm -f "$MP4_FILE"
    exit 1
}
trap Interrupt_Execution ABRT INT QUIT TERM

set -x
if ! ffmpeg -hide_banner -ss "$TIME" -i "$MEDIAFILE" -frames:v 1 "$FRAME_FILE"
then
    set +x
    Interrupt_Execution
fi
set +x

echo "Saved as $FRAME_FILE."
