#!/usr/bin/env sh

##############################################################################
##
##  syncany start up script for UN*X
##
##############################################################################

# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
        PRG="$link"
    else
        PRG=`dirname "$PRG"`"/$link"
    fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/.." >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null

APP_NAME="syncany"
APP_BASE_NAME=`basename "$0"`

# Add default JVM options here. You can also use JAVA_OPTS and SYNCANY_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Dfile.encoding=utf-8"'

# Read max memory from userconfig.xml #SYNCANY_INCL_2#
APP_USERCONFIG_DIR=~/.config/syncany
APP_USERCONFIG_FILE=$APP_USERCONFIG_DIR/userconfig.xml

if [ -f $APP_USERCONFIG_FILE ]; then
    APP_MAX_MEMORY=$(cat $APP_USERCONFIG_FILE | sed -n 's/.*<maxMemory>\([^<]*\)<\/maxMemory>.*/\1/p')
fi

if [ -z "$APP_MAX_MEMORY" ]; then
    DEFAULT_JVM_OPTS="$DEFAULT_JVM_OPTS \"-Xmx512M\""
else
    DEFAULT_JVM_OPTS="$DEFAULT_JVM_OPTS \"-Xmx$APP_MAX_MEMORY\""
fi

# Force SWT/GTK2 (workaround until SWT/GTK3 tables work right) #SYNCANY_INCL_1#
export SWT_GTK3=0


# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"

warn () {
    echo "$*"
}

die () {
    echo
    echo "$*"
    echo
    exit 1
}

# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
  CYGWIN* )
    cygwin=true
    ;;
  Darwin* )
    darwin=true
    ;;
  MINGW* )
    msys=true
    ;;
  NONSTOP* )
    nonstop=true
    ;;
esac

# Determine CLASSPATH (with user plugin JAR preference) #SYNCANY_INCL_4#
CLASSPATH="$APP_USERCONFIG_DIR/plugins/lib/*"
LIBS_GLOBAL=$(ls $APP_HOME/lib/*.jar)
LIBS_PLUGINS_GLOBAL=$(ls $APP_HOME/lib/syncany-plugin-*.jar 2> /dev/null)

for LIB_GLOBAL in $LIBS_GLOBAL; do
	LIB_GLOBAL_BASENAME=$(basename $LIB_GLOBAL)

	if [ "$LIB_GLOBAL_BASENAME" = syncany-plugin-*.jar ]; then
		PLUGIN_JAR_PREFIX=$(expr match "$LIB_GLOBAL_BASENAME" '\(syncany-plugin-[^-]*-\)')
		IN_USER_PLUGINS=$(ls $APP_USERCONFIG_DIR/plugins/lib/$PLUGIN_JAR_PREFIX*.jar 2> /dev/null)

		if [ -z "$IN_USER_PLUGINS" ]; then
			CLASSPATH="$CLASSPATH:$LIB_GLOBAL"
		fi
	else
		CLASSPATH="$CLASSPATH:$LIB_GLOBAL"
	fi
done

# For Darwin / Mac OS X: Add -XstartOnFirstThread (to fix SWT) #SYNCANY_INCL_3#
if $darwin; then
    DEFAULT_JVM_OPTS="$DEFAULT_JVM_OPTS \"-XstartOnFirstThread\""
fi

# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
        # IBM's JDK on AIX uses strange locations for the executables
        JAVACMD="$JAVA_HOME/jre/sh/java"
    else
        JAVACMD="$JAVA_HOME/bin/java"
    fi
    if [ ! -x "$JAVACMD" ] ; then
        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
else
    JAVACMD="java"
    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi

# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
    MAX_FD_LIMIT=`ulimit -H -n`
    if [ $? -eq 0 ] ; then
        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
            MAX_FD="$MAX_FD_LIMIT"
        fi
        ulimit -n $MAX_FD
        if [ $? -ne 0 ] ; then
            warn "Could not set maximum file descriptor limit: $MAX_FD"
        fi
    else
        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
    fi
fi

# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi

# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
    JAVACMD=`cygpath --unix "$JAVACMD"`

    # We build the pattern for arguments to be converted via cygpath
    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
    SEP=""
    for dir in $ROOTDIRSRAW ; do
        ROOTDIRS="$ROOTDIRS$SEP$dir"
        SEP="|"
    done
    OURCYGPATTERN="(^($ROOTDIRS))"
    # Add a user-defined pattern to the cygpath arguments
    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
    fi
    # Now convert the arguments - kludge to limit ourselves to /bin/sh
    i=0
    for arg in "$@" ; do
        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option

        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
        else
            eval `echo args$i`="\"$arg\""
        fi
        i=$((i+1))
    done
    case $i in
        (0) set -- ;;
        (1) set -- "$args0" ;;
        (2) set -- "$args0" "$args1" ;;
        (3) set -- "$args0" "$args1" "$args2" ;;
        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
    esac
fi

# Escape application args
save () {
    for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
    echo " "
}
APP_ARGS=$(save "$@")

# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS --illegal-access=permit --add-opens java.base/java.lang=ALL-UNNAMED $JAVA_OPTS $SYNCANY_OPTS -classpath "\"$CLASSPATH\"" org.syncany.Syncany "$APP_ARGS"

# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
  cd "$(dirname "$0")"
fi

### Daemon script begin #########################################SYNCANY_INCL_5#

# Daemon variables
DAEMON_NAME=syncanyd
DAEMON_APPDIR=~/.config/syncany
DAEMON_CONTROLFILE=$DAEMON_APPDIR/daemon.ctrl
DAEMON_PIDFILE=$DAEMON_APPDIR/daemon.pid
DAEMON_CMD="daemon run"

# Daemon functions
daemon_get_pid() {
	local PID

	if [ -e "$DAEMON_PIDFILE" ]; then
		PID=$(cat "$DAEMON_PIDFILE")
	fi

	if [ -n "$PID" ]; then
		echo $PID
	else
		echo -1
	fi
}

daemon_running() {
	ID=$(daemon_get_pid)
	
	if [ "$ID" == "-1" ]; then
		echo "0"
	elif [ -n "$(ps -p"$ID" -opid=)" ]; then
		echo "1"
	else
		echo "0"
	fi	
}

daemon_start() {
	DAEMON_RUNNING=$(daemon_running)
	
	echo -n "Starting daemon: "
	
	if [ "$DAEMON_RUNNING" == "1" ]; then
		echo "$DAEMON_NAME already running (pid $DAEMON_PID)"
	else
		nohup "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.syncany.Syncany $DAEMON_CMD > /dev/null 2>&1 &

		DAEMON_PID="-1"
		TRIES=10
		
		while [ "$DAEMON_RUNNING" == "0" -a $TRIES -gt 0 ]; do
			DAEMON_RUNNING=$(daemon_running)
			echo -n "."
		
			DAEMON_PID="$(daemon_get_pid)"
			TRIES=$(($TRIES-1))
			sleep 1
		done
		
		if [ $TRIES -eq 0 ]; then
			echo " Failed to start process. EXITING."
			echo "Failed command line: $ $DAEMON $DAEMON_CMD"
			exit 2
		fi
		
		echo " $DAEMON_NAME (pid $DAEMON_PID)."
	fi
}

daemon_stop() {
	DAEMON_RUNNING=$(daemon_running)

	echo -n "Stopping daemon: "
	
	if [ "$DAEMON_RUNNING" == "0" ]; then
		echo "$DAEMON_NAME not running"
	else
		echo "shutdown" >> $DAEMON_CONTROLFILE
		
		TRIES=10
		while [ "$DAEMON_RUNNING" == "1" -a $TRIES -gt 0 ]; do
			DAEMON_RUNNING=$(daemon_running)
			echo -n "."
		
			TRIES=$(($TRIES-1))
			sleep 1
		done
		
		if [ $TRIES -eq 0 ]; then
			echo " Failed to stop process $DAEMON_PID. Try 'force-stop'. EXITING."
			exit 3
		fi
		
		echo " $DAEMON_NAME stopped."
	fi
}

daemon_force_stop() {
	DAEMON_RUNNING="$(daemon_running)"

	echo -n "Force-stopping daemon: "

	if [ "$DAEMON_RUNNING" == "0" ]; then
		echo "$DAEMON_NAME not running"
	else
		kill -9 "$DAEMON_PID"
		
		DAEMON_RUNNING="$(daemon_running)"
		
		sleep 1
			
		DAEMON_RUNNING=$(daemon_running)
		
		if [ "$DAEMON_RUNNING" == "1" ]; then
			echo "Failed to kill -9 $DAEMON_PID. EXITING."
		else 
			rm "$DAEMON_PIDFILE" 2> /dev/null
			rm "$DAEMON_CONTROLFILE" 2> /dev/null

			echo "Killed $DAEMON_NAME (pid $DAEMON_PID)."
		fi
	fi
}

daemon_status() {
	DAEMON_RUNNING="$(daemon_running)"
	echo -n "Checking daemon: $DAEMON_NAME"
	
	if [ "$DAEMON_RUNNING" == "0" ]; then
		echo " not running"
	else
		echo " running (pid $DAEMON_PID)."
	fi
}

daemon_reload() {
	DAEMON_RUNNING="$(daemon_running)"
	echo -n "Reloading daemon: $DAEMON_NAME"
	
	if [ "$DAEMON_RUNNING" == "0" ]; then
		echo " not running"
	else
		echo "reload" >> $DAEMON_CONTROLFILE
		echo "."
	fi
}

export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"

mkdir -p "$DAEMON_APPDIR"
DAEMON_PID="$(daemon_get_pid)"

case "$1" in      
	daemon)                   
		case "$2" in         
			"")
				echo "Usage: sy daemon (start|stop|reload|status|force-stop|add|remove|list)"
				;;        
			start) 
				daemon_start
				;;     
			stop) 
				daemon_stop
				;;     
			restart) 
				daemon_stop
				daemon_start				
				;;     
			status)
				daemon_status
				;;     
			reload)
				daemon_reload
				;;     
			force-stop) 
				daemon_force_stop
				;; 
			*) 
				exec "$JAVACMD" "$@"
				;;
		esac
		;;  
	
	*)                       
		exec "$JAVACMD" "$@"
		;;
esac                          
