{#
# Copyright 2015 Hewlett-Packard Development Company, L.P.
#
#    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
#}

description "Properly handle haproxy"

start on runlevel [2345]
stop on runlevel [!2345]

env PID_PATH={{ haproxy_pid }}
env BIN_PATH={{ haproxy_cmd }}
env CONF_PATH={{ haproxy_cfg }}
env USER_GROUP_CONF_PATH={{ haproxy_user_group_cfg }}
env PEER_NAME={{ peer_name }}

respawn
respawn limit {{ respawn_count }} {{respawn_interval}}

pre-start script
    [ -r $CONF_PATH ]
    # 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 with 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 %}

end script

script
exec /bin/bash <<EOF
echo \$(date) Starting HAProxy
# The -L trick fixes the HAProxy limitation to have long peer names

ip netns exec {{ amphora_nsname }} $BIN_PATH -f $CONF_PATH -f $USER_GROUP_CONF_PATH -L $PEER_NAME -D -p $PID_PATH

trap "ip netns exec {{ amphora_nsname }} $BIN_PATH -f $CONF_PATH -f $USER_GROUP_CONF_PATH -L $PEER_NAME -p $PID_PATH -sf \\\$(cat $PID_PATH)" SIGHUP
trap "kill -TERM \\\$(cat $PID_PATH) && rm $PID_PATH;echo \\\$(date) Exiting HAProxy; exit 0" SIGTERM SIGINT

while true; do # Iterate to keep job running.

# Check if HAProxy has failed and re-spawn
kill -0 \$(cat $PID_PATH)
if [ \$? -ne 0 ]; then
  echo \$(date) HAProxy failed. Respawning
  exit 1
fi

sleep 1 # Don't sleep to long as signals will not be handled during sleep.
done
EOF
end script
