#!/bin/sh

# Copyright (c) 2012 ken.naruo
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


# global.cof load
LANG=C;export LANG
SCRIPT_DIR=`dirname $0`
. ${SCRIPT_DIR}/../../global.conf

PROJECT_JOBNET=$1
SSH_PORT=$2
USER_ROOT=/home/ejobmgr/e-cron

IFCONFIG=/usr/sbin/ifconfig
LINUX=`uname -a | grep Linux`
if [ "${LINUX}" ];then
  IFCONFIG=/sbin/ifconfig
fi

if [ "${PROJECT_JOBNET}" = \. ];then

  JOBNET=`pwd | awk -F [/] '{field = $NF } END {print field }'`
  PROJECT=`pwd | awk -F [/] '{field = $(NF-1) } END {print field}'`

else

  PROJECT=`echo "${PROJECT_JOBNET}" | awk -F"/" '{print $1}'`
  JOBNET=`echo "${PROJECT_JOBNET}" | awk -F"/" '{print $2}'`

fi

if [ ! -d "${ROOT}/project/${PROJECT}/${JOBNET}" ];then
  echo "ERROR no such jobnet"
  exit 1
fi


## user check
USER_CHECK=`id | grep ejobmgr | grep -v grep`
if [ "${USER_CHECK}" = "" ];then
  echo "ERROR you must execute this script as ejobmgr"
  exit 1
fi

# load jobnet.prof
TMP_FILE=/tmp/distribute${project}${jobnet}jobnetprof.tmp
grep -v SCHEDULE ${SCRIPT_DIR}/../../project/${PROJECT}/${JOBNET}/jobnet.prof > $TMP_FILE
chmod 766 ${TMP_FILE}
. ${TMP_FILE}

${SCRIPT_DIR}/mkcontroller $PROJECT/${JOBNET}

if [ $? != 0 ];then
 echo "ERROR make controller failed!"
 exit 1
fi


if [ "${SPARE_SERVER}" ];then
  EXECUTION_SERVERS="${EXECUTION_SERVERS} ${SPARE_SERVER}"
fi

## server dir create
for SERVER in ${EXECUTION_SERVERS}
do
  ERROR_FLAG=""

  if [ ! -d "${ROOT}/servers/${SERVER}" ];then
  
    if [ "${SSH_PORT}" = "" ];then
      SSH_PORT=22
    fi

    ## check server

    IP_ADDR=`dig ${SERVER} | grep -A 1 "ANSWER SECTION" | grep -v "ANSWER SECTION" | awk '{print $5}'`
    LOCAL_CHECK=`${IFCONFIG} -a | grep ${IP_ADDR}`

    if [ "${LOCAL_CHECK}" = "" ];then

      #key check
      if [ $? != 0 ];then
        echo "ERROR scp -P ${SSH_PORT} -pr ${ROOT}/distribute_template/* @${SERVER}:${USER_ROOT}/"
        echo "you must set ssh key authentication"
        echo "please use set /home/ejobmgr/.ssh/authorized_keys"
        echo "see detail -> http://www.e-cron.org/guideline.html"
        ERROR_FLAG=on
      else
        ssh -o "ConnectTimeout 5" -p ${SSH_PORT} ${SERVER} ls ${USER_ROOT} > /dev/null 2>&1

        if [ $? != 0 ];then
          ssh -o "ConnectTimeout 5" -p ${SSH_PORT} ${SERVER} mkdir -p ${USER_ROOT}
          ssh -o "ConnectTimeout 5" -p ${SSH_PORT} ${SERVER} chown ejobmgr ${USER_ROOT}
          scp -o "ConnectTimeout 5" -P ${SSH_PORT} -pr ${ROOT}/distribute_template/* @${SERVER}:${USER_ROOT}/  > /dev/null 2>&1

          if [ $? != 0 ];then
             echo "ERROR scp -P ${SSH_PORT} -pr ${ROOT}/distribute_template/* @${SERVER}:${USER_ROOT}/"
             ERROR_FLAG=on
          fi  
        fi

        echo  "ROOT=${USER_ROOT}" > /tmp/ecron_user_root.tmp
        scp -o "ConnectTimeout 5" -P ${SSH_PORT} /tmp/ecron_user_root.tmp  @${SERVER}:${USER_ROOT}/.root  > /dev/null 2>&1
      
      fi
  
    else

      if [ ! -d ${USER_ROOT} ];then
        mkdir  ${USER_ROOT}
        chown ejobmgr  ${USER_ROOT}
        cp -pr ${ROOT}/distribute_template/* ${USER_ROOT}/

        if [ $? != 0 ];then
          echo "ERROR cp -pr ${ROOT}/distribute_template/* ${USER_ROOT}/ !!"
          ERROR_FLAG=on
        fi
        echo "ROOT=${USER_ROOT}" > ${USER_ROOT}/.root
     fi
     
    fi
  
    ## create dir
    mkdir -p ${ROOT}/servers/${SERVER}

    if [ $? != 0 ];then
      echo "ERROR you can't create ${ROOT}/servers/${SERVER}"
      ERROR_FLAG=on
    fi

    cp -pr ${ROOT}/distribute_template/* ${ROOT}/servers/${SERVER}/
    echo "SSH_PORT=${SSH_PORT}" > ${ROOT}/servers/${SERVER}/server.conf
    echo "USER_ROOT=${USER_ROOT}" >>  ${ROOT}/servers/${SERVER}/server.conf
    chmod 755  ${ROOT}/servers/${SERVER}/server.conf
  
  fi


  ## distribute local to local

  if [ ! -d  ${ROOT}/servers/${SERVER}/project/${PROJECT}/${JOBNET} ];then
    mkdir -p ${ROOT}/servers/${SERVER}/project/${PROJECT}/${JOBNET}
  fi

  cp -prf ${ROOT}/project/${PROJECT}/${JOBNET}/* ${ROOT}/servers/${SERVER}/project/${PROJECT}/${JOBNET}/

  ## distribute to server

  IP_ADDR=`dig ${SERVER} | grep -A 1 "ANSWER SECTION" | grep -v "ANSWER SECTION" | awk '{print $5}'`
  LOCAL_CHECK=`${IFCONFIG} -a | grep ${IP_ADDR}`

  if [ "${SSH_PORT}" = "" ];then
    SSH_PORT=`grep ${SERVER}: ${ROOT}/map.conf | awk -F":" '{print $2}'`
  fi

  if [ "${LOCAL_CHECK}" = "" ];then

    ssh -o "ConnectTimeout 5" -p ${SSH_PORT} ${SERVER} ls ${USER_ROOT}/project/${PROJECT}/${JOBNET}  > /dev/null 2>&1
    if [ $? != 0 ];then
      ssh -o "ConnectTimeout 5" -p ${SSH_PORT} ${SERVER} mkdir -p ${USER_ROOT}/project/${PROJECT}/${JOBNET}
    fi
    
    scp -o "ConnectTimeout 5" -pr -P ${SSH_PORT} ${ROOT}/servers/${SERVER}/project/${PROJECT}/${JOBNET}/* ${SERVER}:${USER_ROOT}/project/${PROJECT}/${JOBNET}/  > /dev/null 2>&1

    if [ $? != 0 ];then
      echo "ERROR: scp -pr -P ${SSH_PORT} ${ROOT}/servers/${SERVER}/project/${PROJECT}/${JOBNET}/* ${SERVER}:${USER_ROOT}/project/${PROJECT}/${JOBNET}/ "
      ERROR_FLAG=on
    fi

    rsync --timeout=5 -e "ssh -p ${SSH_PORT}" -alv --delete ${ROOT}/servers/${SERVER}/project/${PROJECT}/${JOBNET}/bat ${SERVER}:${USER_ROOT}/project/${PROJECT}/${JOBNET}  > /dev/null 2>&1

  else

    if [ ! -d ${USER_ROOT}/project/${PROJECT}/${JOBNET} ];then
      mkdir -p ${USER_ROOT}/project/${PROJECT}/${JOBNET}
    fi

    cp -prf ${ROOT}/servers/${SERVER}/project/${PROJECT}/${JOBNET}/* ${USER_ROOT}/project/${PROJECT}/${JOBNET}/

    if [ $? != 0 ];then
      echo "ERROR:cp -prf ${ROOT}/servers/${SERVER}/project/${PROJECT}/${JOBNET}/* ${USER_ROOT}/project/${PROJECT}/${JOBNET}/"
      ERROR_FLAG=on
    fi

    rsync --timeout=5 -alv --delete ${ROOT}/servers/${SERVER}/project/${PROJECT}/${JOBNET}/bat ${USER_ROOT}/project/${PROJECT}/${JOBNET}  > /dev/null 2>&1 

  fi


  ## map.conf update

  if [ "${FLAG}" = NEW  -o ! -f ${ROOT}/map.conf ];then
    echo "${SERVER}:${SSH_PORT}" >> ${ROOT}/map.conf
  fi

  ## jonet_list update
  if [ -f ${ROOT}/servers/${SERVER}/jobnet_list ];then
    grep  "^${PROJECT} ${JOBNET}:" ${ROOT}/servers/${SERVER}/jobnet_list

    if [ $? != 0 ];then

      echo "${PROJECT} ${JOBNET}: disabled" >> ${ROOT}/servers/${SERVER}/jobnet_list

    else

      CHECK=`grep "^${PROJECT} ${JOBNET}: enabled" ${ROOT}/servers/${SERVER}/jobnet_list`

      if [ "${CHECK}" ];then
        ${ROOT}/bin/disable_jobnet $PROJECT/${JOBNET} ${SERVER}  > /dev/null 2>&1

        if [ $? != 0 ];then
          ERROR_FLAG=on
          echo "ERROR failed to reschedule cron setting to ${SERVER}"
        fi
          
        ${ROOT}/bin/enable_jobnet $PROJECT/${JOBNET} ${SERVER}  > /dev/null 2>&1

        if [ $? != 0 ];then
          ERROR_FLAG=on
          echo "ERROR failed to reschedule cron setting to ${SERVER}"
        fi

      fi
    fi

  else

    echo "${PROJECT} ${JOBNET}: disabled" >> ${ROOT}/servers/${SERVER}/jobnet_list

  fi

  if [ "${SERVER}" = "${SPARE_SERVER}" ];then
    if [ "${LOCAL_CHECK}" = "" ];then
      ssh -o "ConnectTimeout 5" -p ${SSH_PORT} ${SERVER} touch ${USER_ROOT}/project/${PROJECT}/${JOBNET}/spare
    else
      touch ${USER_ROOT}/project/${PROJECT}/${JOBNET}/spare
    fi

    touch ${ROOT}/servers/${SERVER}/project/${PROJECT}/${JOBNET}/spare
    ${ROOT}/bin/enable_jobnet ${PROJECT}/${JOBNET} ${SERVER}  > /dev/null 2>&1
    echo "${JOBNET} was enabled on ${SERVER}, but will not be executed until EXECUTION_SERVERS down"
  fi
 
  if [ "${ERROR_FLAG}" != on ];then
    echo "-----------------------------------"
    echo "${PROJECT} ${JOBNET} successfully distributed to ${SERVER}"
    echo "-----------------------------------"
  else
    echo "-----------------------------------"
    echo "${PROJECT} ${JOBNET} failed to distribut to ${SERVER}"
    echo "-----------------------------------"
  fi

done

## daemon check

${ROOT}/bin/check_ecron_daemon > /dev/null 2>&1

if [ $? != 0 ];then
  echo "fail to start e-cron daemon !!"
  exit 1
fi


