#!/bin/bash

SCRIPT_VER="1.3"

APP="Organizr"
APP_CATEGORY="Utilities"
APP_SCOPE="system"
APP_ENABLED="yes"
SUPPORTED_ON="Ubuntu20.04,Ubuntu22.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

VALIDATE_USER

APP_DIRECTORY="/var/www/organizr"
DB_DIRECTORY="/var/www/db"

while : ; do

    main_rc=1

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

    ADD_PKGS="git-core"
    case "${LSB_VENDOR}" in
      "Debian"|"Ubuntu")
          ADD_PKGS="${ADD_PKGS} php-mysql php-sqlite3 sqlite3 php-xml php-zip openssl php-curl php-cli"
          ;;
    esac

    ${PKG_INSTALL} ${ADD_PKGS} || break

    GIT_CLONE "https://github.com/causefx/Organizr" "${APP_DIRECTORY}" || break
    RUN_LOG "git config --global --add safe.directory ${APP_DIRECTORY}" || break

    if [ ! -d "${DB_DIRECTORY}" ] ; then
        MKDIR "${DB_DIRECTORY}" || break
    fi

    if [ -d "/etc/apache2/userconf-enabled" ] ; then
        cat <<-EOF > "/etc/apache2/userconf-enabled/organizr.conf" 2>> "${LOGFILE}"
	Alias /organizr  /var/www/organizr/
	<Directory /var/www/organizr/>
	  Options -Indexes
	  AllowOverride all
	  Require all granted
	  RewriteEngine On
	  RewriteBase /organizr/api/v2
	  RewriteCond %{REQUEST_FILENAME} !-f
	  RewriteCond %{REQUEST_FILENAME} !-d
	  RewriteRule ^ /organizr/api/v2/index.php [QSA,L]
	</Directory>
	EOF
    fi
    RUN_LOG "apachectl -t 2>&1" || break
    SVC_RESTART "${APACHE_SVC}"

    cat <<-'EOF' > "${APP_DIRECTORY}/cli-wizard.php"
	<?php
	if (PHP_SAPI !== 'cli') {
	    echo "Must be called via CLI";
	    exit(1);
	}
	error_reporting(E_ERROR | E_PARSE);
	require_once __DIR__.DIRECTORY_SEPARATOR."api/functions.php";
	if (file_exists(__DIR__ . DIRECTORY_SEPARATOR . 'api' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php')) {
	    echo "Wizard has already been run. Delete this file." . PHP_EOL;
	    exit(1);
	}
	$arguments = getopt(null, ['dbname:', 'dblocation:', 'username:', 'password:', 'email:', 'hashkey:']);
	$dbName = $arguments['dbname'] ?? 'database.db';
	$dbLocation = $arguments['dblocation'] ?? '/var/www/organizr/db/';
	$username = $arguments['username'] ?? 'user';
	$password = $arguments['password'] ?? 'password';
	$email = $arguments['email'] ?? 'user@example.com';
	$hashKey = $arguments['hashkey'] ?? substr(md5(mt_rand()), 0, 10);
	$apiKey = substr(md5(mt_rand()), 0, 20);
	$configArray = [
	    'dbName'=>$dbName,
	    'dbLocation'=>$dbLocation,
	    'licence'=>'personal',
	    'organizrHash'=>$hashKey,
	    'organizrAPI'=>$apiKey,
	    'registrationPassword'=>$password,
	    'uuid'=>exec('uuidgen -r')
	];
	createConfig($configArray);
	// Call DB Create
	createDB($dbLocation, $dbName);
	// Add in first user
	createFirstAdmin($dbLocation, $dbName, $username, $password, $email);
	createToken($username, $email, gravatar($email), 'Admin', 0, $hashKey, 1);
	EOF

#    oWD="$( pwd )"
#    cd "${APP_DIRECTORY}"
#    RUN_LOG "php cli-wizard.php --dbname 'DB-${USERNAME}.db' --dblocation '${DB_DIRECTORY}/' --username '${USERNAME}' --password '${USERPASSWORD}' 2>&1" || break
#    cd "${oWD}"

    CHOWN_DIR "${APACHE_USER}":"${APACHE_GROUP}" "${APP_DIRECTORY}" || break
    CHOWN_DIR "${APACHE_USER}":"${APACHE_GROUP}" "${DB_DIRECTORY}" || break


    main_rc=0
    break

done


SCRIPTEXIT
