#!/bin/bash

# include configuration
. "$(dirname "$0")/config.sh"


# include additional functions
. "$(dirname "$0")/fs-lib"

# verify the operation parameter
op="$2"
if [ -z "$op" ]; then
    echo "Missing params. Instance and operation are required" >&2
    exit 1
fi
shift
shift

####### Operations
case "$op" in
    start-services)
        #Start fcgi
        echo "Starting mervisfcgi"
        systemctl start mervisfcgi
        exit 0
        ;;
    stop-services)
        #Stop fcgi
        echo "Stoping mervisfcgi"
        systemctl stop mervisfcgi
        exit 0
        ;;
    restart-rt)
        #Restart runtime
        echo "Restarting mervisrt"
        systemctl restart mervisrt
        exit 0
        ;;
    restart-request)
        #Restart all services
        #unlock_fs
        echo "Restarting mervisrt and mervisconfigtool"
        systemctl restart mervisrt mervisconfigtool
        #lock_fs
        exit 0
        ;;
    reboot-request)
        #Restart machine
        echo "Rebooting the PLC"
        /sbin/reboot
        exit 0
        ;;
    start-rt)
        echo "Restarting mervisrt"
        systemctl restart mervisrt
        exit 0
        ;;
    sync)
        #called after changes in filesystem
        do_sync "$1"
        exit 0
        ;;
    service)
        #Configure services
        #continue later
        ;;
    *)
        echo "Unknown operation $op" >&2
        exit 1
        ;;
esac


############### Configure services
service="$1"
shift
if [ -z "$service" ]; then
    echo "Missing service parameter" >&2
    exit 1
fi

unset is_on port ssl password
while [ -n "$1" ]; do
    case "$1" in
        on)
            echo "Status: on"
            is_on=1
            ;;
        off)
            echo "Status: off"
            is_on=0
            ;;
        port)
            shift
            port="$1"
            echo "Port: $port"
            ;;
        ssl)
            shift
            ssl="$1"
            echo "SSL: $ssl"
            ;;
        password)
            shift
            password="$1"
            echo "Password: $password"
            ;;
        *)      
            echo "Unknown parameter for service $service : $1" >&2
            exit 1
        ;;
    esac
    shift
done

case "$service" in
    webserver)
        echo "Service: webserver"
        unlock_fs
        # do we have the "on/off" parameter?
        if [ -z "$is_on" ]; then 
            # no, we need to
            echo "Missing on/off parameter" >&2
            exit 1
        fi

        # yes we have on/off parameter
        if [ "$is_on" == "1" ]; then
            # web server should be turned on

            # check whether the port is also configured
            if [ "$port" == "" ]; then
                # it's not, set it as 80
                port=80
                echo "Port is not passed as parameter, defaulting to 80"
            fi

            # generate the configuration
            # check whether the template file exists
            if [ -r "$NGINX_TEMPLATE" ] && [ -s "$NGINX_TEMPLATE" ]; then
                # replace the port in the template with given one and save this confit to the sites-available
                if ! sed "s/___NGINX_PORT___/$port/" "$NGINX_TEMPLATE" > "$NGINX_AVAILABLE"; then
                    echo "Configuration creation failed"
                    exit 1
                fi
            else
                # uh-oh, the template is damaged
                echo "Nginx template doesn't exist, isn't readable or its size is 0:  $NGINX_TEMPLATE" >&2
                exit 1
            fi

            # check whether the nginx sites-enabled symlink exists
            if [ -h "$NGINX_ENABLED" ] && [ "$(readlink -f "$NGINX_ENABLED")" == "$NGINX_AVAILABLE" ]; then
                echo "Symlink from sites-enabled to sites-available already exists and is correct"
            else
                echo "The symlink doesn't exist or doesn't point to $NGINX_AVAILABLE, removing"
		if [ -f "$NGINX_ENABLED" ]; then
		    if rm -f "$NGINX_ENABLED"; then
		        echo "Unable to remove symlink" >&2
		       exit 1
		    fi
                else
                    echo "Recreating symlink"
                    if ! ln -s "$NGINX_AVAILABLE" "$NGINX_ENABLED"; then
                        echo "Recreation of symlink failed" >&2
                        exit 1
                    fi
                fi
            fi

            # check nginx configuration for errors
            echo "Checking nginx configuration"
            if ! nginx -t; then
                echo "Nginx configuration is not valid, see above for more details" >&2
                exit 1
            fi

            # check whether the nginx is enabled
            if [ "$(systemctl is-active nginx)" == "active" ]; then
                # nginx enabled, restart it
                echo "Nginx already enabled, restarting"
                if ! systemctl restart nginx; then
                    echo "Restarting nginx failed" >&2
                    exit 1
                fi
            else
                # enable and start the nginx
                echo "Enabling nginx"
                if ! systemctl enable nginx; then
                    echo "Enabling nginx failed" >&2
                    exit 1
                fi
                echo "Starting nginx"
                if ! systemctl start nginx; then
                    echo "Enabling nginx failed" >&2
                    exit 1
                fi
            fi
            # end of section for starting web server
        else
            # web server should be turned off
            # check whether the nginx sites-enabled symlink exists
            if [ -h "$NGINX_ENABLED" ]; then
                # it does, remove it
                if ! rm -f "$NGINX_ENABLED"; then
                    echo "Symlink $NGINX_ENABLED could not be removed"
                fi
            fi
            # symlink should not exist
            # stop the nginx and disable it
            echo "Stopping and disabling nginx"
            systemctl stop nginx
            systemctl disable nginx

            # end of section for turning off the webserver
        fi

        # check whether the new MervisFCGI configuration is in the temporary directory
        if [ -s /tmp/fcgi.ini.new ]; then
            # it is, move it to the final destination
            echo "MervisFCGI config is present, moving to the final destination"
            if ! mv /tmp/fcgi.ini.new /opt/mervis/fcgi.ini; then
                echo "Moving failed" >&2
                exit 1
            fi
        fi
        
        lock_fs
        ;;
    netserver)
        # Do nothing. UNUSED
        echo "Ignoring service 'netserver'"
        ;;
    sshserver)
        unlock_fs

        # check the on/off parameter
        if [ -z "$is_on" ]; then 
            echo "Missing parameter for service $service : on/off" >&2
            exit 1
        fi

        # should we turn the SSH on or off?
        if [ "$is_on" == "1" ]; then
            # ssh server should be on, validate port number
            if [ -n "$port" ]; then
                # port number is valid, we will create new configuration temporary file
                TMP_CONFIG="$(mktemp)"
                # check whether in active configuration is Port option, even when commented out
                if grep -q -i -e '^[[:blank:]]*#*[[:blank:]]*Port[[:blank:]]' "$SSHD_CONFIG"; then
                    # the Port option is there, replace the line with the new port and save temporarly
                    sed  "s/^[[:blank:]]*#*[[:blank:]]*Port[[:blank:]].*$/Port $port/"  "$SSHD_CONFIG" > "$TMP_CONFIG"
                else
                    # no Port option, create new config based on the old one and added the Port option
                    echo "Port $port" > "$TMP_CONFIG"
                    cat "$SSHD_CONFIG" >> "$TMP_CONFIG"
                fi

                # replace the running config with new config
                if ! mv "$TMP_CONFIG" "$SSHD_CONFIG"; then
                    echo "Reconfiguration of SSH failed" >&2
                    exit 1
                fi

                # reload SSH
                systemctl reload ssh

                # if the password parameter is passed as well, change it
                [ -n "$password" ] && echo "unipi:$password" | chpasswd 
            fi

            systemctl enable ssh
            systemctl start ssh
        else
            # stop the SSH server
            systemctl disable ssh
            systemctl stop ssh
        fi
        lock_fs
        ;;
    telnetserver)
        # do nothing. UNUSED
        echo "Ignoring service 'telnetserver'"
        ;;
    commit)
        echo "Service: commit"
        if [ -f "$CLOUDACCESS_TMP" ]; then
            echo -n "CloudAccess config file present in $CLOUDACCESS_TMP, moving to $CLOUDACCESS_FINAL ... "
            if ! mv "$CLOUDACCESS_TMP" "$CLOUDACCESS_FINAL"; then
                echo FAILED
            else
                echo OK
                echo -n "Restarting merviscloudaccess service ... "
                if ! systemctl restart merviscloudaccess; then
                    echo FAILED
                else
                    echo OK
                fi
            fi
        fi
        lock_fs
        ;;
    *)      
        echo "Unknown service $service" >&2
        exit 1
        ;;
esac

exit 0
