#!/bin/bash
#
# push-service process manager for NodeJS
#
# chkconfig: 345 80 20
#
# description: start and stop push process
# processname: push-service
#
### BEGIN INIT INFO
# Provides:          push-services
# Required-Start: $local_fs $remote_fs
# Required-Stop: $local_fs $remote_fs
# Should-Start: $network
# Should-Stop: $network
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description: push init script
### END INIT INFO

PROG=$(basename $0)

if [[ -f /etc/sysconfig/push-server-multi ]]; then
  . /etc/sysconfig/push-server-multi
else
  SECURITY_KEY=XXXX
  HG_DIR=/opt/data/push-server
  CFG_DIR=/etc/push-server
  VAR_DIR=/var/log/push-server
  BASE_SUB=801            # base for port number where sub services lives
  BASE_PUB=901            # base for port number where pub services lives
  TMPL_SUB=push-server-sub-__PORT__.json
  TMPL_PUB=push-server-pub-__PORT__.json
  USER=rtcuser
  ID_SUB=5              # max ID for sub service
  ID_PUB=1              # max ID for pub service
  IP_LIST='"127.0.0.1", "10.13.168.110", "10.89.7.62", "92.50.195.50", "10.181.18.244"'
  PID_SUB=push-server-sub-__PORT__.pid
  PID_PUB=push-server-pub-__PORT__.pid
  WS_HOST=ws.bitrix24.com
  WS_PORT=8895
fi

# Source function library.
. /etc/rc.d/init.d/functions

# process template
process_template(){
  template_name=$1
  service_id=$2
  service_base=$3

  template_file=$CFG_DIR/$template_name
  for service_id in `seq 0 ${service_id}`; do
    echo -n "Update config service=$service_id -> "
    service_port=${service_base}${service_id}
    dest_file=$(echo "$template_file" | sed -e "s/__PORT__/$service_port/")
    sed -e "s/__PORT__/$service_port/g;s/__IP_LIST__/$IP_LIST/;s/__SECURITY_KEY__/$SECURITY_KEY/;s/__WS_HOST__/$WS_HOST/;s/__WS_PORT__/$WS_PORT/;" $template_file > $dest_file
    chown -R ${USER}:root $dest_file
    echo "$dest_file"
  done
}

# generate configs for services
generate_config(){
  SERVICE=${1:-all}

  [[ ( "$SERVICE" == "all" ) || ( "$SERVICE" == "sub" ) ]] && \
    process_template "$TMPL_SUB" "$ID_SUB" "$BASE_SUB"

  [[ ( "$SERVICE" == "all" ) || ( "$SERVICE" == "pub" ) ]] && \
   process_template "$TMPL_PUB" "$ID_PUB" "$BASE_PUB"

}


status_service(){
  template_name=$1
  service_id=$2
  service_base=$3
  pid_name=$4

  pid_file=$VAR_DIR/$pid_name
  service_type=$(echo $template_name | awk -F'-' '{print $3}')
  for service_id in `seq 0 ${service_id}`; do
    service_port=${service_base}${service_id}
    pidf=$(echo "$pid_file" | sed -e "s/__PORT__/$service_port/")
    echo -n "Status $service_type-$service_port -> "
    status -p $pidf
  done
}

status_services(){
  SERVICE=${1:-all}

  [[ ( "$SERVICE" == "all" ) || ( "$SERVICE" == "sub" ) ]] && \
    status_service "$TMPL_SUB" "$ID_SUB" "$BASE_SUB" "$PID_SUB"

  [[ ( "$SERVICE" == "all" ) || ( "$SERVICE" == "pub" ) ]] && \
    status_service "$TMPL_PUB" "$ID_PUB" "$BASE_PUB" "$PID_PUB"
}



start_service(){
  template_name=$1
  service_id=$2
  service_base=$3
  pid_name=$4

  template_file=$CFG_DIR/$template_name
  pid_file=$VAR_DIR/$pid_name
  service_type=$(echo $template_name | awk -F'-' '{print $3}')
  for service_id in `seq 0 ${service_id}`; do
    service_port=${service_base}${service_id}
    cfgf=$(echo "$template_file" | sed -e "s/__PORT__/$service_port/")
    pidf=$(echo "$pid_file" | sed -e "s/__PORT__/$service_port/")
    echo -n "Start $service_type-$service_port -> "
    status -p $pidf 1>/dev/null 2>&1
    status_rtn=$?
    if [[ $status_rtn -eq 0 ]]; then
      echo "is running pid=$(cat $pidf)"
    else
      pushd $HG_DIR 1>/dev/null 2>&1
      sudo -u $USER -H /bin/bash \
        -c "node server.js --config $cfgf 1>$VAR_DIR/$service_type-$service_port.log 2>&1 &" 
      rtn=$?

      if [[ -z $rtn ]]; then
        echo "error on start"
      else
        pid=$(ps -ef | grep "node server.js --config $cfgf" | \
          grep -v grep | awk '{print $2}')

        if [[ $pid -gt 0  ]] 2>/dev/null; then
          echo OK pid=$pid
          echo $pid > $pidf
        else
          echo Error
        fi
      fi
      popd 1>/dev/null 2>&1
    fi
  done
}

# start services
start_services(){
  SERVICE=${1:-all}

  [[ ( "$SERVICE" == "all" ) || ( "$SERVICE" == "sub" ) ]] && \
    start_service "$TMPL_SUB" "$ID_SUB" "$BASE_SUB" "$PID_SUB"

  [[ ( "$SERVICE" == "all" ) || ( "$SERVICE" == "pub" ) ]] && \
    start_service "$TMPL_PUB" "$ID_PUB" "$BASE_PUB" "$PID_PUB"

}

stop_service(){
  template_name=$1
  service_id=$2
  service_base=$3
  pid_name=$4

  template_file=$CFG_DIR/$template_name
  pid_file=$VAR_DIR/$pid_name
  service_type=$(echo $template_name | awk -F'-' '{print $3}')
  for service_id in `seq 0 ${service_id}`; do
    service_port=${service_base}${service_id}
    pidf=$(echo "$pid_file" | sed -e "s/__PORT__/$service_port/")
    echo -n "Stop $service_type-$service_port -> "
    killproc -p ${pidf} 1>/dev/null 2>&1
    kill_rtn=$?
    if [[ $kill_rtn -gt 0 ]]; then
      echo "error"
    else
      echo "ok"
    fi
  done
}

# start services
stop_services(){
  SERVICE=${1:-all}

  [[ ( "$SERVICE" == "all" ) || ( "$SERVICE" == "sub" ) ]] && \
    stop_service "$TMPL_SUB" "$ID_SUB" "$BASE_SUB" "$PID_SUB"

  [[ ( "$SERVICE" == "all" ) || ( "$SERVICE" == "pub" ) ]] && \
    stop_service "$TMPL_PUB" "$ID_PUB" "$BASE_PUB" "$PID_PUB"
}

case ${1} in
  "update_configs") generate_config ${2} ;;
  "start") start_services ${2} ;;
  "status") status_services ${2} ;;
  "stop") stop_services ${2} ;;
  "restart") 
  stop_services ${2}
  start_services ${2}
  ;;
  "reset")
  generate_config ${2}
  stop_services ${2}
  start_services ${2}
  ;;
  *) 
  echo "Usage: {start|stop|update_configs|status|restart|reset} {sub|pub}"
  exit 1
  ;;
esac

