#!/usr/local/bin/bash
#
# Copyright (C) 2006 SIPfoundry Inc.
# Licensed by SIPfoundry under the LGPL license.
#
# Copyright (C) 2006 Pingtel Corp.
# Licensed to SIPfoundry under a Contributor Agreement.

stunnel_exec=/usr/sbin/stunnel
stunnel_config_file=@SIPX_CONFDIR@/ssl/stunnel/stunnel-config
stunnel_initd_file=@SIPX_SYSCONFDIR@/init.d/stunnel
stunnel_accept_port=9300
stunnel_forward_port=5432
stunnel_debug_level=5

check_ca_file=1

Action=HELP

checkStunnelRunning() {
   # Get the process info, remove any leading whitespace and retrieve Pid
   ret=`ps -C stunnel | sed -e 's/^\s*//g' | grep stunnel`
   pid=${ret%% *}
   if [ "x$pid" = "x" ]; then
     return 1
   else
     return 0
   fi
}

configtest() {
   if [ ! -f @SIPX_CONFDIR@/ssl/ssl.key ]; then
      echo 
      echo "Error: Could not find @SIPX_CONFDIR@/ssl/ssl.key -"
      echo "       copy the SSL certificates from the master to this machine before"
      echo "       running --setup."
      echo
      return 1
   fi

   if [ ! -f @SIPX_CONFDIR@/ssl/ssl.crt ]; then
      echo 
      echo "Error: Could not find @SIPX_CONFDIR@/ssl/ssl.crt -"
      echo "       copy the SSL certificates from the master to this machine before"
      echo "       running --setup."
      echo
      return 1
   fi

   # Do CA file check only for --setup
   if [ ${Action} != CONFIGTEST ]; then
      if [ -d @SIPX_CONFDIR@/ssl/authorities ]; then
         if [ ! -f @SIPX_CONFDIR@/ssl/authorities/${ca_file} ]; then
            echo 
            echo "Error: Could not find @SIPX_CONFDIR@/ssl/authorities/${ca_file}"
            files=`ls @SIPX_CONFDIR@/ssl/authorities`
            echo "       Possible candidates in that directory are :"
            echo
            echo "${files}"
            echo
            return 1
         fi
      else
         echo 
         echo "Error: Directory @SIPX_CONFDIR@/ssl/authorities not found"
         echo
         return 1
      fi
   fi
   
   # Do stunnel setup only for --setup
   if [ ${Action} != CONFIGTEST ]; then   
      if checkStunnelRunning; then
         echo
         echo "Error: stunnel is already running with Pid ${pid}. It must"
         echo "       be shut down before another instance can be started."
         echo
         return 1
      fi
   else
      echo -n "Check for running stunnel... "
      if checkStunnelRunning; then
         echo "ok"
      else
         echo "failed"
         echo
         echo "   stunnel is not running on this machine."
         return 1
      fi
   fi
   
   return 0
}

generateStunnelConfig() {
   if [ ! -d @SIPX_CONFDIR@/ssl/stunnel ]; then
      mkdir -p @SIPX_CONFDIR@/ssl/stunnel
   fi
   echo "client = no" > ${stunnel_config_file}
   echo "cert = @SIPX_CONFDIR@/ssl/ssl.crt" >> ${stunnel_config_file}
   echo "key = @SIPX_CONFDIR@/ssl/ssl.key" >> ${stunnel_config_file}
   echo "CAfile = @SIPX_CONFDIR@/ssl/authorities/${ca_file}" >> ${stunnel_config_file}
   echo "verify = 2" >> ${stunnel_config_file}
   echo "debug = ${stunnel_debug_level}" >> ${stunnel_config_file}
   echo "output = @SIPX_LOGDIR@/sipstunnel.log" >> ${stunnel_config_file}
   echo "[postgresql]" >> ${stunnel_config_file} >> ${stunnel_config_file}
   echo "accept = ${stunnel_accept_port}" >> ${stunnel_config_file}
   echo "connect = ${stunnel_forward_port}" >> ${stunnel_config_file}
}

generateStunnelStartup() {
   echo "#!/usr/local/bin/bash" > ${stunnel_initd_file}
   echo "# chkconfig: 345 40 60" >> ${stunnel_initd_file}
   echo "# description: Dynamically generated startup script" >> ${stunnel_initd_file}
   echo "# processname: stunnel" >> ${stunnel_initd_file}
   echo "# This file was generated by the sipxha-distrib script" >> ${stunnel_initd_file}
   echo "case \"\${1}\" in" >> ${stunnel_initd_file}
   echo "  start)" >> ${stunnel_initd_file}
   echo "        echo -n \"Starting stunnel services: \"" >> ${stunnel_initd_file}
   echo "        /usr/sbin/stunnel ${stunnel_config_file}" >> ${stunnel_initd_file}
   echo "        echo" >> ${stunnel_initd_file}
   echo "        ;;" >> ${stunnel_initd_file}
   echo "  stop)" >> ${stunnel_initd_file}
   echo "        echo \"Not implemented\"" >> ${stunnel_initd_file}
   echo "        ;;" >> ${stunnel_initd_file}
   echo "  status)" >> ${stunnel_initd_file}
   echo "        echo \"Not implemented\"" >> ${stunnel_initd_file}
   echo "        ;;" >> ${stunnel_initd_file}
   echo "  restart)" >> ${stunnel_initd_file}
   echo "        echo \"Not implemented\"" >> ${stunnel_initd_file}
   echo "        ;;" >> ${stunnel_initd_file}
   echo "  *)" >> ${stunnel_initd_file}
   echo "        echo \"Usage: stunnel {start|stop|status|restart}\"" >> ${stunnel_initd_file}
   echo "        exit 1" >> ${stunnel_initd_file}
   echo "esac" >> ${stunnel_initd_file}
   echo "exit 0" >> ${stunnel_initd_file}
   
   # Generate initial stunnel.log and give it the correct permissions
   # so logrotate can work with it
   if [ -f @SIPX_LOGDIR@/sipstunnel.log ]; then
      rm -f @SIPX_LOGDIR@/sipstunnel.log
   fi
   echo "sipx init" > @SIPX_LOGDIR@/sipstunnel.log
   chmod 0644 @SIPX_LOGDIR@/sipstunnel.log
   chmod +x ${stunnel_initd_file}
   if [ -f /sbin/chkconfig ]; then
      /sbin/chkconfig --add stunnel
   elif [ -f /usr/sbin/chkconfig ]; then
      /usr/sbin/chkconfig --add stunnel
   else
      chkconfig --add stunnel
   fi
}

setup() {
   if configtest 
   then
      generateStunnelConfig
      generateStunnelStartup
      ${stunnel_exec} ${stunnel_config_file}
      echo 
      echo "HA setup done"
      echo
   fi
}

user=`whoami`

if [ "${user}" != "root" ]; then
   echo "Error: Must be root to run sipxha-distrib"
   exit 1
fi

while [ $# -ne 0 ]
do
   case ${1} in
      -c|--configtest)
         Action=CONFIGTEST
         ;;
            
      -s|--setup)
         Action=SETUP
         
         shift
         ca_file=${1}
         ;;

      -h|--help)
         Action=HELP
         ;;
         
      # Override debug level
      -d|--debug)
         shift
         if [[ ${1} = [0-7] ]]; then
            stunnel_debug_level=${1}
         else
            echo "Invalid debug level ${1} - must be 0-7"
            exit 1
         fi
         ;;
         
      # Override accept port
      -a|--accept)
         shift
         port=`expr match "${1}" '\(\d+\)'`
         if [ -n port ]; then
            stunnel_accept_port=${1}
         else
            echo "Invalid port number ${1}"
            exit 1
         fi
         ;;
      
      # Override connect port   
      -c|--connect)
         port=`expr match "${1}" '\(\d+\)'`
         if [ -n port ]; then
            stunnel_foward_port=${1}
         else
            echo "Invalid port number ${1}"
            exit 1
         fi
         ;;
        
      # Override  stunnel executable name
      -e|--exec)
         shift
         if [ -f ${1} ]; then
            if [ -e ${1} ]; then
               stunnel_exec=${1}
            else
               echo "File ${1} found but is not executable"
               exit 1
            fi
         else
            echo "stunnel executable ${1} not found"
            exit 1
         fi
         ;;
      
           
        *)
         ;;
    esac           

    shift # always consume 1
done

if [ ${Action} = CONFIGTEST ]
then
    check_ca_file=0
    if configtest; then
       @SIPX_BINDIR@/sipxcallresolver.sh --distrib-configtest
    fi
    exit $Status
elif [ ${Action} = SETUP ]
then
    setup
elif [ ${Action} = HELP ]
then

cat <<USAGE
Usage: sipxha-distrib [-c|--configtest]
                      [-s|--setup]
                      [-h|--help]
                     
Set up distributed machine for HA.

Options include:

  --configtest         Run diagnostics. Will need root permissions.

  --setup              Initialize the distributed machine for communicating with the
                       call resolver on the master machine. Will need root permissions.

USAGE

fi


syntax highlighted by Code2HTML, v. 0.9.1