#!/bin/bash 
### BEGIN INIT INFO
# Provides:          cloud-passwd-srvr
# Required-Start:    mountkernfs $local_fs cloud-early-config iptables-persistent
# Required-Stop:     $local_fs
# Should-Start:      
# Should-Stop:       
# Default-Start:     
# Default-Stop:      0 6
# Short-Description: Web server that sends passwords to User VMs
### END INIT INFO
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

ENABLED=0
[ -e /etc/default/cloud-passwd-srvr ] && . /etc/default/cloud-passwd-srvr

add_iptables_rules()
{
  #Delete any old iptables rule for port 8080 on eth0
  remove_iptables_rules

  #For all cidrs on eth0 for port 8080 accept only if source is withing that cidr
  for cidr in $(ip addr | grep eth0 | grep inet | awk '{print $2}');
  do
    count=1
    #Try for 10 times, if it still fails then bail
    while [ $count -le 10 ];
    do
      (( count++ ))
      iptables -A INPUT -i eth0 -p tcp -m state --state NEW -m tcp -s $cidr --dport 8080 -j ACCEPT
      if [ `iptables -L INPUT -n -v | grep eth0 | grep 8080 | grep ACCEPT | wc -l` -gt 0 ]
      then
        break
      else
        sleep 2
      fi
    done
  done
  echo "Added cloud-passwd-srvr iptables rules" && return 0
}

remove_iptables_rules()
{
  #Change the Internal Field Separator so the for loop, loops on lines and not spaces
  OIFS="${IFS}"
  NIFS=$'\n'
  IFS="${NIFS}"

  #Removed all iptable rules for port 8080 on eth0, they were added in start()
  for srcdest in `iptables -L -n -v | grep eth0 | grep 8080 | grep ACCEPT | awk '{print "--source "$8" --destination "$9}'`;
  do
    eval "iptables -D INPUT -i eth0 -p tcp -m state --state NEW -m tcp $srcdest --dport 8080 -j ACCEPT";
  done

  #Restore IFS
  IFS="${OIFS}"

  echo "Removed cloud-passwd-srvr iptables rules" && return 0
}

start() {
  [ "$ENABLED" != 0 ]  || exit 0 
  pid=$(getpid)
  [ "$pid" != "" ] && echo "Password server is already running (pid=$pid)" && return 0
  add_iptables_rules
  nohup bash /opt/cloud/bin/passwd_server &
}

getpid() {
  pid=$(ps -ef | grep passwd_server_ip | grep -v grep | awk '{print $2}')
  echo $pid
}

stop_password_server() {
  spid=$(pidof -s python passwd_server_ip.py)
  [ "$spid" != "" ] && kill -9 $spid && echo "Killed password server (pid=$spid)"
  return 0
}

stop () {
  stop_password_server
  pid=$(getpid)
  [ "$pid" != "" ] && kill -9 $pid && remove_iptables_rules && echo "Stopped password server (pid=$pid)" && stop_password_server && return 0

  echo "Password server is not running" && return 0
}

status () {
  pid=$(getpid)
  [ "$pid" != "" ] && echo "Password server is running (pid=$pid)" && return 0
  echo "Password server is not running" && return 0
}

case "$1" in
   start) start
	  ;;
    stop) stop
 	  ;;
    status) status
 	  ;;
 restart) stop
          start
 	  ;;
       *) echo "Usage: $0 {start|stop|status|restart}"
	  exit 1
	  ;;
esac

exit 0
