#!/bin/bash
#
# 2014/09/09 Gabriel Moreau

export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin
export LANG=C


function usage() {
   cat <<END_USAGE
NAME
   $(basename $0) - deploy soft

SYNOPSIS
   $0 -a arch -n soft_name -r release_number [-v] [-h]

OPTIONS
   -a  arch : 32_bit / 64_bit
   -n  name of the soft, example: matlab
   -r  release number of the soft, example: 2.3.1
   -o  os distribution name
   -d  delete (mirror) mode
   -v  verbose
   -h  help

AUTHOR
   Gabriel Moreau

COPYRIGHT
   Copyright (C) 2014-2017, LEGI UMR 5519 / CNRS UGA G-INP, Grenoble, France
   Licence : GNU GPL version 2 or later
END_USAGE
   }

MyVarRSCmd="/usr/bin/ionice -c 3 /usr/bin/nice -18 /usr/bin/rsync"
MyVarRSOpt="--contimeout=3 --timeout=3 --bwlimit=5000 --rsync-path='/usr/bin/ionice -c 3 /usr/bin/nice -18 /usr/bin/rsync'"

# get options
if [ $# -eq 0 ]; then usage; exit 1; fi 
while getopts "a:n:r:o:dvh" options
do
   case ${options} in
      a)
         if echo ${OPTARG} | egrep -q '^[[:digit:]]+'
         then
            export MyVarOSArch=${OPTARG}
         else
            usage
            exit 2
         fi
         ;;

      n)
         if echo ${OPTARG} | egrep -q '[[:alpha:]]'
         then
            export soft_name=${OPTARG}
         else
            usage
            exit 2
         fi
         ;;

      r)
         if echo ${OPTARG} | egrep -q '[[:digit:]]'
         then
            export soft_version=${OPTARG}
         else
            usage
            exit 2
         fi
         ;;

      o)
         if echo ${OPTARG} | egrep -q '[[:alpha:]]'
         then
            export os_name=${OPTARG}
         else
            usage
            exit 2
         fi
         ;;

      d)
         export MyVarRSOpt="${MyVarRSOpt} --delete"
         ;;

      v)
         export verbose='yes'
         ;;

      h|*)
         usage
         exit 3
         ;;
   esac
done


MyVarRSShare="legilnx40::opt/${MyVarOSArch}"
soft_version_server=${soft_version}
if [ -n "${os_name}" ]
then
   soft_version_server="${soft_version}..dist.${os_name}"
fi

[ -d "/opt/${soft_name}" ] || mkdir -p "/opt/${soft_name}"
if eval ${MyVarRSCmd} -avn ${MyVarRSOpt} ${MyVarRSShare}/${soft_name}/.zz-end.${soft_version_server} /opt/${soft_name}/.zz-end.${soft_version} \
      | /bin/grep -q ^\.zz-end
then
   rm -f /opt/${soft_name}/.zz-end.${soft_version}
   [ "${verbose}" == "yes" ] && \
      echo ${MyVarRSCmd} -avz ${MyVarRSOpt} ${MyVarRSShare}/${soft_name}/${soft_version_server}/ /opt/${soft_name}/${soft_version}/
   if eval ${MyVarRSCmd} -avz ${MyVarRSOpt} ${MyVarRSShare}/${soft_name}/${soft_version_server}/ /opt/${soft_name}/${soft_version}/
   then
      chmod ugo+rX /opt/${soft_name}/
      eval ${MyVarRSCmd} -aq ${MyVarRSOpt} ${MyVarRSShare}/${soft_name}/.zz-end.${soft_version_server} /opt/${soft_name}/.zz-end.${soft_version}
   fi
fi
