#!/bin/bash
#
# Copyright (C) 2023-2026 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.
Incorrect_Usage() {
    echo "Incorrect 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
                Incorrect_Usage
                exit 1
            fi
            Print_Help
            exit 0
            ;;
        '-v'|'--version')
            # getopt adds "--" as argument
            if [[ $# -ne 2 ]]; then
                Incorrect_Usage
                exit 1
            fi
            Print_Version
            exit 0
            ;;
        '--')
            shift
            break
            ;;
        *)
            echo "Internal error" >&2
            exit 1
    esac
done

if [[ $# -ne 2 ]]; then
    Incorrect_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
        Incorrect_Usage
        exit 1
    fi
}
Check_Time_Format "${TIME}"


Show_Duration() {
    ffprobe -v error -show_entries format=duration \
        -of default=noprint_wrappers=1:nokey=1 "$1"
}


Calc_Seconds_From_Time_String() {
    local TS="$1"
    local SHORT_FORMAT='^[0-5]?[0-9]:[0-5][0-9](\.[0-9]{1,5})?$'  
    local LONG_FORMAT='^[0-9]{1,2}:[0-5]?[0-9]:[0-5][0-9](\.[0-9]{1,5})?$'
    local SECS=0
    local COUNTDOWN=0
    if [[ "$TS" =~ $SHORT_FORMAT ]]; then  # like 03:25
        COUNTDOWN=2
    elif [[ "$TS" =~ $LONG_FORMAT ]]; then  # like 01:03:25
        COUNTDOWN=3
    else
        Incorrect_Usage
        exit 1
    fi
    local ELEMS=$(echo $TS | sed 's/:/ /g')  # "MM:SS" -> "MM SS"
    for ELEM in $ELEMS; do
        if [[ $COUNTDOWN -eq 3 ]]; then
            ((SECS+=ELEM*60*60))
        elif [[ $COUNTDOWN -eq 2 ]]; then
            ((SECS+=ELEM*60))
        elif [[ $COUNTDOWN -eq 1 ]]; then
            SECS=$(echo "$SECS + $ELEM" | bc)
        fi
        ((COUNTDOWN--))
    done
    echo "$SECS"
}


DURATION=$(Show_Duration "$MEDIAFILE")
TIMESTAMP=$(Calc_Seconds_From_Time_String "$TIME")
if [[ 1 == $(echo "$TIMESTAMP > $DURATION" | bc) ]]; then
    echo "Too big timestamp: $TIME." >&2
    echo "The playback duration is shorter than the specified timestamp." >&2
    Incorrect_Usage
    exit 1
fi


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


if [[ -f "$FRAME_FILE" ]]; then
    if [[ "$(realpath "$FRAME_FILE")" == "$(realpath "$MEDIAFILE")" ]]; then
        Incorrect_Usage
        exit 1
    fi
    ANSWER=n
    echo "This file exists: $FRAME_FILE"
    echo -n "Delete it? Y/n >: "
    read ANSWER
    ANSWER=${ANSWER,,}  # to lower case
    if [[ $ANSWER == "y" || $ANSWER == "yes" || $ANSWER == "" ]]; then
        rm -f "$FRAME_FILE"
    else
        echo "Operation canceled."
        exit 0
    fi
fi


Interrupt_Execution() {
    set +x
    echo "The script has been interrupted." 2>&1
    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

if [[ -f "$FRAME_FILE" ]]; then
    echo "Saved as $FRAME_FILE."
fi
