#!/bin/bash

SCRIPT_VER="1.10"

APP="SyncThing"
APP_CATEGORY="Sync Solutions"
APP_SCOPE="user"
APP_ENABLED="yes"
STORED_PASSWORD_SERVICE="syncthing"
SUPPORTED_ON="Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04"
USE_APACHE2="yes"
DAEMON_PORT=8384
LIBRARY="functions4.sh"

if [ "${SUPPORT-}" = '' ]; then
    SUPPORT="https://installers.rapidseedbox.com/scripts/whmcs_client_installers/support"
fi

LOGFILE="/var/log/whmcs_client_installers/${0}.log"
[ ! -d "/var/log/whmcs_client_installers" ] && mkdir -p "/var/log/whmcs_client_installers"

wget -4 -nc -q --no-check-certificate --timeout=20 --tries=5 ${SUPPORT}/${LIBRARY} >> "${LOGFILE}" 2>&1
if [ ! -f "./${LIBRARY}" ] ; then
    echo "55"
    echo "Error downloading \"${SUPPORT}/${LIBRARY}\"" >> "${LOGFILE}"
    exit 55
fi

# shellcheck source=support/functions4.sh
. "./${LIBRARY}"
SCRIPTENTRY

VALIDATE_USER

while : ; do

    main_rc=1

    CHECK_APP ; _rc=$?
    if [ ${_rc} -ne 0 ] ; then
        main_rc=${_rc}
        break
    fi

    ADD_APT_KEY_URL "https://syncthing.net/release-key.txt" "syncthing.gpg" || break
    RUN_LOG "echo 'deb http://apt.syncthing.net/ syncthing stable' > '/etc/apt/sources.list.d/syncthing.list'"
    _rc=$?
    if [ ${_rc} -ne 0 ] ; then
        ERROR "Error adding APT repository for '${APP}' !"
        break 
    fi

    APT_UPDATE || break
    APT_INSTALL \
            "apache2-utils" \
            "syncthing" \
            "xmlstarlet" \
        || break

    [ -d "${USERHOME}/.config/syncthing" ] \
        || MKDIR "${USERHOME}/.config/syncthing"

    ST_DAEMON_PORT="$(( USERUID + 8384 - FIRST_UID ))"
    if [ "${USERUID}" = "${FIRST_UID}" ] ; then
        _prefix="/syncthing"
    else
        _prefix="/syncthing-${USERNAME}"
    fi

    #
    # TODO: Need testing
    # xmlstarlet edit --update "configuration/gui/password" --value "${password_bcrypt_hash}" config.xml
    # su user -c "syncthing generate --gui-user=user2 --gui-password=ChangeMe2" ; echo $?
    #

    password_bcrypt_hash="$( htpasswd -bnBC 10 "" "${USERPASSWORD}" | tr -d ':\n' )"
    cat <<-EOF > "${USERHOME}/.config/syncthing/config.xml"
	<configuration version="29">
	    <gui enabled="true" tls="false" debugging="false" sendBasicAuthPrompt="false">
	        <address>127.0.0.1:${ST_DAEMON_PORT}</address>
	        <authMode>static</authMode>
	        <insecureSkipHostcheck>true</insecureSkipHostcheck>
	        <user>${USERNAME}</user>
	        <password>${password_bcrypt_hash}</password>
	        <theme>dark</theme>
	    </gui>
	</configuration>
	EOF

    CHOWN_DIR "${USERNAME}":"${USERNAME}" "${USERHOME}/.config/syncthing"


    # Setup systemd service
    cat <<-EOF > "/etc/systemd/system/syncthing@.service"
	[Unit]
	Description=Syncthing - Open Source Continuous File Synchronization for %I
	Documentation=http://docs.syncthing.net/
	After=network.target
	Wants=syncthing-inotify@.service

	[Service]
	User=%i
	ExecStart=/usr/bin/syncthing -no-browser -no-restart -logflags=0
	Restart=on-failure
	SuccessExitStatus=3 4
	RestartForceExitStatus=3 4
	Environment="GOMAXPROCS=2"

	[Install]
	WantedBy=multi-user.target
	EOF

        cat <<-EOF > "/etc/systemd/system/syncthing.slice" 2>> "${LOGFILE}"
	[Unit]
	Description=${APP} resource limiting
	Before=slices.target

	[Slice]
	CPUAccounting=yes
	CPUQuota=20%
	IOAccounting=yes
	IOReadBandwidthMax=/ 20M
	IOWriteBandwidthMax=/ 20M
	EOF

        [ ! -d "/etc/systemd/system/syncthing@.service.d" ] \
            && MKDIR "/etc/systemd/system/syncthing@.service.d"

        cat <<-EOF > "/etc/systemd/system/syncthing@.service.d/001-Slice.conf"
		[Service]
		Slice=syncthing.slice
		EOF

        cat <<-EOF > "/etc/systemd/system/syncthing@.service.d/10-Nice.conf"
		[Service]
		Nice=19
		EOF

    SYSTEMD_RELOAD

    systemctl is-enabled "syncthing@root" > /dev/null 2>&1 \
        && SVC_DISABLE "syncthing@root"
    systemctl is-active "syncthing@root" > /dev/null 2>&1 \
        && SVC_STOP    "syncthing@root"

    SVC_ENABLE "syncthing@${USERNAME}"
    SVC_START  "syncthing@${USERNAME}"

    RUN_LOG "sleep 3"
    SVC_STOP  "syncthing@${USERNAME}"

    # -- Customize service instance
    RUN_LOG "sed -i -e 's,\(\s*\)<maxFolderConcurrency>.*,\1<maxFolderConcurrency>1</maxFolderConcurrency>,' \
                 '${USERHOME}/.config/syncthing/config.xml'"
    RUN_LOG "sed -i -e 's,\(\s*\)<urAccepted>.*,\1<urAccepted>-1</urAccepted>,' \
                 '${USERHOME}/.config/syncthing/config.xml'"
    RUN_LOG "sed -i -e 's,\(\s*\)<urSeen>.*,\1<urSeen>3</urSeen>,' \
                 '${USERHOME}/.config/syncthing/config.xml'"
    RUN_LOG "sed -i -re '/\s*<unackedNotificationID>authenticationUserAndPassword/d' \
                 '${USERHOME}/.config/syncthing/config.xml'"

    SVC_START  "syncthing@${USERNAME}"

    # Configure `apache2` service
    if [ -d "/etc/apache2/userconf-enabled/" ] ; then
        [ -e "/etc/apache2/userconf-enabled/syncthing.conf" ] \
            && RM_FILES "/etc/apache2/userconf-enabled/syncthing.conf"
        cat <<-EOF > "/etc/apache2/userconf-enabled/syncthing-${USERNAME}.conf"
	RewriteEngine on
	RewriteRule ^${_prefix}\$ ${_prefix}/ [R=permanent]
	<Location ${_prefix}/>
	   Order Allow,Deny
	   Allow from All
	#   AuthType Digest
	#   AuthName "apache2"
	#   AuthDigestProvider file
	#   AuthUserFile "/etc/apache2/users.password"
	#   Require user user
	   ProxyPass http://127.0.0.1:${ST_DAEMON_PORT}/
	   ProxyPassReverse http://127.0.0.1:${ST_DAEMON_PORT}/
	   RequestHeader set "X-Forwarded-Proto" expr=%{REQUEST_SCHEME}
	</Location>
	EOF
        RUN_LOG "apachectl -t" || break
        SVC_RESTART "apache2"
    fi


    main_rc=0
    break

done


# Cleanup if error
if [ ${main_rc} -ne 0 -a ${main_rc} -ne 111 -a ${main_rc} -ne 117 ] ; then
    ERROR "'${APP}': Installation failed."

    # Cleanup tasks here

    systemctl is-enabled "syncthing@root" > /dev/null 2>&1 \
        && SVC_DISABLE "syncthing@root"
    systemctl is-active "syncthing@root" > /dev/null 2>&1 \
        && SVC_STOP    "syncthing@root"

    SVC_DISABLE "syncthing@${USERNAME}"
    SVC_STOP    "syncthing@${USERNAME}"

    if [ -e "/etc/apache2/userconf-enabled/syncthing-${USERNAME}.conf" ] ; then
        RM_FILES "/etc/apache2/userconf-enabled/syncthing-${USERNAME}.conf"
        SVC_RESTART "apache2"
    fi

#    RM_FILES    "/etc/systemd/system/syncthing@.service"
    SYSTEMD_RELOAD
fi

SCRIPTEXIT
