#!/bin/bash
# Usage info
show_help() {
cat << EOF
Usage: ${0##*/} [-hv] [-f OUTFILE] [FILE]...
Do stuff with FILE and write the result to standard output. With no FILE
or when FILE is -, read standard input.

    -h          display this help and exit
    -f INFILE  write the result to infile instead of standard output.
    -o OUTFILE write the result to OUTFILE instead of standard output.
EOF
}

# Initialize our own variables:
file=""
output=""

OPTIND=1
# Resetting OPTIND is necessary if getopts was used previously in the script.
# It is a good idea to make OPTIND local if you process options in a function.

while :; do
    case $1 in
        -h|-\?|--help)
            show_help    # Display a usage synopsis.
            exit
            ;;
        -f|--file)       # Takes an option argument; ensure it has been specified.
            if [ "$2" ]; then
                file=$2
                shift
            else
                die 'ERROR: "--file" requires a non-empty option argument.'
            fi
            ;;
        --file=?*)
            file=${1#*=} # Delete everything up to "=" and assign the remainder.
            ;;
        --file=)         # Handle the case of an empty --file=
            die 'ERROR: "--file" requires a non-empty option argument.'
            ;;
        -o|--ouput)       # Takes an option argument; ensure it has been specified.
            if [ "$2" ]; then
                output=$2
                shift
            else
                die 'ERROR: "--output" requires a non-empty option argument.'
            fi
            ;;
        --output=?*)
            output=${1#*=} # Delete everything up to "=" and assign the remainder.
            ;;
        --output=)         # Handle the case of an empty --file=
            die 'ERROR: "--output" requires a non-empty option argument.'
            ;;
        -v|--verbose)
            verbose=$((verbose + 1))  # Each -v adds 1 to verbosity.
            ;;
        --)              # End of all options.
            shift
            break
            ;;
        -?*)
            printf 'WARN: Unknown option (ignored): %s\n' "$1" >&2
            ;;
        *)               # Default case: No more options, so break out of the loop.
            break
    esac

    shift
done

if [ "$file" ]; then
    printf 'INPUT_FILE=<%s>\n' $file
    printf '=== CREATING AUDIO PEAKS === \n'
    audiowaveform -i $file --pixels-per-second 10 -b 8 -o $output
    sleep 5
    printf '=== NORMALIZING AUDIO PEAKS === \n'
    python /var/www/html/utils/jsonscale.py $output
    printf '=== NORMALIZED === \n'
fi
# End of file
printf '<%s> <%s>' $file $output
exit $?