#!/bin/sh

HTTPD="httpd"

if [ -e /usr/lib/systemd/system/apache2.service -o -e /etc/init.d/apache2 ]; then
    HTTPD="apache2"
fi

SERVICES="squid $HTTPD salt-broker tftp"

if [ -e /etc/init.d/functions ]; then
    . /etc/init.d/functions
fi

RETVAL=0

forward_services() {
    ACTION="$1"

    for service in $SERVICES; do
	if [ -e /etc/init.d/$service -o -e /usr/lib/systemd/system/$service.service ]; then
	    /sbin/service $service $ACTION
	    let RETVAL=$RETVAL+$?
	fi
	if [ $RETVAL -gt 0 ]; then
	    RETVAL=1
	fi
    done
}

reverse_services() {
    ACTION="$1"

    for service in $(echo $SERVICES | tac -s" "); do
	if [ -e /etc/init.d/$service -o -e /usr/lib/systemd/system/$service.service ]; then
	    /sbin/service $service $ACTION
            let RETVAL=$RETVAL+$?
        fi
        if [ $RETVAL -gt 0 ]; then
            RETVAL=1
        fi
    done
}

start() {
        echo "Starting spacewalk-proxy..."
	forward_services start
	echo "Done."
        return 0
}

stop() {
        echo "Shutting down spacewalk-proxy..."
	reverse_services stop
	if [ -e /usr/lib/systemd/system/tftp.socket ]; then
    systemctl stop tftp.socket
    fi
	echo "Done."
        return 0
}

restart() {
    stop
    sleep 2
    # if service has not been started and stop fail, we do not care
    RETVAL=0
    start
}

case "$1" in
    start)
	start
        ;;
    stop)
	stop
        ;;
    status)
	forward_services status
        ;;
    restart)
        restart
        ;;
    condrestart)
        restart
        ;;
    *)
        echo "Usage: rhn-proxy {start|stop|status|restart}"
        exit 1
        ;;
esac
exit $RETVAL
