#!/bin/dash
# pgadmin4 startup script
# jamesbond 2018 - MIT license

### configuration
APPTITLE="$(gettext 'pgAdmin4')"
XTERM="defaultterm"
BINFILE=/opt/pgadmin4/pgAdmin4.py
PORT=5050
PIDFILE=/tmp/pgadmin4.pid

### make sure we run in terminal - input: $@
run_in_terminal() {
	# check we're running in terminal, if not, re-exec
	if ! test -t 0; then
		# not on terminal, re-exec on terminal
		if [ $DISPLAY ]; then
			if type exec_with_sane_terminal > /dev/null; then
				TERM_SANE_TERM="$XTERM" exec_with_sane_terminal "$0" "$@"
			else
				exec $XTERM -e "$0" "$@"
			fi
		else
			exit
		fi
	fi
}

### main

# kill previous instance
if [ -e $PIDFILE ]; then
	read pid < $PIDFILE
	kill $pid
	rm -f $PIDFILE
fi

# start it
if ! [ -e  /var/lib/pgadmin/pgadmin4.db ]; then
	# first run, must run in terminal
	run_in_terminal # because it will ask you for email, etc stuff
	dumb-init python $BINFILE
	exit # exit when done
else
	# subsequent run, run as daemon
	dumb-init python $BINFILE &
	echo $! > $PIDFILE
	sleep 3
	exec defaultbrowser "http://localhost:$PORT"
fi
