#!/bin/sh

APP_PID=/var/run/icecast.pid

create_config() {
    uci -q get icecast
    if [ $? -ne 0 ]; then
        cp -f /barix/config/defaults/icecast /barix/config/current/
    fi
}

start() {
    create_config

    # change configuration file owner
    chown icecast /etc/icecast.xml

    # create log directory and change the owner
    if [ ! -d /var/log/icecast ]; then
        mkdir -p /var/log/icecast
        chown icecast /var/log/icecast
    fi

    ICECAST_ENABLED=$(uci -q get icecast.general.enabled)
    if [ "${ICECAST_ENABLED}" == "true" ]; then
        CONFIGURATION_FILE=$(uci -q get icecast.general.configuration_file)
        barix-wd --pid-file=$APP_PID --timeout=10 --background --start -- \
            su -c "/usr/bin/icecast -c ${CONFIGURATION_FILE}" icecast
    fi
}

stop() {
    barix-wd --pid-file=$APP_PID --stop --wait
}


# See how we were called.
case "$1" in
    start)
        start
    ;;

    stop)
        stop
    ;;

    restart)
        stop
        start
    ;;

  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac

exit $?

