#!/usr/bin/env bash
VERSION=1.1.9
#--- Enable check error -------------------------
SYS_TRAP='trap "exit 1" ERR '
trap "exit 1" ERR 2>/dev/null
if [ "$?" != 0 ]; then
	SYS_TRAP="set -e"
	set -e 2>/dev/null
fi

#--- Default values -----------------------------
 
MPLC_PATH=/opt/mplc4
MPLC_INIT=/etc/init.d/mplc4
MPLC_TAR=mplc4.tar.gz
MPLC_BASE_PORT=31550
MPLC_USER=root
MPLC_RC_PRIORITY=99
MPLC_WDT=ON
MPLC_CFG_ONLY=OFF
MPLC_AUTOSTART_DELAY=0
MPLC_GROUP=$MPLC_USER
MPLC_START_SCRIPT=start_mplc4.sh
MPLC_UNINSTALL_SCRIPT=uninstall.sh
MPLC_LOGS=OFF
MPLC_DUMP=OFF
MPLC_EXEMPLARS=0
MPLC_NETKEY=OFF

MPLC_USE_UPLOAD_PATH=OFF
MPLC_UPLOAD_PATH=""

NGINX_PATH=
NGINX_TAR=nginx.tar.gz
NGINX_LOGS=/var/log/nginx
NGINX_PID_FILE=$NGINX_LOGS/nginx.pid
NGINX_CONFIG=conf/nginx-mplc.conf
NGINX_HTTP_PORT=80
NGINX_HTTPS_PORT=443
NGINX_UPDATE=ON
NGINX_HTTP=ON
NGINX_HTTPS=OFF
NGINX_USER=root
NGINX_GZIP=ON
NGINX_USER_DIR_ENABLED=OFF
NGINX_USER_DIR=/etc/nginx/sites-enabled/*.conf
NGINX_SERVER_NAME=_
NGINX_WITH_HSTS=OFF

DOTNET_DIR=
DOTNET_TAR=dotnet-runtime.tar.gz
NETCORE_PLUGINS_DIR=
NETCORE_PLUGINS_TAR=netcore.tar.gz

ADMIN_INTERFACE_DIR=
ADMIN_INTERFACE_TAR=admin.tar.gz

NEW_SERVICE=ON
RTSP_DIR=
RTSP_TAR=rtsp.tar.gz
RTSP_SERVICE=OFF

SET_PASSWORD=OFF

CODESYS_NAME=plclinux_rt
CODESYS_KILL=OFF

SYS_I386_DEP=OFF
SYS_SHELL=sh
SYS_PIDOF=pidof
SYS_UPDATE_RC=OFF

REGEX_NUM='^[0-9]+$'
REGEX_PORT='^[1-9][0-9]+$'

PLATFORM=
FAKE_INIT_D=

MPLC_SYSTEMD=OFF
START_LOGFILE=/tmp/mplc_start.log
SYSTEMD_PATH=/etc/systemd/system/mplc4.service

EXTRA_CREATE_NGINX_CFG=

OS_NAME=Linux
# Read predefined configs
if [ -e "cfg" ]; then
	. ./cfg
fi

#--- Base functions -----------------------------

get_mplc_init() {
	echo $MPLC_INIT
}

restart_mplc() {
	$(get_mplc_init) restart
}

mplc_rm() {
	for file in "$@"; do
		[ -e "$file" ] || continue
		rm -R "$file" # if remove "true" script exit after "done"
	done
}
mplc_loop() {
	local loop_i=$1
	local loop_for=$2
	if [ "$OS_NAME" == QNX ]; then
		echo "integer $loop_i=0; while ((i<\$$loop_for)); do i=i+1;"
	else
		echo "for $loop_i in \`seq 1 \$$loop_for\`; do "
	fi
}
mplc_get_dir() {
	echo $(mkdir -p $1; cd $1; pwd)
}

mplc_which() {
	local res=
	if [ -n "$(which which 2>/dev/null)" ]; then
		res=$(which $1 2>/dev/null)
	else
		for dir in $(echo $PATH | sed 's/:/ /g'); do
			res=$(find $dir -maxdepth 1 -name "$1" -type f)
			[ -n "$res" ] && break || true
		done
	fi
	echo $res
}

mplc_check() {
	if [ -n "$(mplc_which $1)" ]; then
		echo "ON"
	else
		echo "OFF"
	fi
}

#if matched return 0 else 1
#exemple --
#  reg='^a[0-9]+$' : grep regex
#  val="as2232"
#  [ $(mplc_regex $val $reg) == 0 ] && echo OK
mplc_regex() {
	local val=$1
	local reg=$2
	res=$(echo "$val" | grep -E "$reg")
	[ -n "$res" ] && echo 0 || echo 1
}

mplc_unzip() {
	local SRC_ARCHIVE=$1
	local DST_PATH=$2
	local TAR_GZIP=ON
	[ "$(tar --help 2>&1 | grep 'gzip')" == "" ] && TAR_GZIP="OFF"
	if [ "$PLATFORM" != PLC210 ]&& [ "$PLATFORM" != PLC210RK ]; then
		local WITHOUT_PERMISSION='--no-same-owner --no-same-permissions'
	fi
	if [ $TAR_GZIP == "ON" ]; then
		tar xf $SRC_ARCHIVE -C $DST_PATH $WITHOUT_PERMISSION
	else
		cp $SRC_ARCHIVE tmp.tar.gz
		gzip -d tmp.tar.gz
		tar xf tmp.tar -C $DST_PATH $WITHOUT_PERMISSION
		rm tmp.tar
	fi

}

import_mplc_function() {
	cat <<EOL
mplc_kill(){
	kill -INT \$@ 2>/dev/null
}
mplc_regex(){
	local val=\$1
	local reg=\$2
	local res=\$(echo "\$val" | grep -E "\$reg")
	# echo "\$val -> \$reg : \$res : \$([ -n "\$res" ] && echo 0 || echo 1)"
	[ -n "\$res" ] && echo 0 || echo 1
}
mplc_rm(){
	for file in "\$@"; do
		[ -e "\$file" ] && rm -R "\$file" || true
	done
}
mplc_nkill(){
	local pid=\$($SYS_PIDOF \$1 2>/dev/null)
	[ -z "\$pid" ] && return 0
	mplc_kill \$pid
}

mplc_fkill(){
	if [ -e "\$1" ]; then
		mplc_kill \$( cat "\$1" )
		local is_ok=\$?
		sleep 1
		if [ \$is_ok != 0 ]; then 
			mplc_rm "\$1"
		fi
	fi
}
EOL
}

#--- Get platform type --------------------------

if [ $(mplc_regex "$(uname -n)" "plc110") == 0 ]; then
	PLATFORM=PLC110
fi

#--- Preinstall section -------------------------

if [ $(mplc_check sysctl) == "ON" ]; then
	MPLC_DUMP=ON
fi

#--- Read user options --------------------------
opt=
for option; do
	opt="$opt `echo $option | sed -e \"s/\(--[^=]*=\)\(.* .*\)/\1'\2'/\"`"

	case "$option" in
	-*=*) value=`echo "$option" | sed -e 's/[-_a-zA-Z0-9]*=//'` ;;
	*) value="" ;;
	esac

	case "$option" in
		--prefix=*)                         MPLC_PATH="$(mplc_get_dir $value)"   ;;
		--kill-codesys)                     CODESYS_KILL="ON"                    ;;
		--with-https)                       NGINX_HTTPS=ON                       ;;
		--without-http)                     NGINX_HTTP=OFF
		                                    NGINX_HTTPS=ON                       ;;
		--http-port=*)                      NGINX_HTTP_PORT="$value"             ;;
		--without-nginx)                    NGINX_UPDATE="OFF"                   ;;
		--i386-dep)                         SYS_I386_DEP="ON"                    ;;
		--nowdt)                            MPLC_WDT="OFF"                       ;;
		--config-only)                      MPLC_CFG_ONLY="ON"                   ;;
		--start-delay=*)                    MPLC_AUTOSTART_DELAY="$value"        ;;
		--platform=*)                       PLATFORM="$value"                    ;;
		--enable-log)                       MPLC_LOGS="/var/log/mplc4"      ;;
		--enable-log=*)                     MPLC_LOGS="$value"                   ;;
		--upload-files=*)                   MPLC_UPLOAD_PATH="$value"             
                                            MPLC_USE_UPLOAD_PATH=ON              ;;
		--disable-dump)                     MPLC_DUMP=OFF                        ;;
		--nginx-logdir=*)                   NGINX_LOGS="$value"
		                                    NGINX_PID_FILE=$NGINX_LOGS/nginx.pid ;;
		--nginx-disable-gzip)               NGINX_GZIP=OFF                       ;;
		--nginx-user-dir=*)                 NGINX_USER_DIR="$value"        
                                            NGINX_USER_DIR_ENABLED="ON"          ;;
		--create-nginx-cfg=*)               NGINX_CONFIG="$value"
		                                    EXTRA_CREATE_NGINX_CFG="ON"          ;;
		--exemplars=*)                      MPLC_EXEMPLARS="$value"              ;;
		--netkey)                           MPLC_NETKEY=ON                       ;;
		--with-rtsp)                        RTSP_SERVICE=ON                      ;;
		--without-monitor)                  NEW_SERVICE=OFF                      ;;
		--use-systemd)                      MPLC_SYSTEMD=ON                      ;;
		--with-hsts)                        NGINX_WITH_HSTS=ON                   ;;
		--set-password=*)                   SET_PASSWORD="$value"                ;;  
		-v)
			echo "Installer version $VERSION"
			exit 1                                                                 ;;
		*)
			cat <<EOL
$0 availible options:
	--prefix=<path>            The path to the mplc4 installation (default: $MPLC_PATH)
	--enable-log[=<dir>]       Enable log saving for each mplc start in new file in specified directory. Default directory: /var/log/mplc4
	--kill-codesys             Disable runtime codesys
	--without-http             Disable HTTP protocol
	--with-https               Enable HTTPS protocol
	--http-port=<port>         Set another HTTP port (default: $NGINX_HTTP_PORT)
	--without-nginx	           Disable Nginx installation. Can be run without nginx.tar.gz. Works only if --without-monitor
	--i386-dep                 Installing i386 dependency. Required for x64 arhitectures. WARNING: Internet connection required.
	--nowdt                    Disable using watchdog
	--config-only              Update only configs. Can be run without mplc.tar.gz and nginx.tar.gz
	--start-delay=<seconds>    MPLC autostart delay after reboot controller. (default: 0)
	--platform=<NAME>          Set specific platform, availible values (PLC110, REGUL)
	--disable-dump             Disable mplc4 create dump
	--nginx-logdir=<dir>       Set dir for nginx logs and pid file. Works only if --without-monitor
	--create-nginx-cfg=<path>  Generate nginx config file without install
	--exemplars=<N>            Count autostart exemplars
	--nginx-disable-gzip       disable gzip module for static(need on Android)
	--nginx-user-dir           Directory with user defined nginx configs
	--netkey                   Use network license key
	--without-monitor          Use old service without new monitor
	--upload-files=<path>	   Sets directory for upload files sent throught Upload api.
	--with-rtsp                Start the rtsp web camera service
	--use-systemd              Creates native systemd launch script instead of init.d
	--with-hsts 			   Enable HSTS in nginx
	--set-password             Set password for mplc and mplc_monitor
EOL
			exit 1                                                               ;;
	esac
done

#--- Update default options ---------------------

if [ $(mplc_regex $MPLC_AUTOSTART_DELAY $REGEX_NUM) != 0 ]; then
	echo "Error start-delay: '$MPLC_AUTOSTART_DELAY' is bad number of seconds." >&2
	exit 1
fi

if [ $(mplc_regex $MPLC_EXEMPLARS $REGEX_NUM) != 0 ]; then
	echo "Error exemplars count number: '$MPLC_EXEMPLARS'." >&2
	exit 1
fi

if [ $(mplc_regex $NGINX_HTTP_PORT $REGEX_PORT) != 0 ] ||
	[ $(($NGINX_HTTP_PORT > 65535)) == 1 ]; then
	echo "Error http-port: '$NGINX_HTTP_PORT' is bad number port." >&2
	exit 1
fi

if [ "$EXTRA_CREATE_NGINX_CFG" != "ON" ]; then
	MPLC_START_SCRIPT=$MPLC_PATH/$MPLC_START_SCRIPT
	MPLC_UNINSTALL_SCRIPT=$MPLC_PATH/$MPLC_UNINSTALL_SCRIPT
	NGINX_PATH=$MPLC_PATH/nginx
	NGINX_CONFIG=$NGINX_PATH/$NGINX_CONFIG
fi

if [[ -f $DOTNET_TAR ]]; then
	DOTNET_DIR=$MPLC_PATH/dotnet
fi
if [[ -f $NETCORE_PLUGINS_TAR ]]; then
	NETCORE_PLUGINS_DIR=$MPLC_PATH/netcore
fi
if [[ -f $ADMIN_INTERFACE_TAR ]]; then
	ADMIN_INTERFACE_DIR=$MPLC_PATH/admin
fi
if [[ -f $RTSP_TAR ]]; then
	RTSP_DIR=$MPLC_PATH/rtsp
fi

SYS_UPDATE_RC=$(mplc_check update-rc.d)

if [ $(mplc_check bash) == "ON" ]; then
	SYS_SHELL=bash
fi

if [ "$PLATFORM" == PLC110 ]; then
	FAKE_INIT_D=/etc/rc.local
	MPLC_INIT="$MPLC_PATH/init_mplc4.sh"
elif [ "$PLATFORM" == REGUL ]; then
	FAKE_INIT_D=/etc/init/system.main
	OS_NAME=QNX
elif [ "$PLATFORM" == QNX650_X86 ]; then
	FAKE_INIT_D=/etc/rc.d/rc.local
	OS_NAME=QNX
elif [ "$PLATFORM" == TREI ]; then
	FAKE_INIT_D=/fs/etfs/etc/rc.d/rc.local
	OS_NAME=QNX
elif [ "$PLATFORM" == SEREBRUM ]; then
	MPLC_INIT="/etc/init.d/S${MPLC_RC_PRIORITY}mplc4"
fi

if [ "$OS_NAME" == QNX ]; then
	SYS_PIDOF="slay -p"
	MPLC_INIT="$MPLC_PATH/init_mplc4.sh"
fi

if [ "$NEW_SERVICE" == "ON" ]; then
	if [ "$NGINX_UPDATE" == "OFF" ]; then
		echo "--without-nginx option does not work with the new service" >&2
		exit 1
	fi
	if [ "$NGINX_LOGS" != "/var/log/nginx" ]; then
		echo "--nginx-logdir option does not work with the new service" >&2
		exit 1
	fi
fi

echo "NGINX_HTTPS=$NGINX_HTTPS"
echo "NGINX_HTTP=$NGINX_HTTP"
echo "MPLC_LOGS=$MPLC_LOGS"

#--- Platform dependence functions --------------

clear_old_installer() {
	if [ "$SYS_UPDATE_RC" == "ON" ]; then
		update-rc.d -f mplc4s remove >/dev/null 2>&1
	fi
	mplc_rm \
		/etc/init/mplc4d.sh \
		/etc/init.d/mplc4s \
		/etc/init.d/S99mplc \
		$MPLC_PATH/lighttpd \
		$MPLC_PATH/mplcstart.sh
}

create_user() {
	adduser -S $1 >/dev/null 2>&1 || true
}

add_autorun() {
local INIT_SCRIPT=$1
	local FILE_NAME=$(basename $INIT_SCRIPT)
	local NN=$MPLC_RC_PRIORITY
	#$DEBUG && echo "start add_autorun "
	#$DEBUG && echo "INIT_SCRIPT=$1"
	if [ -n "$FAKE_INIT_D" ]; then
		#doesn't have normal init.d and so we need parse this shit
		cp $FAKE_INIT_D ./$(basename $FAKE_INIT_D).bak
		sed -ie "/^cd.*mplc/d; /#run mplc/d; /$FILE_NAME/d; s!.*mplcstart.sh.*!$INIT_SCRIPT start!g" $FAKE_INIT_D
		if [ -z "$(sed -n "/$FILE_NAME/p" $FAKE_INIT_D)" ]; then
			cat >>$FAKE_INIT_D <<EOL
#run mplc 
$INIT_SCRIPT start
EOL
		fi
		mplc_rm ./$(basename $FAKE_INIT_D).bak
	elif [ "$SYS_UPDATE_RC" == ON ]; then
		update-rc.d "$(basename $INIT_SCRIPT)" defaults $NN
	elif [ "$PLATFORM" == PLC210 ] || [ "$PLATFORM" == PLC210RK ]; then
		local run_name=S${NN}_$FILE_NAME
		ln -sf $INIT_SCRIPT /etc/rc.d/$run_name
	else
		local run_name=S${NN}_$FILE_NAME
		local stop_name=K01_$FILE_NAME
		for num in 2 3 4 5; do
			mkdir -p /etc/rc${num}.d
			ln -sf $INIT_SCRIPT /etc/rc${num}.d/$run_name
		done
		for num in 0 1 6; do
			mkdir -p /etc/rc${num}.d
			ln -sf $INIT_SCRIPT /etc/rc${num}.d/$stop_name
		done
	fi
}

#Add check user name in script if MPLC_USER != root
add_check_user() {
	if [ "$MPLC_USER" != "root" ]; then
		cat <<EOL
if [ "\$(whoami)" != "$MPLC_USER" ]; then
	echo Cant run from \$(whoami).\n \
		\$($(get_mplc_init) help)
	exit 1
fi
EOL
	fi
}

get_sh_cmd() {
	if [ "$MPLC_USER" != "root" ]; then
		echo "su - $MPLC_USER -s /bin/$SYS_SHELL -c "
	else
		echo "/bin/$SYS_SHELL -c "
	fi
}

#--- MPLC Scripts -------------------------------

create_mplc_scripts() {
	create_mplcstart_script $MPLC_START_SCRIPT \
		$MPLC_BASE_PORT \
		$MPLC_PATH \
		$NGINX_PATH \
		$NGINX_CONFIG \
		$NGINX_LOGS

	create_nginx_script $MPLC_PATH \
		$NGINX_PATH \
		$NGINX_CONFIG \
		$NGINX_LOGS
	if [ "$MPLC_SYSTEMD" == "ON" ]; then
		create_systemd_script $SYSTEMD_PATH \
		  $MPLC_PATH \
		  $MPLC_START_SCRIPT		
	else
		create_initd_script $MPLC_INIT \
			$MPLC_PATH \
			$MPLC_START_SCRIPT

		add_autorun $MPLC_INIT
	fi

	if [ "$MPLC_SYSTEMD" == "ON" ]; then
		create_uninstall_systemd_script $MPLC_UNINSTALL_SCRIPT
	else 
		create_uninstall_script $MPLC_UNINSTALL_SCRIPT
	fi
}

create_systemd_script() {
	local SCRIPT_PATH=$1
	local MPLC_DIR=$2
	local START_SCRIPT=$3
	cat >$SCRIPT_PATH <<EOT
[Unit]
Description="Mplc4 service"
After=network.target

[Service]
Type=forking
Restart=always
WorkingDirectory=$MPLC_DIR
ExecStart=$START_SCRIPT
KillMode=process

[Install]
WantedBy=multi-user.target
EOT
}

create_initd_script() {
	local SCRIPT_PATH=$1
	local MPLC_DIR=$2
	local START_SCRIPT=$3
	local EXEC_CMD="$(get_sh_cmd)"
	local KILL_CODESYS=
	if [ "$CODESYS_KILL" == "ON" ] && [ -n "$CODESYS_NAME" ]; then
		KILL_CODESYS="mplc_nkill $CODESYS_NAME"
	fi
	local DELAY=
	if [ "$MPLC_AUTOSTART_DELAY" != "0" ]; then
		DELAY="[ \$(mplc_regex \$0 '^/etc/rc[0-6].d/') != 0 ] || sleep $MPLC_AUTOSTART_DELAY;"
	fi
	if [ "$PLATFORM" == SEREBRUM ]; then
		OTHER="mount -o remount /"
	fi
	if [ "$PLATFORM" == PLC210 ] || [ "$PLATFORM" == PLC210RK ]; then
		cat >$SCRIPT_PATH <<EOT
#!/bin/sh /etc/rc.common
START=99
STOP=10
#USE_PROCD=1
QUIET=""
MPLC_RUN_OPTS="\$2"
start(){
	__start \$1
    return 0
}
stop(){
	__stop
    return 0
}
restart() {
    __stop
	__start \$1
    return 0
}
EOT
	else
		cat >$SCRIPT_PATH <<EOT
#!/bin/$SYS_SHELL
### BEGIN INIT INFO
# Provides:          mplc4
# Required-Start:    
# Required-Stop:     
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start the MasterSCADA 4D RT server.
# Description:       Start the MasterSCADA 4D RT server.
### END INIT INFO
RUN_OPTS="\$3"
EOT
	fi
	cat >>$SCRIPT_PATH <<EOT
$(import_mplc_function)
$OTHER
filter_warnings=
skips='/^nginx: \[alert\]/d'

do_start() {
	$DELAY
	$KILL_CODESYS
	cd "$MPLC_DIR"
	if [ "$NEW_SERVICE" == "OFF" ]; then
		$EXEC_CMD "$START_SCRIPT \$1 '\$RUN_OPTS'" 1>> $START_LOGFILE 2>&1
	else
		$EXEC_CMD "$START_SCRIPT \$1 '\$RUN_OPTS'"
	fi
}
do_stop() {
	if [ "$NEW_SERVICE" == "OFF" ]; then
		mplc_fkill "$NGINX_PID_FILE" 	1>>$START_LOGFILE 2>&1
		mplc_nkill mplc_service 		1>>$START_LOGFILE 2>&1
		mplc_nkill mplc					1>>$START_LOGFILE 2>&1
		pkill -f 'dotnet .*RTSPtoWebRTC.*' 1>>$START_LOGFILE 2>&1
		while [ -n "\$($SYS_PIDOF mplc)" ]; do sleep 1; done;
	else
		mplc_nkill mplc_daemon
		while [ -n "\$($SYS_PIDOF mplc_daemon)" ]; do sleep 1; done;
	fi
	return 0
}

__start() {
	
	local OUT=
	if [ "\$1" == "local" ]; then
		cd "$MPLC_DIR"
		$EXEC_CMD "$START_SCRIPT \$1 '\$RUN_OPTS'"
		#\$(do_start \$1 )
	else
		echo -n "Starting MasterSCADA 4D RT..."
		do_start \$1 && echo "   OK" || echo "   BAD"
		if [ "$NEW_SERVICE" == "OFF" ]; then
			cat $START_LOGFILE | sed -e "\$skips"
			mplc_rm $START_LOGFILE
		fi
	fi
	
}

__stop() {
	echo -n "Stopping MasterSCADA 4D RT..."
	local OUT=
	\$(do_stop) &&	echo "   OK" || echo "   BAD"
	if [ "$NEW_SERVICE" == "OFF" ]; then
		cat $START_LOGFILE | sed -e "\$skips"
		mplc_rm $START_LOGFILE
	fi
}
EOT
	if [ "$PLATFORM" != PLC210 ]  && [ "$PLATFORM" != PLC210RK ]; then
		cat >>$SCRIPT_PATH <<EOT
case "\$1" in
  start)
    __start \$2
	;;
  stop)
    __stop
	;;
  restart|reload)
	__stop
	__start \$2
	;;
  *)
	echo \$"Usage: \$0 {start|stop|restart}"
	exit 1
esac

exit $?
EOT
	fi
	chmod 755 $SCRIPT_PATH
}

create_mplcstart_script() {
	local SCRIPT_PATH=$1
	local BASE_PORT=$2
	local MPLC_PATH=$3
	local NGINX_PATH=$4
	local NGINX_CONFIG=$5
	local NGNIX_LOGS_DIR=$6
	local MPLC_OPTS=

	local MPLC_CORE_CONF="$MPLC_PATH/mplc_core.conf"

	if [ "$MPLC_WDT" != ON ]; then
		MPLC_OPTS="$MPLC_OPTS /nowdt"
	fi
	if [ "$MPLC_NETKEY" == ON ]; then
		MPLC_OPTS="$MPLC_OPTS /netkey"
	fi
	if [ "$MPLC_USE_UPLOAD_PATH" == ON ]; then
		MPLC_OPTS="$MPLC_OPTS /upload-files:$MPLC_UPLOAD_PATH"
	fi
	if [ "$MPLC_DUMP" != ON ]; then
		cat >$MPLC_CORE_CONF <<EOT
enable_dump=0
EOT
	fi
	if [ "$SYS_I386_DEP" == "ON" ]; then
		local OTHER_PATHS="/usr/lib/i386-linux-gnu"
	fi
	local CHECK_USER="$(add_check_user)"
	cat >$SCRIPT_PATH <<EOT
#!/bin/$SYS_SHELL
export LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:$MPLC_PATH:$NGINX_PATH/lib:$OTHER_PATHS
export DOTNET_EnableDiagnostics=0
CURDATE=\$(date +"%Y_%m_%d")
COUNT=$MPLC_EXEMPLARS
START_OPTS="\$2"
INST_OPTS="$MPLC_OPTS"
LOGS_DIR="$MPLC_LOGS"

start(){
	if [ "$NEW_SERVICE" == "OFF" ]; then
		local PORT=\$1
		local PARAMS=\$2
		echo "Start mplc4 on \$PORT" >> $START_LOGFILE
		local LOG_OPT=""
		if [ "\$LOGS_DIR" != "OFF" ]; then
			mkdir -p \$LOGS_DIR
		LOG_OPT="/log:\$LOGS_DIR/mplc_\$CURDATE.txt"
		fi
		$MPLC_PATH/mplc_service \$PORT $MPLC_PATH/mplc new \$INST_OPTS \$LOG_OPT \$START_OPTS \$PARAMS 1>> $START_LOGFILE 2>&1
	else
		$MPLC_PATH/mplc_daemon
	fi
}

start_examplar(){
	local BASE_PORT=\$1
	local EXEMPLAR=\$2
	local PORT=\$((\$BASE_PORT + \$EXEMPLAR))
	#Need for INST_OPTS
	mkdir -p log/\$EXEMPLAR 2>/dev/null
	echo "Start mplc4 examplar \$EXEMPLAR on \$PORT" >> $START_LOGFILE
	local LOG_OPT=""
	if [ "\$LOGS_DIR" != "OFF" ]; then
		mkdir -p \$LOGS_DIR
		LOG_OPT="/log:\$LOGS_DIR/\$EXEMPLAR/mplc_\$CURDATE.txt"
	fi
	$MPLC_PATH/mplc_service \$PORT $MPLC_PATH/mplc new \$INST_OPTS \$LOG_OPT \$START_OPTS "/ea:\$EXEMPLAR" 1>> $START_LOGFILE 2>&1
}

run_with_check(){
	local NAME=\$1
	local CMD=\$2
	#\$3 - path to pidfile
	local TMP=\$( [ "\$3" ] && [ -e "\$3" ] && cat "\$3" )
	local PIDS=\$($SYS_PIDOF \$NAME 2>/dev/null) || true
	if [ "\$3" ] ; then
		if [ -z "\$PIDS" ] || [ \$(mplc_regex "\$PIDS" "\$TMP") != 0 ]; then
			mplc_rm \$3
			PIDS=
		else
			PIDS=\$TMP
		fi
	fi
	if [ -n "\$PIDS" ]; then
		if [ -z "\$AS_LOCAL" ]; then
			echo "\$NAME is already running. PID: \$PIDS"
		fi
	else
		\$(\$CMD)
	fi
}

run_nginx(){
	mkdir -p $NGNIX_LOGS_DIR/temp
	mkdir -p $NGNIX_LOGS_DIR/log
	$NGINX_PATH/sbin/nginx -p \$PWD -c $NGINX_CONFIG
}

run_rtsp(){
	$DOTNET_DIR/dotnet $RTSP_DIR/RTSPtoWebRTC.WebAPI.dll </dev/null >/dev/null 2>&1 & disown
}

run_as_local(){
	if [ "$NEW_SERVICE" == "ON" ]; then
		$MPLC_PATH/mplc /new-service \$INST_OPTS \$START_OPTS
	else
		$MPLC_PATH/mplc 1 2 \$INST_OPTS \$START_OPTS
	fi
}

run_as_service(){
	$CHECK_USER
	if [ "$NEW_SERVICE" == "ON" ]; then
		start		
	else
		start $BASE_PORT
		$(mplc_loop i COUNT)
			start_examplar $BASE_PORT \$i
		done
	fi
}

# --- Script execution section ---
if [ -e $MPLC_PATH/prerun.sh ]; then 
	. $MPLC_PATH/prerun.sh 1>> $START_LOGFILE 2>&1
fi

mkdir -p log 2>/dev/null
echo "Started in \$(date +"%Y_%m_%d-%H:%M:%S")" >> $START_LOGFILE

$(import_mplc_function)

$USE_DUMP

$SYS_TRAP

if [ "\$1" == "local" ]; then
	AS_LOCAL=TRUE
fi
if [ \$(mplc_regex "\$1" "$REGEX_NUM") == 0 ] ; then
	COUNT=\$1
fi

if [ -z "\$AS_LOCAL" ] && [ \$(mplc_regex "\$1" "$REGEX_NUM") != 0 ] ; then
	START_OPTS="\$START_OPTS \$1"
fi

if [ "$NEW_SERVICE" == "OFF" ]; then
	if [ -e "$NGINX_PATH/sbin/nginx" ]; then
		run_with_check nginx "run_nginx" $NGINX_PID_FILE
	fi
fi

if [ "$NEW_SERVICE" == "OFF" ]; then
	if [ "$RTSP_SERVICE" == "ON" ] && [ -e "$RTSP_DIR/RTSPtoWebRTC.WebAPI.dll" ] && [ -e "$DOTNET_DIR/dotnet" ]; then
		run_with_check rtsp "run_rtsp"
	fi
	if [ -n "\$AS_LOCAL" ]; then
		run_as_local
	else
		run_with_check mplc_service "run_as_service \$1"
	fi
else
if [ -n "\$AS_LOCAL" ]; then
		run_as_local
	else
		run_with_check mplc_daemon "run_as_service \$1"
	fi
fi

EOT
	chmod 755 $SCRIPT_PATH
}

create_nginx_script() {
	local SCRIPT_PATH=$1/nginx.sh
	local NGINX_PATH=$2
	local NGINX_CONFIG=$3
	local NGNIX_LOGS_DIR=$4
	
cat >$SCRIPT_PATH <<EOT
#!/bin/$SYS_SHELL

$(import_mplc_function)

run_with_check(){
	local NAME=\$1
	local CMD=\$2
	#\$3 - path to pidfile
	local TMP=\$( [ "\$3" ] && [ -e "\$3" ] && cat "\$3" )
	local PIDS=\$($SYS_PIDOF \$NAME 2>/dev/null) || true
	if [ "\$3" ] ; then
		if [ -z "\$PIDS" ] || [ \$(mplc_regex "\$PIDS" "\$TMP") != 0 ]; then
			mplc_rm \$3
			PIDS=
		else
			PIDS=\$TMP
		fi
	fi
	if [ -n "\$PIDS" ]; then
		echo "\$NAME is already running. PID: \$PIDS"
	else
		\$(\$CMD)
	fi
}
run_nginx(){
	mkdir -p $NGNIX_LOGS_DIR/temp
    mkdir -p $NGNIX_LOGS_DIR/log
	$NGINX_PATH/sbin/nginx -p \$PWD -c $NGINX_CONFIG </dev/null >/dev/null 2>&1 & disown
}
start(){
	if [ -e "$NGINX_PATH/sbin/nginx" ]; then
	    run_with_check nginx "run_nginx" $NGINX_PID_FILE
	fi
}
stop(){
	mplc_fkill "$NGINX_PID_FILE" 	1>> $START_LOGFILE 2>&1
}

case "\$1" in
  start)
    start
	;;
  stop)
    stop
	;;
  restart|reload)
	stop
	start
	;;
  *)
	echo \$"Usage: \$0 {start|stop|restart}"
	exit 1
esac

EOT
	chmod 755 $SCRIPT_PATH
}

#--- Uninstaller block --------------------------
get_instaled_files() {
	cat <<EOL
$MPLC_PATH
$NGINX_PATH
EOL
}

remove_autorun() {
	local NN=$MPLC_RC_PRIORITY
	local FILE_NAME=$(basename $MPLC_INIT)
	local LINK_RUN=S${NN}_$(basename $MPLC_INIT)
	local LINK_STOP=K01_$(basename $MPLC_INIT)
	if [ -n "$FAKE_INIT_D" ]; then
		cat <<EOL
sed  -ie "/#run mplc/d; /$FILE_NAME/d" $FAKE_INIT_D
EOL
	elif [ "$SYS_UPDATE_RC" == "ON" ]; then
		cat <<EOL
update-rc.d -f $FILE_NAME remove
mplc_rm $MPLC_INIT
EOL
	else
		cat <<EOL
mplc_rm $MPLC_INIT
for num in 2 3 4 5; do
	mplc_rm /etc/rc\${num}.d/$LINK_RUN
done
for num in 0 1 6; do
	mplc_rm /etc/rc\${num}.d/$LINK_STOP
done
EOL
	fi
}

create_uninstall_script() {
	local SCRIPT_PATH=$1
	local FILES="$(echo $(get_instaled_files))"
	cat >$SCRIPT_PATH <<EOT
#!/bin/$SYS_SHELL
$(import_mplc_function)

$(get_mplc_init) stop

if [[ -f "$MPLC_PATH/core_dump_helper" ]]; then
	echo "Disable core dump helper"
	$MPLC_PATH/core_dump_helper -u
fi

echo "Remove from autostart"
$(remove_autorun)

echo "Remove installed files"
mplc_rm $FILES

EOT
	chmod 755 $SCRIPT_PATH
}

create_uninstall_systemd_script() {
	local SCRIPT_PATH=$1
	local FILES="$(echo $(get_instaled_files))"
	cat >$SCRIPT_PATH <<EOT
#!/bin/$SYS_SHELL
$(import_mplc_function)

systemctl stop mplc4 
mplc_rm $SYSTEMD_PATH
systemctl daemon-reload
echo "Remove installed files"
mplc_rm $FILES
EOT
	chmod 755 $SCRIPT_PATH
}

#--- Nginx config -------------------------------
install_nginx_config() {
	local CONFIG_PATH=$1
	local LOG_DIR=$2
	local HTTP_PORT=$3
	local USER_OPT=
	if [ -n "$NGINX_USER" ]; then
		USER_OPT="user $NGINX_USER;"
	fi
	local CONFIG_DIR="$(mplc_get_dir $(dirname $CONFIG_PATH))"
	local LOCATION_OPTS=$CONFIG_DIR/tmp.nginx.location_opt
	local DAEMON=
	if [ "$NEW_SERVICE" == "ON" ]; then
		local DAEMON=daemon off;
	fi
	cat >$LOCATION_OPTS <<EOT
include fastcgi_params;
			add_header Access-Control-Allow-Origin * ;
			add_header X-Frame-Options ALLOWALL  ;
			if (\$request_method = 'OPTIONS') {
				 # Tell client that this pre - flight info is valid for 20 days
				add_header 'Access-Control-Allow-Credentials' 'true' always;
				add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
				add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With,Browser-name,Browser-version' always;
				add_header 'Access-Control-Max-Age' 1728000;
				add_header 'Content-Type' 'text/plain charset=UTF-8';
				add_header 'Content-Length' 0;
				return 204;
			}
EOT

	local LOCATIONS=$CONFIG_DIR/tmp.nginx.locations
    cat >$LOCATIONS <<EOT
        location ~ /(\d+)/Methods/(.*) {
            let \$fastcgi_backend fcgi_backend_ . \$1 ;
            fastcgi_pass  \$fastcgi_backend;
            fastcgi_keep_conn on;
            fastcgi_param  PATH_INFO /\$2;
            $(cat $LOCATION_OPTS)
        }
        location ~ /Methods/(.*) {
            fastcgi_pass fcgi_backend;
            fastcgi_keep_conn on;
            fastcgi_param  PATH_INFO /\$1;
            $(cat $LOCATION_OPTS)
        }
        location ~* ^.+\.(js|json|html|css|pdf|ttf)$ {
            add_header Cache-Control "no-cache, must-revalidate";
            add_header Access-Control-Allow-Origin * ;
            root \$root_dir;
        }
        location / {
            index index.html;
            add_header Access-Control-Allow-Origin * ;
            add_header Cache-Control max-age=60;
            root \$root_dir;
        }
        
        location /rtsptowebrtcapi {
            proxy_pass http://127.0.0.1:30520;
            proxy_http_version 1.1;
            proxy_set_header Upgrade \$http_upgrade;
            proxy_set_header Connection keep-alive;
            proxy_set_header Host \$host;
            proxy_cache_bypass \$http_upgrade;
            add_header Access-Control-Allow-Origin * ;
        }
EOT
	local SERVER_HTTPS=$CONFIG_DIR/tmp.nginx.server_https

	local USER_INCLUDE=
	if [ "$NGINX_USER_DIR_ENABLED" == "ON" ]; then
		local USER_INCLUDE="include $NGINX_USER_DIR;"
	fi

	if [ "$NGINX_HTTPS" == "ON" ]; then
		if [ "$NGINX_WITH_HSTS" == "ON" ]; then
			local HSTS="add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains; preload' always;"
		fi
		cat >$SERVER_HTTPS <<EOT
		$(echo $USER_INCLUDE)
server {
		set \$fastcgi_port_base 30750;
		set \$root_dir "htdocs";
		server_name $NGINX_SERVER_NAME;
		
		listen		${NGINX_HTTPS_PORT} ssl;
		ssl_certificate      server.crt;
		ssl_certificate_key  server.key;
		ssl_session_cache    shared:SSL:1m;
		ssl_session_timeout  5m;

		ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305';
		ssl_prefer_server_ciphers  on;
		ssl_protocols TLSv1.2 TLSv1.3;

		$HSTS
		$(cat $LOCATIONS)
	}
EOT
	fi
	local SERVER_HTTP=$CONFIG_DIR/tmp.nginx.server_http
	if [ "$NGINX_HTTP" == "ON" ]; then
		if [ "$NGINX_HTTPS" == "ON" ]; then
			# Формируем URL для редиректа: если порт стандартный (443), не указываем его
			local REDIRECT_URL
			if [ "$NGINX_HTTPS_PORT" == "443" ]; then
				REDIRECT_URL="https://\$host\$request_uri"
			else
				REDIRECT_URL="https://\$host:${NGINX_HTTPS_PORT}\$request_uri"
			fi
			cat >$SERVER_HTTP <<EOT
	server {
		listen $HTTP_PORT default_server;
		server_name $NGINX_SERVER_NAME;
		return 301 $REDIRECT_URL;
	}
EOT
		else
			cat >$SERVER_HTTP <<EOT
		$(echo $USER_INCLUDE)
server {
		listen $HTTP_PORT default_server;
		server_name $NGINX_SERVER_NAME;
		set \$fastcgi_port_base 30750;
		set \$root_dir "htdocs";
		
		$(cat $LOCATIONS)
	}
EOT
		fi
	fi
	local GZIP_OPTS=$CONFIG_DIR/tmp.nginx.gzip_on
	if [ "$NGINX_GZIP" == "ON" ]; then
		cat >$GZIP_OPTS <<EOT
gzip  on;
	gzip_min_length 1000;
	gzip_buffers     4 4k;
	gzip_types application/x-javascript text/css application/javascript text/javascript text/plain text/xml application/json application/vnd.ms-fontobject application/x-font-opentype application/x-font-truetype application/x-font-ttf application/xml font/eot font/opentype font/otf image/svg+xml image/svg image/vnd.microsoft.icon;
	gzip_disable "msie6";
	
EOT
	fi
    cat >$CONFIG_PATH <<EOT
worker_processes  1;
$DAEMON
$USER_OPT
#error_log  $LOG_DIR/error.log;
#error_log  $LOG_DIR/error.log  notice;
#error_log  $LOG_DIR/error.log  info;
error_log	$LOG_DIR/error.log  crit;
pid			$NGINX_PID_FILE;

pcre_jit off;

events {
    worker_connections  256;
}

http {
	## Hide Nginx version ##
	server_tokens   off;
	proxy_temp_path 		$LOG_DIR/temp/proxy;
	fastcgi_temp_path 		$LOG_DIR/temp/fastcgi;
	scgi_temp_path 			$LOG_DIR/temp/scgi;
	uwsgi_temp_path 		$LOG_DIR/temp/uwsgi;
	client_body_temp_path	$LOG_DIR/temp/client;
	
	access_log off;
	access_log  			$LOG_DIR/access.log;
	include					mime.types;
	default_type			application/octet-stream;

    sendfile        on;

    keepalive_timeout  65;
	tcp_nopush on;
	tcp_nodelay on;
	client_max_body_size 8m;
	
	$([ -e "$GZIP_OPTS" ] && cat "$GZIP_OPTS")
	
	upstream fcgi_backend { server 127.0.0.1:30750; keepalive 16; }
	upstream fcgi_backend_1 { server 127.0.0.1:30751; keepalive 16; }
	upstream fcgi_backend_2 { server 127.0.0.1:30752; keepalive 16; }
	upstream fcgi_backend_3 { server 127.0.0.1:30753; keepalive 16; }
	upstream fcgi_backend_4 { server 127.0.0.1:30754; keepalive 16; }
	upstream fcgi_backend_5 { server 127.0.0.1:30755; keepalive 16; }
	upstream fcgi_backend_6 { server 127.0.0.1:30756; keepalive 16; }
	upstream fcgi_backend_7 { server 127.0.0.1:30757; keepalive 16; }
	upstream fcgi_backend_8 { server 127.0.0.1:30758; keepalive 16; }
	upstream fcgi_backend_9 { server 127.0.0.1:30759; keepalive 16; }
	upstream fcgi_backend_10 { server 127.0.0.1:30760; keepalive 16; }
	upstream fcgi_backend_11 { server 127.0.0.1:30761; keepalive 16; }
	upstream fcgi_backend_12 { server 127.0.0.1:30762; keepalive 16; }
	upstream fcgi_backend_13 { server 127.0.0.1:30763; keepalive 16; }
	upstream fcgi_backend_14 { server 127.0.0.1:30764; keepalive 16; }
	upstream fcgi_backend_15 { server 127.0.0.1:30765; keepalive 16; }
	upstream fcgi_backend_16 { server 127.0.0.1:30766; keepalive 16; }
	upstream fcgi_backend_17 { server 127.0.0.1:30767; keepalive 16; }
	upstream fcgi_backend_18 { server 127.0.0.1:30768; keepalive 16; }
	upstream fcgi_backend_19 { server 127.0.0.1:30769; keepalive 16; }
	upstream fcgi_backend_20 { server 127.0.0.1:30770; keepalive 16; }
	upstream fcgi_backend_21 { server 127.0.0.1:30771; keepalive 16; }
	upstream fcgi_backend_22 { server 127.0.0.1:30772; keepalive 16; }
	upstream fcgi_backend_23 { server 127.0.0.1:30773; keepalive 16; }
	upstream fcgi_backend_24 { server 127.0.0.1:30774; keepalive 16; }
	upstream fcgi_backend_25 { server 127.0.0.1:30775; keepalive 16; }
	upstream fcgi_backend_26 { server 127.0.0.1:30776; keepalive 16; }
	upstream fcgi_backend_27 { server 127.0.0.1:30777; keepalive 16; }
	upstream fcgi_backend_28 { server 127.0.0.1:30778; keepalive 16; }
	upstream fcgi_backend_29 { server 127.0.0.1:30779; keepalive 16; }
	upstream fcgi_backend_30 { server 127.0.0.1:30780; keepalive 16; }
	upstream fcgi_backend_31 { server 127.0.0.1:30781; keepalive 16; }
	upstream fcgi_backend_32 { server 127.0.0.1:30782; keepalive 16; }
	upstream fcgi_backend_33 { server 127.0.0.1:30783; keepalive 16; }
	upstream fcgi_backend_34 { server 127.0.0.1:30784; keepalive 16; }
	upstream fcgi_backend_35 { server 127.0.0.1:30785; keepalive 16; }
	upstream fcgi_backend_36 { server 127.0.0.1:30786; keepalive 16; }
	upstream fcgi_backend_37 { server 127.0.0.1:30787; keepalive 16; }
	upstream fcgi_backend_38 { server 127.0.0.1:30788; keepalive 16; }
	upstream fcgi_backend_39 { server 127.0.0.1:30789; keepalive 16; }
	upstream fcgi_backend_40 { server 127.0.0.1:30790; keepalive 16; }
	upstream fcgi_backend_41 { server 127.0.0.1:30791; keepalive 16; }
	upstream fcgi_backend_42 { server 127.0.0.1:30792; keepalive 16; }
	upstream fcgi_backend_43 { server 127.0.0.1:30793; keepalive 16; }
	upstream fcgi_backend_44 { server 127.0.0.1:30794; keepalive 16; }
	upstream fcgi_backend_45 { server 127.0.0.1:30795; keepalive 16; }
	upstream fcgi_backend_46 { server 127.0.0.1:30796; keepalive 16; }
	upstream fcgi_backend_47 { server 127.0.0.1:30797; keepalive 16; }
	upstream fcgi_backend_48 { server 127.0.0.1:30798; keepalive 16; }
	upstream fcgi_backend_49 { server 127.0.0.1:30799; keepalive 16; }
	upstream fcgi_backend_50 { server 127.0.0.1:30800; keepalive 16; }
	upstream fcgi_backend_51 { server 127.0.0.1:30801; keepalive 16; }
	upstream fcgi_backend_52 { server 127.0.0.1:30802; keepalive 16; }
	upstream fcgi_backend_53 { server 127.0.0.1:30803; keepalive 16; }
	upstream fcgi_backend_54 { server 127.0.0.1:30804; keepalive 16; }
	upstream fcgi_backend_55 { server 127.0.0.1:30805; keepalive 16; }
	upstream fcgi_backend_56 { server 127.0.0.1:30806; keepalive 16; }
	upstream fcgi_backend_57 { server 127.0.0.1:30807; keepalive 16; }
	upstream fcgi_backend_58 { server 127.0.0.1:30808; keepalive 16; }
	upstream fcgi_backend_59 { server 127.0.0.1:30809; keepalive 16; }
	upstream fcgi_backend_60 { server 127.0.0.1:30810; keepalive 16; }
	upstream fcgi_backend_61 { server 127.0.0.1:30811; keepalive 16; }
	upstream fcgi_backend_62 { server 127.0.0.1:30812; keepalive 16; }
	upstream fcgi_backend_63 { server 127.0.0.1:30813; keepalive 16; }
	upstream fcgi_backend_64 { server 127.0.0.1:30814; keepalive 16; }
	upstream fcgi_backend_65 { server 127.0.0.1:30815; keepalive 16; }
	upstream fcgi_backend_66 { server 127.0.0.1:30816; keepalive 16; }
	upstream fcgi_backend_67 { server 127.0.0.1:30817; keepalive 16; }
	upstream fcgi_backend_68 { server 127.0.0.1:30818; keepalive 16; }
	upstream fcgi_backend_69 { server 127.0.0.1:30819; keepalive 16; }
	upstream fcgi_backend_70 { server 127.0.0.1:30820; keepalive 16; }
	upstream fcgi_backend_71 { server 127.0.0.1:30821; keepalive 16; }
	upstream fcgi_backend_72 { server 127.0.0.1:30822; keepalive 16; }
	upstream fcgi_backend_73 { server 127.0.0.1:30823; keepalive 16; }
	upstream fcgi_backend_74 { server 127.0.0.1:30824; keepalive 16; }
	upstream fcgi_backend_75 { server 127.0.0.1:30825; keepalive 16; }
	upstream fcgi_backend_76 { server 127.0.0.1:30826; keepalive 16; }
	upstream fcgi_backend_77 { server 127.0.0.1:30827; keepalive 16; }
	upstream fcgi_backend_78 { server 127.0.0.1:30828; keepalive 16; }
	upstream fcgi_backend_79 { server 127.0.0.1:30829; keepalive 16; }
	upstream fcgi_backend_80 { server 127.0.0.1:30830; keepalive 16; }
	upstream fcgi_backend_81 { server 127.0.0.1:30831; keepalive 16; }
	upstream fcgi_backend_82 { server 127.0.0.1:30832; keepalive 16; }
	upstream fcgi_backend_83 { server 127.0.0.1:30833; keepalive 16; }
	upstream fcgi_backend_84 { server 127.0.0.1:30834; keepalive 16; }
	upstream fcgi_backend_85 { server 127.0.0.1:30835; keepalive 16; }
	upstream fcgi_backend_86 { server 127.0.0.1:30836; keepalive 16; }
	upstream fcgi_backend_87 { server 127.0.0.1:30837; keepalive 16; }
	upstream fcgi_backend_88 { server 127.0.0.1:30838; keepalive 16; }
	upstream fcgi_backend_89 { server 127.0.0.1:30839; keepalive 16; }
	upstream fcgi_backend_90 { server 127.0.0.1:30840; keepalive 16; }
	upstream fcgi_backend_91 { server 127.0.0.1:30841; keepalive 16; }
	upstream fcgi_backend_92 { server 127.0.0.1:30842; keepalive 16; }
	upstream fcgi_backend_93 { server 127.0.0.1:30843; keepalive 16; }
	upstream fcgi_backend_94 { server 127.0.0.1:30844; keepalive 16; }
	upstream fcgi_backend_95 { server 127.0.0.1:30845; keepalive 16; }
	upstream fcgi_backend_96 { server 127.0.0.1:30846; keepalive 16; }
	upstream fcgi_backend_97 { server 127.0.0.1:30847; keepalive 16; }
	upstream fcgi_backend_98 { server 127.0.0.1:30848; keepalive 16; }
	upstream fcgi_backend_99 { server 127.0.0.1:30849; keepalive 16; }
	$([ -e "$SERVER_HTTP"  ] && cat "$SERVER_HTTP" )
	$([ -e "$SERVER_HTTPS" ] && cat "$SERVER_HTTPS")
}
EOT
	mplc_rm $SERVER_HTTP $SERVER_HTTPS $LOCATIONS $LOCATION_OPTS
}

create_monitor_config() {
DEFAULT_MONITOR_CONFIG='{
	"HostSettings": {
		"LaunchOptions":"%s",
		"UseNetKey":%s,
		"MplcInstanceCount":%d
	},
	"WebServerSettings": {
		"AllowHttpAccess":%s,
		"HttpWebServerPort":%d,
		"AllowHttpsAccess":%s,
		"UseHsts":%s,
		"NginxUserConf":"%s"
	},
	"RtspServerSettings": {
		"StartBehavior":%d
	},
	"LogSettings":{
		"WriteLogsToHost":%s,
		"HostLogDirectory":"%s",
		"WriteDumpsToHost":%s
	}
}'

LAUNCH_OPTIONS=
USE_NETKEY=false
MPLC_INSTANCE_COUNT=$((1 + $MPLC_EXEMPLARS))
ALLOW_HTTP_ACCESS=false
ALLOW_HTTPS_ACCESS=false
USE_HSTS=false
NGINX_USER_CONF=
RTSP_START_BEHAVIOUR=0
WRITE_LOGS_TO_HOST=false
HOST_LOG_DIRECTORY=/var/log/mplc4
WRITE_DUMPS_TO_HOST=false

if [ "$MPLC_WDT" != ON ]; then
	LAUNCH_OPTIONS="$LAUNCH_OPTIONS /nowdt"
fi
if [ "$MPLC_NETKEY" == ON ]; then
	USE_NETKEY=true
fi
if [ "$MPLC_USE_UPLOAD_PATH" == ON ]; then
	LAUNCH_OPTIONS="$LAUNCH_OPTIONS /upload-files:$MPLC_UPLOAD_PATH"
fi
if [ "$NGINX_HTTP" == ON ]; then
	ALLOW_HTTP_ACCESS=true
fi
if [ "$NGINX_WITH_HSTS" == "ON" ]; then
	USE_HSTS=true
fi
if [ "$NGINX_USER_DIR_ENABLED" == "ON" ]; then
	NGINX_USER_CONF=$NGINX_USER_DIR
fi
if [ "$NGINX_HTTPS" == ON ]; then
	ALLOW_HTTPS_ACCESS=true
fi
if [ "$RTSP_SERVICE" == ON ] && [ -e "$RTSP_DIR/RTSPtoWebRTC.WebAPI.dll" ] && [ -e "$DOTNET_DIR/dotnet" ]; then
	RTSP_START_BEHAVIOUR=1
fi
if [ "$MPLC_LOGS" != OFF ]; then
	WRITE_LOGS_TO_HOST=true
	HOST_LOG_DIRECTORY=$MPLC_LOGS
fi
if [ "$MPLC_DUMP" == ON ]; then
	WRITE_DUMPS_TO_HOST=true
fi

printf "$DEFAULT_MONITOR_CONFIG" "$LAUNCH_OPTIONS" "$USE_NETKEY" "$MPLC_INSTANCE_COUNT" "$ALLOW_HTTP_ACCESS" "$NGINX_HTTP_PORT" "$ALLOW_HTTPS_ACCESS" "$USE_HSTS" "$NGINX_USER_CONF" "$RTSP_START_BEHAVIOUR" "$WRITE_LOGS_TO_HOST" "$HOST_LOG_DIRECTORY" "$WRITE_DUMPS_TO_HOST" > $MPLC_PATH/default_monitor_config.json
rm -f $MPLC_PATH/monitor_config.json $MPLC_PATH/monitor_config_backup.json
}

set_mplc_password() {
	cd $MPLC_PATH
    ./mplc_secret "$SET_PASSWORD"
	cd -
}

#--- Help Info ----------------------------------

create_help_file() {
	local HELP_CMD
	if [ "$MPLC_SYSTEMD" == "ON" ]; then
		HELP_CMD="systemctl <start | stop | restart> mplc4"
	else
		HELP_CMD="$(get_mplc_init) <start | stop | restart>"
	fi
	cat >$1 <<EOL
Help for MasterSCADA 4D RT:
 $HELP_CMD
    start          Runing MasterSCADA 4D RT (mplc_service, mplc and nginx processes). If
                    something was started  before, a  warning  will be displayed
                    (not restarted).
    stop           Full stop MasterSCADA 4D RT (mplc_service, mplc and nginx  processes)
    restart        Always use if MasterSCADA 4D RT is already running and need to reload
EOL
}
#--- Instalation functions ----------------------

install_nginx_cfg() {
	[ "$NGINX_UPDATE" != "ON" ] && return 0
	#	echo -n "Install Nginx configs...     "
	mkdir -p $NGINX_PATH $NGINX_LOGS
	install_nginx_config $NGINX_CONFIG $NGINX_LOGS $NGINX_HTTP_PORT
	[ "$MPLC_USER" == "root" ] ||
		chown $MPLC_USER:$MPLC_GROUP -R $NGINX_PATH
	#	echo OK
}
install_nginx_bin() {
	[ "$NGINX_UPDATE" != "ON" ] && return 0
	echo -n "Install Nginx...       "
	mkdir -p $NGINX_PATH $NGINX_LOGS
	mplc_unzip $NGINX_TAR $NGINX_PATH 1>/dev/null
	[ "$MPLC_USER" == "root" ] ||
		chown $MPLC_USER:$MPLC_GROUP -R $NGINX_PATH
	echo OK
}
create_nginx_certificate() {
	[ "$NGINX_UPDATE" != "ON" ] && return 0
	echo -n "Create Nginx certificate...       "
	openssl ecparam -name prime256v1 -genkey -noout -out $NGINX_PATH/conf/server.key > /dev/null 2>&1
	openssl req -new -x509 -key $NGINX_PATH/conf/server.key -out $NGINX_PATH/conf/server.crt -days 90 -subj "/C=RU/ST=Moscow/L=Moscow/O=OrganozationName/OU=unitName/CN=server.local/emailAddress=email@server.local" > /dev/null 2>&1
	echo OK
}
install_mplc_cfg() {
	echo -n "Update configs...      "
	mkdir -p $MPLC_PATH
	[ "$MPLC_LOGS" == "OFF" ] || mkdir -p $MPLC_LOGS
	create_mplc_scripts
	[ "$MPLC_USER" == "root" ] ||
		chown $MPLC_USER:$MPLC_GROUP -R $MPLC_PATH
	echo OK
}
install_mplc_bin() {
	echo -n "Install mplc4...       "
	mplc_unzip $MPLC_TAR $MPLC_PATH 1>/dev/null
	[ "$MPLC_USER" == "root" ] ||
		chown $MPLC_USER:$MPLC_GROUP -R $MPLC_PATH
	echo OK
}
install_dotnet() {
	echo -n "Install dotnet runtime...       "
	mplc_rm  $DOTNET_DIR
	mplc_unzip $DOTNET_TAR $MPLC_PATH 1>/dev/null
	[ "$MPLC_USER" == "root" ] ||
		chown $MPLC_USER:$MPLC_GROUP -R $DOTNET_DIR
	echo OK
}
install_netcore() {	
	echo -n "Install netcore plugins...       "
	mplc_unzip $NETCORE_PLUGINS_TAR $MPLC_PATH 1>/dev/null
	[ "$MPLC_USER" == "root" ] ||
		chown $MPLC_USER:$MPLC_GROUP -R $NETCORE_PLUGINS_DIR
	echo OK

}
install_rtsp() {
	echo -n "Install rtsp web camera service...  "
	mkdir -p $RTSP_DIR
	mplc_unzip $RTSP_TAR $RTSP_DIR 1>/dev/null
	[ "$MPLC_USER" == "root" ] ||
		chown $MPLC_USER:$MPLC_GROUP -R $RTSP_DIR
	echo OK
}
install_admin() {
	echo -n "Install admin interface...  "
	mkdir -p $ADMIN_INTERFACE_DIR
	mplc_unzip $ADMIN_INTERFACE_TAR $ADMIN_INTERFACE_DIR 1>/dev/null
	[ "$MPLC_USER" == "root" ] ||
		chown $MPLC_USER:$MPLC_GROUP -R $ADMIN_INTERFACE_DIR
	echo OK
}

run_install() {
	echo "Install dir: $MPLC_PATH"
	local last_action=restart
	clear_old_installer
	if [ "$MPLC_USER" != "root" ]; then
		create_user $MPLC_USER
	fi
	install_mplc_cfg
	if [ "$MPLC_CFG_ONLY" == "OFF" ]; then
		if [ "$MPLC_SYSTEMD" == "OFF" ]; then
			$(get_mplc_init) stop
		else
			systemctl stop mplc4
		fi
		last_action=start
		install_mplc_bin
		install_nginx_bin
	fi
	if [[ -f $DOTNET_TAR ]]; then
		install_dotnet
	fi
	if [[ -f $NETCORE_PLUGINS_TAR ]]; then
		install_netcore
	fi
	if [[ -f $ADMIN_INTERFACE_TAR ]]; then
		install_admin
	fi
	if [[ -f $RTSP_TAR ]]; then
		install_rtsp
	elif [ "$RTSP_SERVICE" == ON ]; then
		echo -n "The Rtsp webcam service cannot be installed, rtsp.tar.gz missing. "
	fi
	install_nginx_cfg
	if [ $(mplc_check openssl) == "ON" ]; then
		create_nginx_certificate
	fi
	if [ "$NEW_SERVICE" == "ON" ]; then
		create_monitor_config
	fi
	if [ "$SET_PASSWORD" != "OFF" ]; then
		set_mplc_password
	fi

	if [[ -f "$MPLC_PATH/core_dump_helper" ]]; then
		echo "Install core dump helper"
		chmod u+x $MPLC_PATH/core_dump_helper
		#--- Install core dump helper ---------------
		$MPLC_PATH/core_dump_helper -i
	fi

	echo "Installed successfully"
	#--- Install Dependency -------------------------
	if [ "$SYS_I386_DEP" == "ON" ]; then
		echo "Installing i386 dependency .."
		source /etc/os-release 2>/dev/null || ID=unknown
		if [ "$ID" == "debian" ] || [ $(mplc_regex "$ID_LIKE" "debian") == 0 ]; then
			dpkg --add-architecture i386
			apt-get update
			if [ "$ID" == "astra" ]; then
				apt-get install -y ia32-libs
			else
				apt-get install -y libstdc++6:i386 libgcc1:i386 zlib1g:i386 libncurses5:i386
			fi
		elif [ $(mplc_regex "$ID_LIKE" "rhel") == 0 ]; then
			yum check-update -y
			yum install -y libstdc++.i686 libcrypt.i686
		elif [ "$ID" == "altlinux" ]; then
			# local pkg_src="/etc/apt/sources.list.d/temp.list"
			# echo "rpm [cert8] ftp://update.altsp.su/pub/distributions/ALTLinux c8/branch/x86_64 classic" >> $pkg_src
			# echo "rpm [cert8] ftp://update.altsp.su/pub/distributions/ALTLinux c8/branch/x86_64-i586 classic" >> $pkg_src
			apt-get update
			apt-get install -y i586-libstdc++6 libstdc++6 i586-libgcc1 || echo "[ERROR] Can't install x86 dependency"
			apt-get install -y i586-libcrypt || echo "[WARNING] pkg i586-libcrypt not found"
			#rm $pkg_src
		else
			echo "[WARNING] Unknown type OS: $ID:$VERSION_ID ($ID_LIKE)"
			echo "[WARNING] Can\'t install x86 dependency"
		fi
	fi
	#--- restart systemctl daemon in case us native systemd script
	if [ "$MPLC_SYSTEMD" == "ON" ]; then
		systemctl daemon-reload
	fi
	#--- Run MPLC -----------------------------------
	if [ $(mplc_check systemctl) == "ON" ]; then
		systemctl enable mplc4
		systemctl stop mplc4 2>/dev/null
		systemctl $last_action mplc4
	else
		$(get_mplc_init) $last_action
	fi
	echo ""
	create_help_file "$MPLC_PATH/help"
	cat $MPLC_PATH/help
}

if [ "$EXTRA_CREATE_NGINX_CFG" == ON ]; then
	install_nginx_config $NGINX_CONFIG $NGINX_LOGS $NGINX_HTTP_PORT
	exit 0
fi

#--- Check files --------------------------------
MISSING_FILES=
if [ "$MPLC_CFG_ONLY" != "ON" ]; then
	if [ "$NGINX_UPDATE" == "ON" ] && ! [ -e $NGINX_TAR ]; then
		MISSING_FILES="$NGINX_TAR"
	fi
	if ! [ -e $MPLC_TAR ]; then
		MISSING_FILES="$MISSING_FILES $MPLC_TAR"
	fi
fi
if [ -n "$MISSING_FILES" ]; then
	echo "Error: does not exist $MISSING_FILES"
	exit 1
fi

#--- Check root ---------------------------------
if [ "$OS_NAME" == Linux ] && [ "$(id -u)" != "0" ]; then
	echo "This script must be run as root" 1>&2
	exit 1
fi

#--- Run install ------------------------------

run_install
