#!/usr/bin/bash
# Copyright (C) California Institute of Technology (2024)
#
# This file is part of dqr-tasks.

# add help function 
Help()
{
   # Display Help
   echo "Wrapper script to tar and upload DQR results."
   echo
   echo "Syntax: tar_and_upload [-h|g|b|r|t|p|d]"
   echo "options:"
   echo "-h          Print this Help"
   echo "-g [arg]    GraceID"
   echo "-b [arg]    Base Directory"
   echo "-r [arg]    Revision"
   echo "-t [arg]    Task"
   echo "-p [arg]    Project"
   echo "-s [arg]    SSH port"
   echo "-R [arg]    Retriest"
   echo "-d [arg]    Temporary Directory"
   echo
}

# parse input args
while getopts "hg:b:r:t:p:s:R:d:" option; do
   case $option in
      h) # display Help
         Help
         exit;;
      g) # GraceID
         graceid=$OPTARG;;
      b) # Base Directory
         basedir=$OPTARG;;
      r) # Revision
         revision=$OPTARG;;
      t) # Task
         task=$OPTARG;;
      p) # Project
         project=$OPTARG;;
      s) # SSH port
         sshport=$OPTARG;;
      R) # retries
         retries=$OPTARG;;
      d) # Temp Dir
         temp_dir=$OPTARG;;
   esac
done

# check that we have all variables
if [ -z ${graceid+x} ]; then echo "GraceID is not provided, exiting"; exit; fi
if [ -z ${basedir+x} ]; then echo "Base Directory is not provided, exiting"; exit; fi
if [ -z ${revision+x} ]; then echo "Revision is not provided, exiting"; exit; fi
if [ -z ${task+x} ]; then echo "Task is not provided, exiting"; exit; fi
if [ -z ${project+x} ]; then echo "Project is not provided, exiting"; exit; fi
# allow a default for temp dir
if [ -z ${temp_dir+x} ]; then echo "Temp Directory is not provided, setting to /home/dqr/t/"; temp_dir=/home/dqr/t/; fi
if [ -z ${sshport+x} ]; then echo "SSH Port is not provided, not specifying port when running remote commands"; sshport=""; else sshport="--port ${sshport}"; fi
if [ -z ${retries+x} ]; then echo "Retries is not provided, not specifying retries when running remote commands"; retries=""; else retries="--retries ${retries}"; fi

# identify what location we are uploading from
# only support LHO, LLO, CIT
case $(hostname -f) in
    *ligo-wa*)
        site=LHO
        ;;
    *ligo-la*)
        site=LLO
        ;;
    *ligo.cal*)
        site=CIT
        ;;
    *)
        site=unknown
        ;;
esac
echo "Site identified as ${site}"

tar_name="${temp_dir}${graceid}_${site}_${project}_${revision}_${task}.tar.gz"

# cd into basedir
pushd ${basedir}

# tar up all results
echo "Running command:"
echo "    tar -czf ${tar_name} ${task}"
tar -czf ${tar_name} ${task}

# upload this to CIT
echo "Running command:"
echo "    dqr-upload -vv --graceid ${graceid} --uploader ${site} --project ${project} --user ${USER} --revision ${revision} ${sshport} ${retries} ${tar_name}"
dqr-upload -vv --graceid ${graceid} --uploader ${site} --project ${project} --user ${USER} --revision ${revision} ${sshport} ${retries} ${tar_name}
ret=$?

# pop back to original dir
popd

exit $ret

