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

site=daint

case ${site} in
   daint)

      function safe_copy {
      
         # usage: safe_copy $file $desthost destdir [keep]
      
         file=$(readlink -f ${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
      
         if [ $(du ${file} | awk '{print $1}') -ne 0 ]; then  # just to make sure, that no empty files are tried to be copied.
      
            tmp=$(ssh ela mktemp -d -p /project/s964/transfer tmp_XXX)
      
            if [ "${keep}" == "keep" ]; then
               ssh ela rsync daint:${file} ${tmp} && ssh ela rsync --remove-source-files -a ${tmp}/$(basename ${file}) ${desthost}:${destdir}/. && echo "${file} copied to ${desthost}:${destdir}/$(basename ${file}) and kept on daint."
            else
               ssh ela rsync --remove-source-files -a daint:${file} ${tmp} && 
               ssh ela rsync --remove-source-files -a ${tmp}/$(basename ${file}) ${desthost}:${destdir}/. &&
               echo "${file} copied to ${desthost}:${destdir}/$(basename ${file}) and deleted from 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
               export success=false 
            fi
      
            ssh ela rmdir ${tmp}
      
         fi # file is not empty
      
      }
      ;;

   ubelix)  

      function safe_copy {
 
         # usage: safe_copy $file $desthost destdir [keep]
 
         file=$(readlink -f ${1})
         desthost=${2}
         destdir=${3}
         keep=${4}
 
         if ssh ${desthost} [ ! -d ${destdir} ]; then
            ssh ${desthost} mkdir --mode=755 -p ${destdir}
         fi  # destdir does not exist on desthost
 
#         if [ $(du ${file} | awk '{print $1}') -ne 0 ]; then  # just to make sure, that no empty files are tried to be copied.
 
            if [ "${keep}" == "keep" ]; then
               ssh submit03 rsync -a ${file} ${desthost}:${destdir}/. && echo "${file} copied to ${desthost}:${destdir}/$(basename ${file}) and kept on daint."
            else   
               ssh submit03 rsync --remove-source-files -a ${file} ${desthost}:${destdir}/. && echo "${file} copied to ${desthost}:${destdir}/$(basename ${file}) and deleted from ubelix."
            fi
    
            if [ $? -ne 0 ] ; then
               echo "${file} to ${desthost}:${destdir} at $(date +%Y-%m-%d\ %H:%M)" >> ${HOME}/failed_transfers.log
               export success=false
            fi
 
#         fi # file is not empty
 
      }
      ;;

esac

