#!/bin/bash

SCRIPT_VER="1.3"

APP="FileCommander"
APP_CATEGORY="File Managers"
APP_SCOPE="user"
APP_ENABLED="yes"
APP_VER="0.2.6"
STORED_PASSWORD_SERVICE="userdir"
SUPPORTED_ON="Debian9,Debian10,Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04"
USE_APACHE2="yes"
DAEMON_PORT=38080
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/filecommander"

while : ; do

    main_rc=1

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

    MKDIR "${APP_DIRECTORY}" || break

    if [ ! -x "/usr/local/bin/filecommander" ] ; then
        WGET "https://github.com/alphapeter/filecommander/releases/download/${APP_VER}/filecommander-${APP_VER}-linux-amd64.tar.gz" \
             "${TMP_DIR}/fc.tar.gz" || break
        TAR_ZXF "${TMP_DIR}/fc.tar.gz" "${TMP_DIR}/" || break
        MV "${TMP_DIR}/filecommander" "/usr/local/bin/filecommander" || break
        CHMOD_FILE 755 "/usr/local/bin/filecommander" || break
    fi

    CHOWN_DIR "${USERNAME}":"${USERNAME}" "${APP_DIRECTORY}" || break

    FC_PORT="$(( USERUID - FIRST_UID + 38080 ))"
    cat <<-EOF > "${APP_DIRECTORY}/settings.json"
	{
	  "roots": [
	    {
	      "name": "home",
	      "path": "/home/${USERNAME}"
	    },
	    {
	      "name": "Downloads",
	      "path": "/home/${USERNAME}/Downloads"
	    }
	  ],
	  "binding": "127.0.0.1:${FC_PORT}"
	}
	EOF

    _svc_file="/etc/systemd/system/filecommander@.service"
    if [ ! -e "${_svc_file}" ] ; then
        cat <<-EOF > "${_svc_file}"
	[Unit]
	Description=FileCommander
	After=network.target

	[Service]
	Type=simple
	User=%I
	Group=%I
	ExecStart=/usr/local/bin/filecommander --settings /home/%I/.config/filecommander/settings.json
	Restart=always

	[Install]
	WantedBy=multi-user.target
	EOF
        SYSTEMD_RELOAD
    fi

    SVC_ENABLE "filecommander@${USERNAME}" || break
    SVC_START  "filecommander@${USERNAME}" || break

    _apache_conf="/etc/apache2/userconf-enabled/filecommander-${USERNAME}.conf"
    _password_file="/etc/apache2/users.password"
    if [ ! -d "/etc/apache2/userconf-enabled/" ] ; then
        MKDIR "/etc/apache2/userconf-enabled" || break
    fi
    if [ "${USERUID}" = "${FIRST_UID}" ] ; then
        cat <<-EOF > "${_apache_conf}"
		RewriteEngine on
		RewriteRule ^/files$ /files/ [R=permanent]
		RewriteRule ^/files-${USERNAME}$ /files-${USERNAME}/ [R=permanent]
		<Location /files>
		    order deny,allow
		    deny from all
		    allow from all
		    AuthType Digest
		    AuthName "apache2"
		    AuthUserFile ${_password_file}
		    Require user ${USERNAME}
		    ProxyPass http://localhost:${FC_PORT}
		    ProxyPassReverse http://localhost:${FC_PORT}
		</Location>
		<Location /files-${USERNAME}>
		    order deny,allow
		    deny from all
		    allow from all
		    AuthType Digest
		    AuthName "apache2"
		    AuthUserFile ${_password_file}
		    Require user ${USERNAME}
		    ProxyPass http://localhost:${FC_PORT}
		    ProxyPassReverse http://localhost:${FC_PORT}
		</Location>
		EOF
    else
        cat <<-EOF > "${_apache_conf}"
		RewriteEngine on
		RewriteRule ^/files-${USERNAME}$ /files-${USERNAME}/ [R=permanent]
		<Location /files-${USERNAME}>
		    order deny,allow
		    deny from all
		    allow from all
		    AuthType Digest
		    AuthName "apache2"
		    AuthUserFile ${_password_file}
		    Require user ${USERNAME}
		    ProxyPass http://localhost:${FC_PORT}
		    ProxyPassReverse http://localhost:${FC_PORT}
		</Location>
		EOF
    fi

    SVC_RESTART "${APACHE_SVC}"


    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}': Starting cleanup procedure"
    SVC_DISABLE "filecommander@${USERNAME}"
    SVC_STOP  "filecommander@${USERNAME}"
    RM_FILES "/etc/apache2/userconf-enabled/filecommander-${USERNAME}.conf"
    RM_DIRS "${APP_DIRECTORY}"
    SVC_RESTART "${APACHE_SVC}"
fi

SCRIPTEXIT
