#!/bin/bash

SCRIPT_VER="1.10"

APP="Resilio Sync"
APP_CATEGORY="Sync Solutions"
APP_SCOPE="user"
APP_ENABLED="yes"
SYS_PKG_NAME="resilio-sync"
STORED_PASSWORD_SERVICE="resiliosync"
SUPPORTED_ON="CentOS7,CentOS8,CentOSStream8,Debian9,Debian10,Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04"
WEBUI_PORT=8888
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

APP_DIRECTORY="${USERHOME}/.config/resilio-sync"

while : ; do

    main_rc=1

    [ -d "${USERHOME}" ] || break

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

    STORAGE_DIRECTORY="${USERHOME}/resilio-sync-storage"
    LOG_DIRECTORY="/var/log/resilio-sync/${USERNAME}"
    RSLSYNC_PORT="$(( USERUID + 8888 - FIRST_UID ))"
    DEBUG "USERUID:      ${USERUID}"
    DEBUG "FIRST_UID:    ${FIRST_UID}"
    DEBUG "RSLSYNC_PORT: ${RSLSYNC_PORT}"

    case "${LSB_VENDOR}" in
      "CentOS"|"CentOSStream")
          cat <<-EOF > "/etc/yum.repos.d/resilio-sync.repo"
		[resilio-sync]
		name=Resilio Sync \$basearch
		baseurl=http://linux-packages.resilio.com/resilio-sync/rpm/\$basearch
		enabled=1
		gpgcheck=1
		EOF
          RUN_LOG "rpm --import https://linux-packages.resilio.com/resilio-sync/key.asc" || break
          YUM_INSTALL "resilio-sync" || break
          ;;

      "Debian"|"Ubuntu")
          MKDIR "/etc/apt/sources.list.d" || break
          echo "deb http://linux-packages.resilio.com/resilio-sync/deb resilio-sync non-free" \
                      > "/etc/apt/sources.list.d/resilio-sync.list"
          if [ $? -ne 0 ] ; then
              ERROR "Error adding Resilio Sync repository!"
              break
          fi
          ADD_APT_KEY_URL "https://linux-packages.resilio.com/resilio-sync/key.asc" "resilio.gpg"
          if [ $? -ne 0 ] ; then
              ERROR "Error adding Resilio Sync repository key!"
              RM_FILES "/etc/apt/sources.list.d/resilio-sync.list"
              break
          fi
          APT_UPDATE || break
          APT_INSTALL "openssl" || break
          APT_INSTALL "resilio-sync"
          ;;
    esac

    # Stop/disable system service - we do not need it :)
    if [ -e "/etc/monit/conf.d/resilio-sync" ] ; then
        RM_FILES "/etc/monit/conf.d/resilio-sync"
        MONIT_RELOAD
    fi
    SVC_STATUS "resilio-sync" \
        && SVC_STOP "resilio-sync"
    SVC_DISABLE "resilio-sync"
    if [ "${SVC_SYSTEM}" = "init" ] ; then
        [ -e "/etc/init.d/resilio-sync" ] \
            && RM_FILES "/etc/init.d/resilio-sync"
    fi

    # Stop/Disable BTSync service - conflicts
    SVC_STATUS "btsync@${USERNAME}" \
        && SVC_STOP "btsync@${USERNAME}"
    systemctl is-enabled "btsync@${USERNAME}" > /dev/null 2>&1 \
        && SVC_DISABLE "btsync@${USERNAME}"

    if [ ! -d "${APP_DIRECTORY}" ] ; then
        MKDIR "${APP_DIRECTORY}" || break
    fi
    if [ ! -d "${STORAGE_DIRECTORY}" ] ; then
        MKDIR "${STORAGE_DIRECTORY}" || break
        CHOWN_DIR "${USERNAME}":"${USERNAME}" "${STORAGE_DIRECTORY}" || break
    fi

    password_hash="$( openssl passwd -crypt "${USERPASSWORD}" 2> /dev/null )"
    [ -z "${password_hash}" ] \
        && password_hash="$( mkpasswd -m des "${USERPASSWORD}" )"
    if [ -e "/etc/ssl/a.seedbox.vip/cert.pem" ] \
       && [ -e "/etc/ssl/a.seedbox.vip/privkey.pem" ] ; then
        MKDIR "${APP_DIRECTORY}/ssl" || break
        CP_FILE "/etc/ssl/a.seedbox.vip/cert.pem" "${APP_DIRECTORY}/ssl/" || break
        CP_FILE "/etc/ssl/a.seedbox.vip/privkey.pem" "${APP_DIRECTORY}/ssl/" || break
        cat <<-EOF > "${APP_DIRECTORY}/config.json"
	{
	    "listening_port" : 0,
	    "storage_path" : "${STORAGE_DIRECTORY}",
	    "directory_root" : "${USERHOME}",
	    "pid_file" : "${APP_DIRECTORY}/sync.pid",
	    "agree_to_EULA": "yes",

	    "webui" :
	    {
	        "listen" : "0.0.0.0:${RSLSYNC_PORT}",
	        "login" : "${USERNAME}",
	        "password_hash" : "${password_hash}",
	        "force_https" : true,
	        "ssl_certificate" : "${APP_DIRECTORY}/ssl/cert.pem",
	        "ssl_private_key" : "${APP_DIRECTORY}/ssl/privkey.pem"
	    }
	}
	EOF
    else
        cat <<-EOF > "${APP_DIRECTORY}/config.json"
	{
	    "listening_port" : 0,
	    "storage_path" : "${STORAGE_DIRECTORY}",
	    "directory_root" : "${USERHOME}",
	    "pid_file" : "${APP_DIRECTORY}/sync.pid",
	    "agree_to_EULA": "yes",

	    "webui" :
	    {
	        "listen" : "0.0.0.0:${RSLSYNC_PORT}",
	        "login" : "${USERNAME}",
	        "password_hash" : "${password_hash}",
	        "force_https" : true
	    }
	}
	EOF
    fi

    CHOWN_DIR "${USERNAME}":"${USERNAME}" "${APP_DIRECTORY}"
    [ ! -d "${LOG_DIRECTORY}" ] \
        && MKDIR "${LOG_DIRECTORY}"
    CHOWN_DIR "${USERNAME}":"${USERNAME}" "${LOG_DIRECTORY}"

    cat <<-EOF > "/etc/systemd/system/resilio-sync@.service"
	[Unit]
	Description=Resilio Sync service
	Documentation=http://help.getsync.com/
	After=network.target

	[Service]
	Type=forking
	User=%I
	Group=%I
	UMask=0002
	Restart=on-failure
	PermissionsStartOnly=true
	PIDFile=/home/%I/.config/resilio-sync/sync.pid
	ExecStartPre=/bin/mkdir -p /home/%I/.config/resilio-sync
	ExecStartPre=/bin/chown -R %I:%I /home/%I/.config/resilio-sync
	ExecStart=/usr/bin/rslsync --config /home/%I/.config/resilio-sync/config.json --log /var/log/resilio-sync/%I/resilio-sync.log

	[Install]
	WantedBy=multi-user.target
	EOF

    cat <<-EOF > "/etc/systemd/system/resilio-sync.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/resilio-sync@.service.d" ] \
        && MKDIR "/etc/systemd/system/resilio-sync@.service.d"

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

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

    SYSTEMD_RELOAD


    # -- Configure firewall
    FW_OPEN_PORTS "${RSLSYNC_PORT}/tcp"

    # -- Enable / start `resilio-sync` service instance
    SVC_ENABLE  "resilio-sync@${USERNAME}"
    SVC_START   "resilio-sync@${USERNAME}"

    #
    # -- 'monit' configs
    if [ -d "/etc/monit/conf.d" ] ; then
        cat <<-EOF > "/etc/monit/conf.d/resilio-sync@${USERNAME}"
	check process resilio-sync-${USERNAME} with pidfile ${APP_DIRECTORY}/sync.pid
	  start program = "/usr/sbin/service resilio-sync@${USERNAME} restart"
	  stop program  = "/usr/sbin/service resilio-sync@${USERNAME} stop"
	  if 5 restarts within 5 cycles then timeout
	  if failed host localhost port ${RSLSYNC_PORT} type tcp then restart
	EOF
        MONIT_RELOAD
    fi

    # -- 'logrotate' configs
    if [ -d "/etc/logrotate.d" ] ; then
         cat <<-EOF > "/etc/logrotate.d/resilio-sync-${USERNAME}" 2>> "${LOGFILE}"
	/var/log/resilio-sync/${USERNAME}/resilio-sync.log {
	    weekly
	    rotate 8
	    compress
	    delaycompress
	    dateext
	    missingok
	    size 10M
	    create 660 ${USERNAME} ${USERNAME}
	    postrotate
	        service resilio-sync@${USERNAME} restart 1>/dev/null
	    endscript
	    maxage 100
	}
	EOF
    fi 


    main_rc=0
    break

done


SCRIPTEXIT
