#!/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
SERVER=$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}" = "" -o "${SERVER}" = "" ];then
  echo "usage is following"
  echo "pattern A: distribute <PROJECT>/<JOBNET> <SERVER>"
  echo "pattern B: cd <JOBNET_DIR>;distribute . <SERVER>"
  exit 1
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

if [ ! -f "${ROOT}/project/${PROJECT}/${JOBNET}/controller.sh" ];then
  echo "ERROR please execute mkcontroller.sh beforehand"
  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

## server dir create
if [ ! -d "${ROOT}/servers/${SERVER}" ];then
  FLAG=NEW
  echo "please input server ssh port number(default is port:22)"
  read SSH_PORT

  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

    ssh -p ${SSH_PORT} ${SERVER} ls ${USER_ROOT} 2> /dev/null

    if [ $? != 0 ];then

      ssh -p ${SSH_PORT} ${SERVER} mkdir -p ${USER_ROOT}
      ssh -p ${SSH_PORT} ${SERVER} chown ejobmgr ${USER_ROOT}
      scp -P ${SSH_PORT} -pr ${ROOT}/distribute_template/* @${SERVER}:${USER_ROOT}/

      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"
        exit 1
      fi

    fi

    echo  "ROOT=${USER_ROOT}" > /tmp/ecron_user_root.tmp
    scp -P ${SSH_PORT} /tmp/ecron_user_root.tmp  @${SERVER}:${USER_ROOT}/.root


  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}/ !!"
        rm -rf ${ROOT}/servers/${SERVER}
        exit 1
      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}"
    exit 1
  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

## key check

. ${ROOT}/servers/${SERVER}/server.conf
${ROOT}/bin/keycheck ${SERVER} ${SSH_PORT} > /dev/null 2>&1
if [ $? != 0 ];then
  echo "${SERVER} key check failed!"
  echo "you must set ssh key authentication"
  echo "please set /home/ejobmgr/.ssh/authorized_keys"
  echo "see detail -> http://www.e-cron.org/guideline.html"
  exit 1
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 [ "${LOCAL_CHECK}" = "" ];then

  ssh -p ${SSH_PORT} ${SERVER} ls ${USER_ROOT}/project/${PROJECT}/${JOBNET} 2> /dev/null
  if [ $? != 0 ];then
    ssh -p ${SSH_PORT} ${SERVER} mkdir -p ${USER_ROOT}/project/${PROJECT}/${JOBNET}
  fi

    scp -pr -P ${SSH_PORT} ${ROOT}/servers/${SERVER}/project/${PROJECT}/${JOBNET}/* ${SERVER}:${USER_ROOT}/project/${PROJECT}/${JOBNET}/

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

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}/"
    exit 1
  fi
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
  fi

else

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

fi


## daemon check

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

if [ $? != 0 ];then
  echo "fail to start e-cron daemon !!"
  exit 1
fi
  
echo "-----------------------------------"
echo "${PROJECT} ${JOBNET} succesfully distributed to ${SERVER}"
echo "-----------------------------------"

exit 0

