#!/bin/bash

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

dir_root=$SCRIPT_DIR"/"
zip_output=$SCRIPT_DIR"/"
file_xslt="$SCRIPT_DIR/roles.xslt"
file_name="All roles and resource.csv"
extension="*.zip"
file_prefix=true
allow_old_files=fals
delete_matrix=false
password=true

delimit_if_spaces()
{
  filename="$@"
  if [[ "$@" =~ ( |\') ]]; then
    filename="\"$@\""
  fi
  echo $filename
}

do_help()
{
  echo;
  echo "Script usage flags: [-s] [-m] [-i] [-x] [-o] [-f] [-b] [-a] [-d] [-q] [-p]"
  echo;
  echo "-s"
  echo "    The directory to scan for files using the file mask"
  echo "    Default : "$(delimit_if_spaces $dir_root)
  echo "-m"
  echo "    The file mask applied when scanning for files"
  echo "    Default : "$(delimit_if_spaces $extension)
  echo "-i"
  echo "    The full path to the input file which the XSLT stylesheet runs against"
  echo "-x"
  echo "    The full path of the XSLT stylesheet"
  echo "    Default : "$(delimit_if_spaces $file_xslt)
  echo "-o"
  echo "    The directory where the output file is placed"
  echo "    Default : "$(delimit_if_spaces $zip_output)
  echo "-f"
  echo "    Suffix assigned to the output file"
  echo "    Default : "$(delimit_if_spaces $file_name)
  echo "-b"
  echo "    Prepend current date to output file (true | false)"
  echo "    Default : $file_prefix"
  echo "-a"
  echo "    Process files where creation date is in the past; only valid with the -d option (true | false)"
  echo "    Default : $allow_old_files"
  echo "-d"
  echo "    Delete input file; only valid with the -d option (true | false)"
  echo "    Default : $delete_matrix";
  echo "-q"
  echo "    Partial name of the Role to query for"
  echo "-p"
  echo "    Use a password with 7z when extracting the input file (true | false)"
  echo "    Default : $password"
  echo;
  exit 0;
}

while getopts ":hi:s:m:o:x:f:b:a:d:q:p:" opt; do
  case $opt in
    h) do_help ;;
    i) matrix_file="$OPTARG" ;;
    s) dir_root="$OPTARG" ;;
    m) extension="$OPTARG" ;;
    o) zip_output="$OPTARG" ;;
    x) file_xslt="$OPTARG" ;;
    f) file_name="$OPTARG" ;;
    b) file_prefix="$OPTARG" ;;
    a) allow_old_files="$OPTARG" ;;
    d) delete_matrix="$OPTARG" ;;
    q) query="$OPTARG" ;;
    p) password="$OPTARG" ;;
    \?) echo "Invalid option" ;;
    :) echo "Error: Option -$OPTARG requires an argument." >&2; exit 1 ;;
  esac
done

echo;

if [ ! -z $matrix_file ]; then
  allow_old_files=true
  delete_matrix=false
  if [ $password != true ]; then
    password=false
  fi
fi

dir_root=$(echo $dir_root | sed 's:/*$::')"/"
zip_output=$(echo $zip_output | sed 's:/*$::')"/"

if [ -z $matrix_file ]; then
  zips="$dir_root""$extension"
  matrix_file=$(ls $zips | tail -n 1)
fi

start_time=$(date)
today_date=$(date +"%Y.%m.%d")

echo "Allow old files  : "$allow_old_files
echo "Use password     : "$password
echo "Delete matrix    : "$delete_matrix
echo "Use file prefix  : "$file_prefix
echo "Root directory   : "$(delimit_if_spaces $dir_root)
echo "Output directory : "$(delimit_if_spaces $zip_output)
echo "XSLT file        : "$(delimit_if_spaces $file_xslt)
echo "Matrix file      : "$(delimit_if_spaces $matrix_file)

if [[ "$query" =~ ^.+$ ]]; then
  echo "Role query text  : "$(delimit_if_spaces $query);
fi

if [ -z "$matrix_file" ] || [ ! -f "$matrix_file" ]; then
  echo
  echo "Found no files to process!"
  echo
  exit 0
fi

echo
echo "Matrix zipped    : "$(delimit_if_spaces $matrix_file)

check_date=$(date +"%Y-%m-%d")
filetime=$(find $matrix_file -type f -newermt $check_date)
if [ $allow_old_files = false ]; then
  if [[ "$filetime" =~ ^$ ]]; then
    echo
    echo "The file [$(basename $matrix_file)] is older than today. Not allowed!"
    echo
    exit 0
  fi
fi

matrix_file_name=$(basename $matrix_file)
IFS='_' read -ra ADDR <<< "$matrix_file_name"

begin="${ADDR[0]}"

zipcmd=(7z);
zipcmd+=(x);
zipcmd+=($matrix_file);
zipcmd+=(-aoa);

if [ $password == 'true' ]; then
  password="${begin: -4}.${ADDR[1]}.${ADDR[2]}"
  zipcmd+=(-p$password);
fi

echo "ZIP password     : "$(delimit_if_spaces $password)
zipcmd+=(-o$zip_output);
zipcmd+=(*.xml);

"${zipcmd[@]}"

dir_extracted_files="$zip_output${begin: -4}_${ADDR[1]}_${ADDR[2]}*.xml"
file=$(ls $dir_extracted_files | tail -n 1)

filesize=$(wc -c $file | awk '{print $1}')
if [ ! -f $file ] || [ $filesize = 0 ]; then
  echo
  echo "Something went wrong"
  echo
  exit 0
fi

echo
echo "Matrix XML file : "$(delimit_if_spaces $file)

if [ $file_prefix = true ]; then
  output_starting="${begin: -4}_${ADDR[1]}_${ADDR[2]}"
  output_ending="_run_on""_"$(date +"%Y_%m_%d_%H_%M_%S")""_"$file_name"
  echo "Output starting : "$(delimit_if_spaces $output_starting)
  echo "Output ending   : "$(delimit_if_spaces $output_ending)
  output_file="$zip_output""$output_starting""$output_ending"
else
  output_file="$zip_output""$file_name"
fi

cmd=(xsltproc);
cmd+=(--output);
cmd+=("$output_file");

if [[ "$query" =~ ^.+$ ]]; then
  cmd+=(--stringparam role_name "$query");
fi

cmd+=($file_xslt);
cmd+=($file);

"${cmd[@]}"
echo

if [ -f "$output_file" ]; then
  echo "File written    : "$(delimit_if_spaces $output_file)
fi

if [ $delete_matrix = true ] && [ -f "$matrix_file" ]; then
  echo "Deleting file   : "$(delimit_if_spaces $file)
  remove=$(rm $file)
fi

end_time=$(date)
echo
echo "End Date   : "$end_time
echo "Start Date : "$start_time
echo

exit 0