#!/bin/sh

APPNAME="MindtimeProBackup"
PACKAGE_DIRNAME="$(basename "$(dirname "$(dirname "$(realpath $0)")")")"

if [ "$SYNOPKG_PKGNAME" != "" ]; then
    APPNAME=$SYNOPKG_PKGNAME
elif [ "$PACKAGE_DIRNAME" != "" ] && [ "$APPNAME" != "$PACKAGE_DIRNAME" ]; then
    # Use App name extracted from script location if $SYNOPKG_PKGNAME is empty
    APPNAME=$PACKAGE_DIRNAME
fi

BASE="/var/packages/$APPNAME/target"
if [ "$SYNOPKG_PKGDEST" != "" ]; then
    BASE=$SYNOPKG_PKGDEST
fi

APP_HOME="$BASE/obm"
SERVICE_LOG=$APP_HOME/log/Scheduler/cbs.log

# This method only works on DSM6
PARENT_COMMAND="$(ps -o comm= $PPID)"

SERVICE="scheduler"

gen_environment()
{
    # Only if the script is run by Package Center Installer
    if [ "$SYNOPKG_PKG_STATUS" != "" ]; then
        echo "Generate environemnt variables. SYNOPKG_PKG_STATUS=$SYNOPKG_PKG_STATUS"
        APP_NAME=$SYNOPKG_PKGNAME
        APP_BASE=$SYNOPKG_PKGDEST
        APP_OS=DSM
        RC_PATH="/usr/local/etc/rc.d"
        echo "APP_NAME=$SYNOPKG_PKGNAME" > $SYNOPKG_PKGDEST/ui/env
        echo "APP_VER=$SYNOPKG_PKGVER" >> $SYNOPKG_PKGDEST/ui/env
        echo "APP_BASE=$APP_BASE" >> $SYNOPKG_PKGDEST/ui/env
        echo "APP_OS=DSM" >> $SYNOPKG_PKGDEST/ui/env
        echo "APP_RC=/var/packages/$APP_NAME/scripts/start-stop-status" >> $SYNOPKG_PKGDEST/ui/env
        if [ -f "$SYNOPKG_PKGDEST/debug" ]; then
            echo "APP_DEBUG_MODE=Y" >> $SYNOPKG_PKGDEST/ui/env
        else
            echo "APP_DEBUG_MODE=N" >> $SYNOPKG_PKGDEST/ui/env
        fi
        echo "USER_BASE=$APP_BASE/.obm" >> $SYNOPKG_PKGDEST/ui/env
        echo "DSM_LANG=$SYNOPKG_DSM_LANGUAGE" >> $SYNOPKG_PKGDEST/ui/env
        echo "DSM_VER_MAJOR=$SYNOPKG_DSM_VERSION_MAJOR" >> $SYNOPKG_PKGDEST/ui/env
        echo "DSM_VER_MINOR=$SYNOPKG_DSM_VERSION_MINOR" >> $SYNOPKG_PKGDEST/ui/env
        echo "DSM_VER_BUILD=$SYNOPKG_DSM_VERSION_BUILD" >> $SYNOPKG_PKGDEST/ui/env
        echo "DSM_ARCH=$SYNOPKG_DSM_ARCH" >> $SYNOPKG_PKGDEST/ui/env
    fi
}

status_scheduler()
{
    #[[ `get_running_scheduler_pid` == -1 ]] && return 1 || return 0
    sch_pid=`get_running_scheduler_pid`
    if [ $sch_pid == -1 ]; then
        return 1
    else
        return 0
    fi
}

status_wuiservice()
{
    if [ -f "$APP_HOME/WuiService.pid" ]; then
        PID=`cat $APP_HOME/WuiService.pid`
        if [ -d "/proc/$PID" ]; then
            return 0
        fi
    fi
    return 1
}

status_service()
{
    status=0
    case $1 in
        scheduler)
            status_scheduler
            status=$?
            ;;
        # wuiservice)
        #     status_wuiservice
        #     status=$?
        #     ;;
        # all)
            #status_scheduler
            #status1=$?
            # status1=0
            # status_wuiservice
            # status2=$?
            # status=$(($status1 | $status2))
            # status_scheduler
            # status=$?
            # ;;
        *)
            # echo "unknown"
            echo "Cannot get status of unknown service \"$1\""
            status=1
            ;;
    esac
    return $status
}

start_scheduler()
{
    # update env
    gen_environment
    status_scheduler
    status=$?
    if [ $status -eq 0 ]
    then
        echo "Scheduler is already running"
        # Use 255 as already running status code
        return 255
    fi
    kill_leftover_processes
    # Make sure the script is executable
    chmod 755 $APP_HOME/bin/Scheduler.sh
    # Start background services
    output=`$APP_HOME/bin/Scheduler.sh`
    return $?
}

start_wuiservice()
{
    # update env
    gen_environment
    status_wuiservice
    status=$?
    if [ $status -eq 0 ]
    then
        echo "Command Server is already running"
        # Use 255 as already running status code
        return 255
    fi
    # Make sure the script is executable
    chmod 755 $APP_HOME/bin/WuiService.sh
    # Start background services
    output=`$APP_HOME/bin/WuiService.sh $BASE/.obm 32168`
    return $?
}

start_service()
{
    status=0
    case $1 in
        scheduler)
            start_scheduler
            status1=$?
            # Do not need to anything if it is already running, and return 0
            if [ $status1 -eq 255 ]; then
                return 0
            fi
            status_scheduler
            status2=$?
            status=$(($status1 | $status2))
            if [ $status -eq 0 ]
            then
                # Create startup tag to preserve the status after reboot
                mkdir -p $BASE/.obm/config
                touch $BASE/.obm/config/scheduler.run
            else
                # Remove startup tag if failed to start
                rm -f $BASE/.obm/config/scheduler.run
            fi
            ;;
        # wuiservice)
        #     start_wuiservice
        #     status=$?
        #     ;;
        # all)
            # For DSM5, it'll be called by root during bootup
            # For DSM6, it'll be called by sh and synopkgctl during bootup
            # Not allowing startup from Synology Package Centre
            # if [ $PARENT_COMMAND == "synopkgctl" ]; then
                # Not allow if it is run by Package Center during bootup to prevent double start
                # if [ "$SYNOPKG_PKG_STATUS" == "" ]; then
                    # return 0
                # fi
            # fi
            # if [ -f "$BASE/.obm/config/scheduler.run" ]; then
            #     start_scheduler
            #     status1=$?
            # else
            #     status1=0
            # fi
            # start_wuiservice
            # status2=$?
            # status=$(($status1 | $status2))
            # start_scheduler
            # status=$?
            # ;;
        *)
            echo "Cannot start unknown service \"$1\""
            status=1
            ;;
    esac
    return $status
}

stop_scheduler()
{
    kill_leftover_processes
    status_scheduler
    status=$?
    if [ $status -eq 1 ]; then
        echo "Skip stopping scheduler since it is not running"
        return 0
    fi
    if [ -f "$APP_HOME/ipc/Scheduler/running" ]; then
        echo "Stopping scheduler by creating IPC stop file"
        touch $APP_HOME/ipc/Scheduler/stop
    fi
    counter=15
    while [ $counter -gt 0 ]; do
        # PID=`cat $APP_HOME/Scheduler.pid`
        # echo "Killing PID $PID" >> /tmp/status.log
        # kill -9 $PID
        # echo "Killed Scheduler = $?" >> /tmp/status.log
        status_scheduler
        status=$?
        if [ $status -eq 1 ]; then
            echo "Successfully stop scheduler by creating IPC stop file"
            return 0
        fi
        sleep 2
        let counter=counter-1
    done
    echo "Cannot stop scheduler by creating stop IPC and wait 30s"
    # Kill background services
    #$BASE/bin/obm/bin/StopScheduler.sh
    if [ -f "$APP_HOME/Scheduler.pid" ]; then
        PID=`cat $APP_HOME/Scheduler.pid`
        if [ -d "/proc/$PID" ]; then
            kill -9 $PID
            echo "Stopped scheduler by kill scheduler process of process ID: $PID"
            return 0
        fi
    fi
    return 1
}

stop_wuiservice()
{
    status_wuiservice
    status=$?
    if [ $status -eq 1 ]; then
        return 1
    fi
    counter=15
    while [ $counter -gt 0 ]; do
        PID=`cat $APP_HOME/WuiService.pid`
        echo "Killing PID $PID" >> /tmp/status.log
        kill -9 $PID
        echo "Killed WuiService = $?" >> /tmp/status.log
        status_wuiservice
        status=$?
        if [ $status -eq 1 ]; then
            return 1
        fi
        let counter=counter-1
    done
    return 0
}

stop_service()
{
    status=0
    case $1 in
        scheduler)
            # Remove startup tag only in manual operation
            rm -f $BASE/.obm/config/scheduler.run
            stop_scheduler
            status=$?
            ;;
        # wuiservice)
        #     stop_wuiservice
        #     status=$?
        #     ;;
        # all)
            # stop_scheduler
            # status1=$?
            # status=$?
            #status1=0
            # stop_wuiservice
            # status2=$?
            # status=$(($status1 | $status2))
            # ;;
        *)
            echo "Cannot stop unknown service \"$1\""
            status=1
            ;;
    esac
    return $status
}

# This method will be called by `get_running_scheduler_pid`, result will based on echo content
# so don't added any log message to this method
get_running_scheduler_pid()
{
    if [ -f "$APP_HOME/Scheduler.pid" ]; then
        PID=`cat $APP_HOME/Scheduler.pid`
        if [ -d "/proc/$PID" ]; then
            echo $PID
            return 0
        fi
    fi
    echo -1
}

kill_leftover_processes()
{
    echo "Start kill leftover process"
    running_scheduler_pid=`get_running_scheduler_pid`
    if [ $running_scheduler_pid != -1 ]; then
        echo "Exclude scheduler process id: $running_scheduler_pid"
    fi
    app_home_real_path=`readlink -f $APP_HOME`
    if [[ -z $app_home_real_path ]]; then
        app_home_real_path=$APP_HOME
    fi
    grep -l "^$app_home_real_path" /proc/*/cmdline | while read -r cmdline_path; do
        pid=`echo $cmdline_path |  awk -F / '{print $3}'`
        if [[ $pid != $running_scheduler_pid ]]; then
            echo "Kill leftover process: $pid" 
            kill -9 $pid
        fi
    done
}

if [ -n "$2" ]; then
    SERVICE=$2
fi

case $1 in
    start)
        echo "Running ${APPNAME} - ${SERVICE}"|tee -a $SERVICE_LOG
        start_service $SERVICE 2>&1|tee -a $SERVICE_LOG
        status=${PIPESTATUS[0]}
        echo "Start service completed. Exit code=$status"|tee -a $SERVICE_LOG
        exit $status
        ;;
    stop)
        echo "Stopping ${APPNAME} - ${SERVICE}"|tee -a $SERVICE_LOG
        stop_service $SERVICE 2>&1|tee -a $SERVICE_LOG
        status=${PIPESTATUS[0]}
        echo "Stop service completed. Exit code=$status"|tee -a $SERVICE_LOG
        exit $status
        ;;
    status)
        status_service $SERVICE
        status=$?
        if [ $status == 0 ]
        then
            echo "${APPNAME} is running - ${SERVICE}"
        else
            echo "${APPNAME} is not running - ${SERVICE}"
        fi
        exit $status
        ;;
    log)
        # Create a log file with embedded link to collect all necessary files
        # Which the link would be shown in package centre for easier access
        echo '<a href="/webman/3rdparty/'${APPNAME}'/cb.cgi?m=logcollect" target="_blank">Download Logs</a>' > $APP_HOME/logcollect.lnk
        echo $APP_HOME/logcollect.lnk
        ;;
    *)
        exit 1
        ;;
esac

