#!/bin/sh

usage() {
    echo "usage $(basename $0) <status|start|stop|restart>"
}

isRunning() {
    ps aux|awk '/node \.\/soundfics.js/{ print $2}'
    # ps -C node -o pid,command | awk '/soundfics.js/{print $1}'
}

if [ ${#} -ne 1 ] ; then
    usage
    exit 1
fi

ACTION=${1}
PID=$(isRunning)

case ${ACTION} in
    "start")
        if [ ! -z  ${PID} ] ; then
            echo "already running, stop first"
            exit 1
        fi
        # if symlink then go to workdir
        if [ -L ${0} ] ; then
            cd $(dirname $(readlink -en ${0}))
        fi
        yarn start
        ;;
    "stop")
        if [ -z ${PID} ]; then
            echo 'not running'
        else
            kill ${PID}
        fi
        ;;
    "status")
        if [ -z ${PID} ]; then
            echo 'not running'
        else
            echo "running"
        fi
        ;;
    "restart")
        ${0} stop
        ${0} start
        ;;
    *)
        usage
        ;;
esac
