#!/bin/bash

SCRIPT_VER="1.3"

APP="elFinder"
APP_CATEGORY="File Managers"
APP_SCOPE="system"
APP_ENABLED="yes"
#><#APP_CHECK_VER_CMD="if [ -e /var/www/html/elfinder/package.json ] ; then grep -e "\s*\"version\":" /var/www/html/elfinder/package.json | awk "{print \$NF}" | tr -d "\"," ; else echo "" ; fi"
#><#APP_UPGRADE_VER_CMD="curl -Ls --connect-timeout 10 --retry 3 -m 30 -o /dev/null -w "%{url_effective}" https://github.com/Studio-42/elFinder/releases/latest | awk -F/ "{print \$NF}""
SUPPORTED_ON="Debian9,Ubuntu16.04,Ubuntu18.04,Ubuntu20.04"
USE_APACHE2="yes"
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

#ELFINDER_VER="2.1.15"
#ELFINDER_VER="2.1.56"
ELFINDER_USER="admin"
ELFINDER_PASSWORD="ChangeMe"
APP_DIRECTORY="/var/www/html/elfinder"

ELFINDER_THEME="windows-10"
#ELFINDER_THEME="moono"

while : ; do

    main_rc=1

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

    APT_UPDATE || break

    # Install apache2 & PHP
    case "${LSB_CODENAME}" in
      "xenial"|"stretch")
        PHP_VER="7.0"
        ;;
      "bionic")
        PHP_VER="7.2"
        ;;
      "focal")
        PHP_VER="7.4"
        ;;
      *)
        ERROR "Unsupported ${LSB_VENDOR} release: ${LSB_RELEASE}"
        break
        ;;
    esac

#    APT_INSTALL "apache2" || break
    APT_INSTALL "php${PHP_VER}" "libapache2-mod-php${PHP_VER}" || break

    APT_INSTALL "unzip" || break

    ELFINDER_VER="$( \
        curl -Ls --connect-timeout 10 --retry 3 -m 30 -o /dev/null -w '%{url_effective}' \
                 https://github.com/Studio-42/elFinder/releases/latest \
             | awk -F/ '{print $NF}' )"

    WGET "https://github.com/Studio-42/elFinder/archive/${ELFINDER_VER}.zip" || break
    UNZIP "${TMP_DIR}/${ELFINDER_VER}.zip" "${TMP_DIR}/" || break
    MV "${TMP_DIR}/elFinder-${ELFINDER_VER}" "${APP_DIRECTORY}" || break
    CP_FILE "${APP_DIRECTORY}/php/connector.minimal.php-dist" \
            "${APP_DIRECTORY}/php/connector.minimal.php" \
        || break

#    main_rc=0
#    break

## vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv

    #
    # Additional theme(s) setup
    #
    while : ; do

        MKDIR "${APP_DIRECTORY}/themes" || break

        APT_INSTALL "git-core" || break

        case "${ELFINDER_THEME}" in
           "windows-10")
               # 'Windows 10' theme
               GIT_CLONE \
                    "https://github.com/lokothodida/elfinder-theme-windows-10" \
                    "${TMP_DIR}/theme" \
                 || break
               MV "${TMP_DIR}/theme/windows-10" "${APP_DIRECTORY}/themes/" || break
               RUN_LOG "sed -i.bak \
                   -e 's|href=\"css/theme.css\"|href=\"themes/windows-10/css/theme.css\"|' \
                      '${APP_DIRECTORY}/elfinder.html' 2>&1"
               ;;
           "moono")
               # 'moono' theme
               GIT_CLONE \
                    "https://github.com/lokothodida/elfinder-theme-moono" \
                    "${TMP_DIR}/theme" \
                 || break
               MV "${TMP_DIR}/theme/moono" "${APP_DIRECTORY}/themes/" || break
               RUN_LOG "sed -i.bak \
                   -e 's|href=\"css/theme.css\"|href=\"themes/moono/css/theme.css\"|' \
                      '${APP_DIRECTORY}/elfinder.html' 2>&1"
               ;;
        esac

        break

    done



    INFO "-------------------------------------"
    INFO "Build password protection for elFinder"
    INFO "-------------------------------------"

    # Setup .htaccess
    cat <<-EOF > "${APP_DIRECTORY}/.htaccess" 2>> "${LOGFILE}"
	DirectoryIndex elfinder.php
	EOF

    # Setup Directory
    cat <<-EOF > "/etc/apache2/conf-enabled/elfinder.conf" 2>> "${LOGFILE}"
	<Directory ${APP_DIRECTORY}/>
	       Options Indexes FollowSymLinks
	       AllowOverride All
	       Require all granted
	</Directory>
	EOF


    OUTFILE="${APP_DIRECTORY}/elfinder.php"
    cat <<-EOF > "${OUTFILE}" 2>> "${LOGFILE}"
	<?php
	session_start();

	if(isset(\$_GET['logout'])){
	    session_destroy();
	    header('Location: elfinder.php');
	    exit();
	}

	if(!isset(\$_SESSION['authorized'])){

	if(isset(\$_POST['submit'])){
	    if(\$_POST['username'] =='${ELFINDER_USER}' && \$_POST['password'] == '${ELFINDER_PASSWORD}'){
	        \$_SESSION['authorized'] = true;
	        header('Location: elfinder.php');
	        exit();
	    }
	}

	?>

	<form action='' method='post' autocomplete='off'>
	<p>Username: <input type="text" name="username" value=""></p>
	<p>Password: <input type="password" name="password" value=""></p>
	<p><input type="submit" name="submit" value="Login"></p>    
	</form>

	<?php } else { ?>


	EOF
    cat "${APP_DIRECTORY}/elfinder.html" >> "${OUTFILE}" 2>> "${LOGFILE}"
    cat <<-EOF >> "${OUTFILE}" 2>> "${LOGFILE}"


	<?php } ?>
	EOF
    RUN_LOG "sed -i.bak -e 's|^\(\s*\)\(<!-- Element where elFinder will be created.*\)$|\n\1\<p\>\<a href=\"?logout\"\>Logout\</a\>\</p\>\n\n\1\2|' '${OUTFILE}' 2>&1"

    CHOWN_DIR www-data:www-data "${APP_DIRECTORY}"

    SVC_RESTART "apache2"



    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"
    RM_DIRS "${APP_DIRECTORY}"
fi

SCRIPTEXIT
