#!/bin/bash
# provides funictionality to safely copy data to bern
# rhand@giub.unibe.ch

function safe_copy {

   # usage: safe_copy $file $desthost destdir

   file=${1}
   desthost=${2}
   destdir=${3}
   keep=${4}

   if ssh ela ssh ${desthost} [ ! -d ${destdir} ]; then
      ssh ela ssh ${desthost} mkdir --mode=755 -p ${destdir}
   fi  # destdir does not exist on desthost

#    ssh ela "scp daint:${file} ${desthost}:${destdir}/."
#    check_src=$(md5sum ${file} | awk '{print$1}')
#    check_dest=$(ssh ela ssh ${desthost} md5sum ${destdir}/$(basename ${file}) | awk '{print $1}' )
#    if [ "${check_src}" == "${check_dest}" ]; then
#       if [ ! "${keep}" == "keep" ]; then 
#          rm ${file} && echo "${file} copied to ${desthost}:${destdir}/$(basename ${file}) and deleted from daint."
#       else
#          echo "${file} copied to ${desthost}:${destdir}/$(basename ${file}) and kept on daint."
#       fi
#    else
#       echo "!!! ERROR: copying file ${file} failed !!!" 
#       exit 1
#    fi 

   if [ "${keep}" == "keep" ]; then
      ssh ela rsync daint:${file} /project/s964/transfer && ssh ela rsync --remove-source-files -a /project/s964/transfer/$(basename ${file}) ${desthost}:${destdir}/. && echo "${file} copied to ${desthost}:${destdir}/$(basename ${file}) and deleted from daint."
   else
      ssh ela rsync --remove-source-files -a daint:${file} /project/s964/transfer && ssh ela rsync --remove-source-files -a /project/s964/transfer/$(basename ${file}) ${desthost}:${destdir}/. && echo "${file} copied to ${desthost}:${destdir}/$(basename ${file}) and kept on daint."
   fi

   if [ $? -ne 0 ] ; then 
      ssh ela echo "${file} to ${desthost}:${destdir} at $(date +%Y-%m-%d\ %H:%M)" >> /project/s964/transfer/failed_transfers.log
   fi

}
