#!/bin/bash
#
# openshift-port-proxy
#
# chkconfig:   345 85 15
# description: OpenShift proxy
# processname: haproxy
# config:      /etc/openshift/port-proxy.cfg
# pidfile:     /var/run/openshift-port-proxy.pid
#
### BEGIN INIT INFO
# Provides: openshift-port-proxy
# Required-Start: $local_fs $remote_fs $network $named
# Required-Stop: $local_fs $remote_fs $network
# Short-Description: start and stop OpenShift Node Port Proxy
# Description: Script to configure HAProxy to do port forwarding for OpenShift
### END INIT INFO

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

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

[ -e /etc/sysconfig/openshift-port-proxy ] && source /etc/sysconfig/openshift-port-proxy

exec=/usr/sbin/haproxy
prog=haproxy
lockfile=/var/lock/subsys/openshift-port-proxy
pidfile=/var/run/openshift-port-proxy.pid
cfgfile=/etc/openshift/port-proxy.cfg

pre_start() {
    # Fix internal ip address in case it was changed by the cloud provider
    openshift-port-proxy-cfg fixaddr
}

start() {
    echo -n $"Starting openshift-port-proxy: "
    daemon --pidfile $pidfile $exec -D -f $cfgfile -p $pidfile
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping openshift-port-proxy: "
    if [ -e ${pidfile} ]; then
      killproc -p $pidfile $prog
    else
      # BZ876939
      echo -n "(already stopped)"
      success
    fi
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    stop
    start
}

reload() {
    echo -n $"Reloading openshift-port-proxy: "
    $exec -D -f $cfgfile -p $pidfile -sf $(cat $pidfile)
    retval=$?
    echo
    return $retval
}

case "$1" in
    start)
        pre_start
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    reload)
        reload
        ;;
    status)
        status -p $pidfile $prog
        ;;
    condrestart|try-restart)
  	if [ -f $lockfile ] 
        then
            restart
        fi
	;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|reload}"
        exit 2
esac
