#!/usr/bin/bash
#############################################################################
#  Copyright (C) 2013-2015 Lawrence Livermore National Security, LLC.
#  Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
#  Written by Albert Chu <chu11@llnl.gov>
#  LLNL-CODE-644248
#
#  This file is part of Magpie, scripts for running Hadoop on
#  traditional HPC systems.  For details, see https://github.com/llnl/magpie.
#
#  Magpie is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  Magpie 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
#  General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with Magpie.  If not, see <http://www.gnu.org/licenses/>.
#############################################################################

# This script is for sleeping.  For the most part, it shouldn't be
# editted.  See job submission files for configuration details.

# Why did I bother to write this script?  It's mostly for
# refactoring/architecture purposes.  If I put "sleeping" into a
# script, then things like 'interactive' mode or 'setuponly' are just
# "another script" and be managed just like any other script.

source ${MAGPIE_SCRIPTS_HOME}/magpie/lib/magpie-lib-log
source ${MAGPIE_SCRIPTS_HOME}/magpie/lib/magpie-lib-run

# Will set magpie_jobtimeseconds
Magpie_job_time_seconds

secondsleft=$magpie_jobtimeseconds

if [ "$1X" == "X" ]
then
    Magpie_output_internal_error "magpie-job-sleep, first argument unset"
    exit 1
fi

if [ "$1" != "normal" ] && [ "$1" != "countdown" ]
then
    Magpie_output_internal_error "magpie-job-sleep, first argument invalid = $1"
    exit 1
fi

sleeptype=$1

if [ "${sleeptype}" == "normal" ]
then
    sleep ${secondsleft}
else
# 3600 = 60 mins
    if [ "${secondsleft}" -gt 3600 ]
    then
        sleepseconds=`expr ${secondsleft} - 3600`
        sleep ${sleepseconds}

        echo "*** Warning - 60 minutes left"
        secondsleft=3600
    fi

# 1800 = 30 mins
    if [ "${secondsleft}" -gt 1800 ]
    then
        sleepseconds=`expr ${secondsleft} - 1800`
        sleep ${sleepseconds}

        echo "*** Warning - 30 minutes left"
        secondsleft=1800
    fi

# 300 = 5 mins
    if [ "${secondsleft}" -gt 300 ]
    then
        sleepseconds=`expr ${secondsleft} - 300`
        sleep ${sleepseconds}

        echo "*** Warning - 5 minutes left"
        secondsleft=300
    fi

# 60 = 1 min
    if [ "${secondsleft}" -gt 60 ]
    then
        sleepseconds=`expr ${secondsleft} - 60`
        sleep ${sleepseconds}

        echo "*** Warning - 1 minute left"
        secondsleft=60
    fi

    sleep ${secondsleft}
fi

exit 0
