#!/bin/bash
#
# Copyright (C) 2023 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>
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_file="$(dirname -- "${BASH_SOURCE[0]}")/bbsi_version"
    local vers
    vers="$(cat "$version_file" 2>/dev/null)" || vers="is unknown"
    echo "Bash-based set of instruments (bbsi), version $vers."
}


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


# parse command line arguments
if [[ $# -eq 1 ]]; then
    if [[ "$1" == "-h" || "$1" == "--help" ]]; then
        Print_Help
        exit 0
    elif [[ "$1" == "-v" || "$1" == "--version" ]]; then
        Print_Version
        exit 0
    else
        Wrong_Usage
        exit 1
    fi
elif [[ $# -ne 2 ]]; then
    Wrong_Usage
    exit 1
fi


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

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

SCREENSHOT="${NAME_WITHOUT_EXT}.${TIME//:/}.png"
set -x
ffmpeg -hide_banner -ss "$TIME" -i "$MEDIAFILE" -frames:v 1 ff-frame-%03d.png
mv ff-frame-001.png "$SCREENSHOT"
set +x

echo "Saved to $SCREENSHOT."
