#!/bin/sh

PID_FILE='/var/run/elephantdrive.pid'
BASE="/var/packages/elephantdrive/target"
CONFIG_DIR="/var/packages/elephantdrive/etc/"
LOG_FILE="$BASE/var/log/elephantdrive.log"
export LD_LIBRARY_PATH="$BASE/lib"
cd /

set_proxy()
{
	if [ -f /etc/proxy.conf ]; then
		. /etc/proxy.conf
		if [ "$proxy_enabled" = "yes" ]; then
			export http_proxy="$https_host":"$https_port"
		fi
	fi
}

start_service ()
{
    set_proxy
		touch ${CONFIG_DIR}/elephantdrive.config
		if [ -f "/usr/syno/etc/smb.conf" ]; then
			SMB_CONF="/usr/syno/etc/smb.conf"
		else
			#DSM 6
			SMB_CONF="/etc/samba/smb.share.conf"
		fi
		# Launch the server in the background.
    ${BASE}/bin/elephantdrive -D -c ${CONFIG_DIR} \
		"WebUIPort=17017" \
		"WebUIAddress=0.0.0.0" \
		"WebUIWWWRoot=$BASE/www" \
    "AppRoot=$BASE" \
    "SmbConfFile=$SMB_CONF" \
    "VetoFiles=/@eaDir/"
    return $?
}

stop_service ()
{
    # Kill elephantdriveDaemon
    ${BASE}/bin/elephantdrive -K
}

#status_service ()
#{
#    ${BASE}/bin/elephantdrive -S
#    return $?
#}

status_service ()
{
    if [ -f "${PID_FILE}" ] && [ -d /proc/`cat "${PID_FILE}"` ]; then
        return 0
    fi
    if [ -f "${PID_FILE}" ]; then
        return 1
    fi
    return 3
}

case $1 in
    start)
        start_service
        echo "Running ElephantDrive"
        exit 0
        ;;
    stop)
        stop_service
        echo "Stopped ElephantDrive"
        exit 0
        ;;
    status)
				status_service
        sts=$?
        if [ $sts -eq 0 ]; then
            echo "ElephantDrive is running"
        else
            echo "ElephantDrive is not running"
        fi
        exit $sts
        ;;

    log)
        if [ -f $LOG_FILE ];
        then
           echo $LOG_FILE
        fi
        exit 0
        ;;
    *)
        exit 1
        ;;
esac
