#!/bin/sh
{#-
# Copyright 2015 Rackspace.
#
#    Licensed 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.
#
#   Inspired by https://gist.github.com/gfrey/8472007
#}
### BEGIN INIT INFO
# Provides:          octavia-amp-{{ haproxy_pid }}
# Required-Start:    $local_fs $network
# Required-Stop:     $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: fast and reliable load balancing reverse proxy
# Description:       This file should be used to start and stop haproxy.
### END INIT INFO


PATH=/sbin:/usr/sbin:/bin:/usr/bin
PIDFILE={{ haproxy_pid }}
CONFIG={{ haproxy_cfg }}
PEER_NAME={{ peer_name }}
HAPROXY={{ haproxy_cmd }}
USER_GROUP_CONF_PATH={{ haproxy_user_group_cfg }}

EXTRAOPTS=
ENABLED=1

test -x $HAPROXY || exit 0
test -f "$CONFIG" -f "$USER_GROUP_CONF_PATH" || exit 0

if [ -e /etc/default/haproxy ]; then
    . /etc/default/haproxy
fi

test "$ENABLED" != "0" || exit 0

[ -f /etc/default/rcS ] && . /etc/default/rcS
. /lib/lsb/init-functions

HAPROXY="ip netns exec {{ amphora_nsname }} $HAPROXY"

haproxy_start()
{
    # Re-add the namespace
    ip netns add {{ amphora_nsname }} || true
    # Load the system sysctl into the new namespace
    ip netns exec {{ amphora_nsname }} sysctl --system || true
    # We need the plugged_interfaces file sorted to join the host interfaces
    sort -k 1 /var/lib/octavia/plugged_interfaces > /var/lib/octavia/plugged_interfaces.sorted || true
    # Assign the interfaces into the namespace with the appropriate name
    ip link | awk '{getline n; print $0,n}' | awk '{sub(":","",$2)} { for(i=1;i<=NF;i++) if ($i == "link/ether") {print $(i+1) " " $2} }' | sort -k 1 | join -j 1 - /var/lib/octavia/plugged_interfaces.sorted | awk '{system("ip link set "$2" netns {{ amphora_nsname }} name "$3"")}' || true
    # Bring up all of the namespace interfaces
    {%- if HasIFUPAll %}
    ip netns exec {{ amphora_nsname }} ifup -a || true
    {%- else %}
    awk '{system("/sbin/ip netns exec {{ amphora_nsname }} ifup " $2)}' /var/lib/octavia/plugged_interfaces || true
    {%- endif %}

    start-stop-daemon --start --pidfile "$PIDFILE" \
        --exec $HAPROXY -- -f "$CONFIG" -f "$USER_GROUP_CONF_PATH" -L "$PEER_NAME" -D -p "$PIDFILE" \
        $EXTRAOPTS || return 2
    return 0
}

haproxy_stop()
{
    if [ ! -f $PIDFILE ] ; then
        # This is a success according to LSB
        return 0
    fi
    for pid in $(cat $PIDFILE) ; do
        /bin/kill $pid || return 4
    done
    rm -f $PIDFILE
    return 0
}

haproxy_reload()
{
    $HAPROXY -f "$CONFIG" -f "$USER_GROUP_CONF_PATH" -L "$PEER_NAME" -p $PIDFILE -D $EXTRAOPTS -sf $(cat $PIDFILE) \
        || return 2
    return 0
}

haproxy_checkconf()
{
    rcode=0

    $HAPROXY -c -f "$CONFIG" -f "$USER_GROUP_CONF_PATH" -L "$PEER_NAME"
    if [ $? -ne 0 ]; then
        rcode=1
    fi

    return $rcode
}

haproxy_status()
{
    if [ ! -f $PIDFILE ] ; then
        # program not running
        return 3
    fi

    for pid in $(cat $PIDFILE) ; do
        if ! ps --no-headers p "$pid" | grep haproxy > /dev/null ; then
            # program running, bogus pidfile
            return 1
        fi
    done

    return 0
}

case "$1" in
checkconf)
    haproxy_checkconf
    exit $?
    ;;
start)
    log_daemon_msg "Starting haproxy" "haproxy"
    haproxy_start
    ret=$?
    case "$ret" in
    0)
        log_end_msg 0
        ;;
    1)
        log_end_msg 1
        echo "pid file '$PIDFILE' found, haproxy not started."
        ;;
    2)
        log_end_msg 1
        ;;
    esac
    exit $ret
    ;;
stop)
    log_daemon_msg "Stopping haproxy" "haproxy"
    haproxy_stop
    ret=$?
    case "$ret" in
    0|1)
        log_end_msg 0
        ;;
    2)
        log_end_msg 1
        ;;
    esac
    exit $ret
    ;;
reload|force-reload)
    echo "Checking HAProxy configuration first"
    haproxy_checkconf
    case "$?" in
    0)
        echo "Everything looks fine"
        ;;
    1)
        echo "Errors..."
        exit 1
        ;;
    esac

    log_daemon_msg "Reloading haproxy" "haproxy"
    haproxy_reload
    case "$?" in
    0|1)
        log_end_msg 0
        ;;
    2)
        log_end_msg 1
        ;;
    esac
    ;;
restart)
    echo "Checking HAProxy configuration first"
    haproxy_checkconf
    case "$?" in
    0)
        echo "Everything looks fine"
        ;;
    1)
        echo "Errors..."
        exit 1
        ;;
    esac

    log_daemon_msg "Restarting haproxy" "haproxy"
    haproxy_stop
    haproxy_start
    case "$?" in
    0)
        log_end_msg 0
        ;;
    1)
        log_end_msg 1
        ;;
    2)
        log_end_msg 1
        ;;
    esac
    ;;
status)
    haproxy_status
    ret=$?
    case "$ret" in
    0)
        echo "haproxy is running."
        ;;
    1)
        echo "haproxy dead, but $PIDFILE exists."
        ;;
    *)
        echo "haproxy not running."
        ;;
    esac
    exit $ret
    ;;
*)
    echo "Usage: /etc/init.d/haproxy {start|stop|reload|restart|status|checkconf}"
    exit 2
    ;;
esac
:
