#!/bin/bash

usage()
{
  echo
  echo "Usage: $PROG_NAME -u: url [-o: output] [-f: filename]"
  echo
  echo " -u      =   Url to process."
  echo " -o      =   Full absolute path to destination folder. If not specified //ket/Union/Public"
  echo " -f      =   Filename for the output file (.html). If not specified output_#currentdat#.html"
  echo
  exit 0
}

set_variable()
{
  local varname=$1
  shift
  if [ -z "${!varname}" ]; then
    eval "$varname=\"$@\""
  else
    echo "Error: $varname already set"
    usage
  fi
}

####################################################################
# Main script starts here

set_variable PROG_NAME "$(basename "$0")"
set_variable PROCESS_DATE $(date +"%Y%m%d%H%M")

if [[ $1 == "" ]]; then
    usage;
    exit;
else
    while getopts 'u:o:f:?h' c
    do
        case $c in
            u) set_variable URL "$OPTARG" ;;
            o) set_variable OUTPUT "$OPTARG" ;;
            f) set_variable FILENAME "$OPTARG" ;;
            h|?) usage ;; 
        esac
    done
fi

if [[ $OUTPUT == "" ]]; then set_variable OUTPUT "/mnt/user/Public"; fi
if [[ $FILENAME == "" ]]; then set_variable FILENAME "$PROCESS_DATE"output.html; fi



# ---------------
# Error Handling
# ---------------
set -e
trap 'catch $? $LINENO' EXIT

catch() {
  echo "catching!"
  if [ "$1" != "0" ]; then
    # error handling goes here
    echo "Error $1 occurred on $2 in $PROG_NAME"
  fi
}

#echo "$OUTPUT" +  " $URL" + " $FILENAME"


echo "$PROG_NAME: Processing $URL site ..."
docker run --rm -v "$OUTPUT":/usr/src/app/out capsulecode/singlefile "$URL" "$FILENAME"
echo ""
echo "**********************************************************************************"
echo "$PROG_NAME: Site page has been processed and is availbale at "$OUTPUT"/"$FILENAME""
echo "**********************************************************************************"
echo ""