#!/bin/sh

PATH=$PATH:/bin:/sbin:/usr/sbin
CUR_PATH=$(dirname "$0")
SERVICE_BIN=$CUR_PATH/ksa_service
LAUNCHD_PLIST=/Library/LaunchDaemons/com.kanxue.ksa.launchd.plist

start() {
    if pgrep 'ksa_service' > /dev/null; then
        return 1
    fi
    if [ -f $LAUNCHD_PLIST ]; then
        launchctl load -w $LAUNCHD_PLIST
    else
        ($CUR_PATH/ksa_service &)
    fi
    return 0
}

stop() {
    launchctl remove com.kanxue.ksa.launchd
    pgrep 'ksa_service' | xargs kill -9
    while [ $(pgrep 'ksa_service') > /dev/null ]; do sleep 0.1; done
    return 0
}

restart() {
    stop && start
}

status() {
    echo -n "Checking for KsaService"
    if pgrep 'ksa_service' > /dev/null; then
        echo " ...running"
    else
        echo " ...not running"
    fi
}

ksa_setup() {
    sed "s:SERVICE_BIN:$SERVICE_BIN:g" $CUR_PATH/com.kanxue.ksa.launchd.plist > $LAUNCHD_PLIST
    chmod 444 $LAUNCHD_PLIST
}

ksa_remove() {
    launchctl remove com.kanxue.ksa.launchd
    rm -f $LAUNCHD_PLIST 
}

case "$1" in
start)
    start
    ;;
stop)
    stop
    ;;
restart)
    restart
    ;;
status)
    status
    ;;
setup)
    ksa_remove
    ksa_setup
    ;;
remove)
    ksa_remove
    ;;
*)
    echo "Usage: $0 {start|stop|restart|status}"
    exit 1
esac

exit $RETVAL
