#!/bin/bash

# Date: 2020-02-15T22:23Z

# Author: Steven Baltakatei Sandoval

# Description: `bkgettext` prints text between and including two
# specified tags.

# Usage:
#    $ bkgettext [ -s tagStart ]  [ -e tagEnd ]  [ -f file ]

echoerr() { echo "$@" 1>&2; } # function for outputing to stderr; see [3]
vc() { [ "$OPTION_VERBOSE" == "true" ] && return 0 || return 1; } # returns true if verbose mode active
print_help() { echoerr "Usage: [ -s tagStart ]  [ -e tagEnd ]  [ -f file ] "; } # print help
process_inputs() {
    # echoerr "process_inputs() \$1:""===""$1""==="
    # echoerr "process_inputs() \$2:""===""$2""==="
    # echoerr "process_inputs() \$3:""===""$3""==="
    # echoerr "process_inputs() \$4:""===""$4""==="
    # echoerr "process_inputs() \$5:""===""$5""==="
    # echoerr "process_inputs() \$6:""===""$6""==="
    # echoerr "process_inputs() \$7:""===""$7""==="
    # echoerr "process_inputs() \$8:""===""$8""==="
    
    while getopts "vhs:e:f:" options_array; do
    case "${options_array}" in
	v)
	    OPTION_VERBOSE="true"
	    vc && echoerr "DEBUG:Verbose mode active."
	    ;;
	h)
	    print_help; exit 1
	    ;;
	s)
	    tagStart=${OPTARG}
	    vc && echoerr "DEBUG:tagStart:""$tagStart"
	    ;;
	e)
	    tagEnd=${OPTARG}
	    vc && echoerr "DEBUG:tagEnd:""$tagEnd"
	    ;;
	f)
	    [ ! -f ${OPTARG} ] && echoerr "ERROR: Invalid file name provided." && exit 1;
	    fileInput=${OPTARG}
	    vc && echoerr "DEBUG:fileInput:""$fileInput"
	    ;;
	*)
	    echoerr "Error."
	    ;;
    esac
    done
    shift $((OPTIND-1))
}

main() {

    process_inputs "$@" # Define variables: tagStart tagEnd fileInput
    # echoerr "main() \$1:""===""$1""==="
    # echoerr "main() \$2:""===""$2""==="
    # echoerr "main() \$3:""===""$3""==="
    # echoerr "main() \$4:""===""$4""==="
    # echoerr "main() \$5:""===""$5""==="
    # echoerr "main() \$6:""===""$6""==="
    # echoerr "main() \$7:""===""$7""==="
    # echoerr "main() \$8:""===""$8""==="
    # echoerr "main() \$tagStart:""===""$tagStart""==="
    # echoerr "main() \$tagEnd:""===""$tagEnd""==="
    # echoerr "main() \$fileInput:""===""$fileInput""==="
    #OUTPUT=$(cat "$fileInput" | awk "/$tagStart/,/$tagEnd/") # get text between and including tag lines; see [1]
    #OUTPUT=$(cat "$fileInput" | awk "/$tagStart/{f=1;next} /$tagEnd/{f=0} f") # get text between tag lines; see [1]
    OUTPUT=$(cat "$fileInput" | awk "/$tagStart/{f=1} /$tagEnd/{f=0;print} f") # get text between and including tag lines; see [1]
    echo "$OUTPUT"
}

main "$@" # pass arguments to function "main" and execute "main" (for why `"$@"`, see [2])
exit 0 # exit normally



#===References===
# [1]: How to get text between and including specified strings: https://stackoverflow.com/a/22222219
# [2]: How to correctly pass bash script arguments to functions: https://stackoverflow.com/a/8198970
# [3]: How to print text to stderr instead of stdout: https://stackoverflow.com/a/2990533