#!/usr/bin/bash

# ve_check_job
# Copyright (C) 2021 NEC Corporation
# This file is part of VE system initialization
#
# VE system initialization 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.
#
# VE system initialization 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 VE system initialization; if not, see
# <http://www.gnu.org/licenses/>

#function usage()
#{
#    echo "ve_job_check <option> <node No> <Job_ID>"
#}

args=$#

VE_OS_ONLINE=0
RET_SUCCESS=0
RET_INVALID_PARAMS=1
RET_FAIL_CREATE_FILE=2
RET_VEOS_NOT_ONLINE=3
RET_NO_CHECK_FILE=4

if [ ${args} -ne 3 ]; then
#    usage
    exit ${RET_INVALID_PARAMS}
fi

opt=$1
node_no=$2
session_id=$3

JOB_FILE_DIR="/var/run/opt/nec/ve/veos"
JOB_FILE_NAME="${JOB_FILE_DIR}/job${session_id}_node${node_no}"

#echo "opt = $opt, node no = $node_no, session id = $session_id" > /dev/null


# check os_state ONLINE
function get_os_state()
{
    # VE/OS status check
    if [ ! -e /dev/veslot${node_no} ]; then
        exit ${RET_VEOS_NOT_ONLINE}
    fi
    OS_STATE_FILE=`echo /sys$(udevadm info -q path /dev/veslot${node_no})/os_state`
    if [ ! -f ${OS_STATE_FILE} ]; then
        exit ${RET_VEOS_NOT_ONLINE}
    fi
    os_state=`cat ${OS_STATE_FILE}`
    if [ ${os_state} -ne ${VE_OS_ONLINE} ]; then
        exit ${RET_VEOS_NOT_ONLINE}
    fi
}

function check_start()
{
    get_os_state

    # create directory for job check file
    if [ ! -d ${JOB_FILE_DIR} ]; then
        /usr/bin/mkdir -p ${JOB_FILE_DIR} > /dev/null 2>&1
        if [ $? -ne 0 ]; then
            exit ${RET_FAIL_CREATE_FILE}
        fi
    fi

    # create job check file
    /usr/bin/touch ${JOB_FILE_NAME}  > /dev/null 2>&1
    if [ $? -eq 0 -a -f ${JOB_FILE_NAME} ]; then
        exit ${RET_SUCCESS}
    else
        exit ${RET_FAIL_CREATE_FILE}
    fi
}

function check_end()
{
    get_os_state

    # check if the job check file exists and removes it
    if [ -f ${JOB_FILE_NAME} ]; then
        /bin/rm -f ${JOB_FILE_NAME} > /dev/null 2>&1
        exit ${RET_SUCCESS}
    else
        exit ${RET_NO_CHECK_FILE}
    fi
}

# option check
if [ $opt == "-s" ]; then
    check_start
elif [ $opt == "-e" ]; then
    check_end
else
    exit ${RET_INVALID_PARAMS}
fi

