#!/bin/bash
#
# Copyright (C) 2023-2024 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 new mediafile from source one without some piece
(from time1 to time2).

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

Example:
    $0 video.mp4 02:10 03:35
Result is saved to output.mp4 (extension depends on source video).

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 && $# -ne 3 ]]; then
    Wrong_Usage
    exit 1
fi

readonly MEDIAFILE="$1"
readonly START="$2"
readonly FINISH="$3"

EXT="${MEDIAFILE##*.}"
OUTFILE="output.$EXT"
FRAGM1="tmp-1.$EXT"
FRAGM2="tmp-2.$EXT"
FRAG_LIST="tmp-list.txt"


# The function saves first part of mediafile
# using global variables MEDIAFILE and START.
# Parameters:
#     $1 - path to output file.
Extract_Begin() {
    ffmpeg -hide_banner -i "$MEDIAFILE" -to "$START" -c copy "$1"
}


# The function saves second part of mediafile
# using global variables MEDIAFILE and FINISH.
# Parameters:
#     $1 - path to output file.
Extract_Tail() {
    ffmpeg -hide_banner -i "$MEDIAFILE" -ss "$FINISH" -c copy "$1"
}


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

Exit() {
    set +x
    rm -f "$FRAGM1" "$FRAGM2" "$FRAG_LIST"
}
trap Exit EXIT


# save media file fragment
set -x
if [[ "$START" == "00:00" || "$START" == "00:00:00" ]]; then
    if [[ -z "$FINISH" ]]; then
        cp -- "$MEDIAFILE" "$OUTFILE"
    else
        Extract_Tail "$OUTFILE"
    fi
elif [[ -z "$FINISH" ]]; then
    Extract_Begin "$OUTFILE"
else
    Extract_Begin "$FRAGM1"
    Extract_Tail "$FRAGM2"
    # concatenate two videos
    printf %s "file '$FRAGM1'\nfile '$FRAGM2'\n" >  "$FRAG_LIST"
    ffmpeg -hide_banner -f concat -safe 0 -i "$FRAG_LIST" -c copy "$OUTFILE"
fi
set +x

echo "Saved to $OUTFILE."
