#!/bin/ksh

#/* Part of the Maestro sequencer software package.
# * Copyright (C) 2011-2015  Operations division of the Canadian Meteorological Centre
# *                          Environment Canada
# *
# * Maestro is free software; you can redistribute it and/or
# * modify it under the terms of the GNU Lesser General Public
# * License as published by the Free Software Foundation,
# * version 2.1 of the License.
# *
# * Maestro is distributed in the hope that it will be useful,
# * but WITHOUT ANY WARRANTY; without even the implied warranty of
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# * Lesser General Public License for more details.
# *
# * You should have received a copy of the GNU Lesser General Public
# * License along with this library; if not, write to the
# * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# * Boston, MA 02111-1307, USA.
# */


arguments=$*

eval `cclargs $0 \
  -n        ""                    ""                           "[Node               ]" \
  -ext      ""                    ""                           "[Extension          ]" \
  -d        ""                    ""                           "[Datestamp          ]" \
  -h        ""                    ""                           "[Display help       ]" \
  -v        "0"                   "1"                          "[Verbose]" \
  ++ $arguments`

[[ $v == 1 ]] && set -x 

if [[ -n "${SEQ_BIN}" ]] ; then
    nodeinfo=${SEQ_BIN}/nodeinfo
    tictac=${SEQ_BIN}/tictac
else
    nodeinfo=$(which nodeinfo)
    tictac=$(which tictac)
fi

if [ ! -d "${SEQ_EXP_HOME}" ]; then
   echo "node_savework error: Invalid path SEQ_EXP_HOME=$SEQ_EXP_HOME"
   exit 1
fi

if [[ $n == "" ]] ; then
   echo "node_savework error: Node must be defined"
   exit 1
fi
    
mach=$(nodeinfo -n $n | grep node.machine | cut -d "=" -f 2)

if [[ -z "${d}" ]] ; then
   datestamp=$(tictac -f %Y%M%D%H%Min%S)
else
   datestamp=${d}
fi

# time stamp 16:30:18_28Jan2015
timestamp=$(date +"%Y%m%d%H%M%S")

workpath=/${n}${ext}
sourceFile=${SEQ_EXP_HOME}/hub/${mach}/work/${datestamp}${workpath}
destFile=${sourceFile}_${timestamp}

if [[ ! -e ${sourceFile} ]] ; then
  ssh ${mach} "mv ${sourceFile} ${destFile}" 1>&2 
  return_status=$?
else 
  mv ${sourceFile} ${destFile} 1>&2
  return_status=$?
fi

if [[ $return_status == 0 ]]; then 
   echo "${mach}:${destFile} created."
else
   echo "Error in creation of ${mach}:${destFile}" 
   exit 1
fi 
