#!/bin/bash
set -e

### BEGIN INIT INFO
# Provides:           toxiproxy
# Required-Start:     $syslog $remote_fs
# Required-Stop:      $syslog $remote_fs
# Default-Start:      2 3 4 5
# Default-Stop:       0 1 6
# Short-Description:  proxy to simulate network and system conditions
# Description:
#  Toxiproxy is a framework for simulating network conditions. It's made
#  specifically to work in testing, CI and development environments,
#  supporting deterministic tampering with connections, but with support
#  for randomized chaos and customization. Toxiproxy is the tool you need
#  to prove with tests that your application doesn't have single points of
#  failure.
### END INIT INFO

USER=toxiproxy
GROUP=toxiproxy
name=toxiproxy
desc=proxy
daemon=/usr/bin/toxiproxy

if [ -r /lib/lsb/init-functions ]; then
    source /lib/lsb/init-functions
fi

# Default
DEFAULT=/etc/default/toxiproxy
if [ -r $DEFAULT ]; then
    source $DEFAULT
fi

# STDOUT
if [ -z "$STDOUT" ]; then
    STDOUT=/var/log/toxiproxy/toxiproxy.log
fi
if [ ! -f "$STDOUT" ]; then
    mkdir -p $(dirname $STDOUT)
fi

# STDERR
if [ -z "$STDERR" ]; then
    STDERR=/var/log/toxiproxy/toxiproxy.log
fi
if [ ! -f "$STDERR" ]; then
    mkdir -p $(dirname $STDERR)
fi

# pid file for the daemon
pidfile=/var/run/toxiproxy/toxiproxy.pid
piddir=$(dirname $pidfile)

if [ ! -d "$piddir" ]; then
    mkdir -p $piddir
    chown $GROUP:$USER $piddir
fi

case $1 in
    start)
        log_daemon_msg "Starting $desc" "$name"
        start-stop-daemon --oknodo --chuid $GROUP:$USER --start --quiet --make-pidfile --pidfile $pidfile --exec $daemon -- -port $TOXIPROXY_PORT -host $TOXIPROXY_HOST $TOXIPROXY_OPTS >>$STDOUT 2>>$STDERR &
        status=$?
        log_end_msg $status
        ;;

    stop)
        log_daemon_msg "Stopping $desc" "$name"
        start-stop-daemon --stop --quiet --oknodo --pidfile $pidfile
        status=$?
        log_end_msg $status
        rm -f $pidfile
        ;;

    restart|force-reload)
        $0 stop && sleep 2 && $0 start
        ;;

    status)
        status_of_proc $daemon "toxiproxy"
        ;;

    *)
        # For invalid arguments, print the usage message.
        echo "Usage: $0 {start|stop|restart|status}"
        exit 2
        ;;
esac
