#!/bin/bash
### BEGIN INIT INFO
# Provides:          vagrant-vmware-utility
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Vagrant VMware Utility Service
# Description:       Provides the Vagrant VMware REST API
### END INIT INFO

name=$(basename $0)
pid_file="/var/run/$name.pid"
log="/var/log/$name.log"
cmd="/opt/vagrant-vmware-desktop/bin/vagrant-vmware-utility"
cmdargs="api -config-file="/opt/vagrant-vmware-desktop/config/service.hcl" -log-file=$log"

if [ -f /usr/lsb/init-functions ]; then
    lsb=1
    . /usr/lsb/init-functions
else
    lsb=0
    . /etc/init.d/functions
    function log_success_msg() {
        echo $1
    }
    function log_warning_msg() {
        echo $1
    }
    function log_failure_msg() {
        echo $1
    }
fi

is_running() {
    pidofproc -p $pid_file $cmd
}

case "$1" in
    start)
        if is_running; then
            log_warning_msg "Service already running"
        else
            if [ $lsb -eq 1 ]; then
                start_daemon -p $pid_file $cmd $cmdargs
            else
                daemon --pidfile=$pid_file $cmd $cmdargs
            fi
            if ! is_running; then
                log_failure_msg "Failed to start $name"
                exit 1
            fi
            log_success_msg "Started service $name"
        fi
        ;;
    stop)
        if ! is_running; then
            log_warning_msg "Service not running"
        else
            killproc -p $pid_file $cmd
            if is_running; then
                log_failure_msg "Failed to stop $name"
                exit 1
            fi
            log_success_msg "Stopped service $name"
        fi
        ;;
    restart)
        $0 stop
        if is_running; then
            log_failure_msg "Failed to restart $name"
            exit 1
        fi
        $0 start
        if ! is_running; then
            log_failure_msg "Failed to restart $name"
            exit 1
        fi
        log_success_msg "Restarted service $name"
        ;;
    force-reload)
        if ! is_running; then
            log_failure_msg "Service not running"
            exit 1
        fi
        $0 restart
        if !is_running; then
            log_failure_msg "Failed to reload $name"
            exit 1
        fi
        log_success_msg "Reloaded service $name"
        ;;
    status)
        if ! is_running; then
            exit 3
        fi
        ;;
esac

exit 0
