#!/bin/bash

HOST=${WIKISUITE_INSTALL_HOST:-$(hostname)}

ASSETS_DIR="/usr/share/wikisuite-virtualmin-base"

WEBMIN_ETC="/etc/webmin"
WEBMIN_PATH="/usr/share/webmin"
WEBMIN_CLI="/usr/share/webmin/bin/webmin"

# Helper functions (extensions to slib)
run() {
  echo "$2"
  eval "$1"
}

run_file_exists() {
  if [ ! -f "$3" ] || [ ! -d "$3" ] ; then
    return 0
  fi
  run "$1" "$2"
}

configvalue() {
  local sc_config="$2"
  local sc_value="$1"
  local sc_directive=$(echo "$sc_value" | cut -d'=' -f1 | sed 's/^[ \t]*//;s/[ \t]*$//')
  if grep -q "$sc_directive" "$2"; then
    sed -i -e "s#$sc_directive.*#$sc_value#" "$sc_config"
  else
    echo "$1" >>"$2"
  fi
}

convert_to_bytes() {
  local number=$1
  case ${number: -1} in
    "K") echo $(( ${number:0:-1} * 1024 )) ;;
    "M") echo $(( ${number:0:-1} * 1024 * 1024 )) ;;
    "G") echo $(( ${number:0:-1} * 1024 * 1024 * 1024 )) ;;
    *) echo $(( ${number} * 1 )) ;;
  esac
}

check_size_needs_update() {
  local key="$1"
  local value="$2"
  local file="$3"

  local curr_value=$(grep "${key}" "${file}" 2> /dev/null | cut -d'=' -f2 | sed 's/^[ \t]*//;s/[ \t]*$//')
  if [ -n "$curr_value" ]; then
    if [ $(convert_to_bytes ${value}) -gt $(convert_to_bytes ${curr_value}) ] ; then
      return 0
    else
      return 1
    fi
  fi

  return 0
}

#
# Setup Templates
#

virtualmin_modify_template_web () {
  (
    # works around escaping $ in the template when using "run"
    set -x
    APACHE_TEMPLATE=$(cat ${ASSETS_DIR}/apache-template | sed 's/\t/    /g' | tr '\n' '\t')
    virtualmin modify-template --id 0 --setting web --value "${APACHE_TEMPLATE}"
    return $?
  )
}

virtualmin_modify_template_nginx () {
  (
    # works around escaping $ in the template when using "run"
    set -x
    TEMPLATE=$(cat ${ASSETS_DIR}/nginx-template | sed -e '/^#/d' -e '/^ *$/d' -e 's/\t/    /g' | tr '\n' '\t')
    virtualmin modify-template --id 0 --setting virtualmin-nginx --value "${TEMPLATE}"
    return $?
  )
}

run "virtualmin_modify_template_web" "Modifying template Web"
run "virtualmin modify-template --id 0 --setting web_webmail --value 0" "Modifying template WebMail"
run "virtualmin modify-template --id 0 --setting web_admin --value 0" "Modifying template WebAdmin"
run "virtualmin modify-template --id 0 --setting web_stats_hdir --value stats" "Modifying template WebStats"
run "virtualmin modify-template --id 0 --setting web_phpver --value 7.4" "Modifying template Web PHP Version"
run "virtualmin modify-template --id 0 --setting web_php_suexec --value 3" "Modifying template PHP su exec"
run "virtualmin modify-template --id 0 --setting php_vars --value ''" "Modifying template PHP vars"
run "virtualmin modify-template --id 0 --setting php_fpm --value 'php_admin_value[sys_temp_dir] = \$HOME/tmp'" "Modifying template PHP FPM pool"

run "virtualmin modify-plan --id 0 --no-quota" "Modifying plan quota"
run "virtualmin modify-plan --id 0 --no-admin-quota" "Modifying plan admin-quota"

#
# Sensible defaults
#
sed  -n  -e  '/^blockhost_failures=/!p'  -i -e  '$ablockhost_failures=15'  /etc/webmin/miniserv.conf
sed  -n  -e  '/^blockhost_time=/!p'      -i -e  '$ablockhost_time=600'      /etc/webmin/miniserv.conf
sed  -n  -e  '/^blockuser_failures=/!p'  -i -e  '$ablockuser_failures=20'  /etc/webmin/miniserv.conf
sed  -n  -e  '/^blockuser_time=/!p'      -i -e  '$ablockuser_time=600'      /etc/webmin/miniserv.conf
sed  -n  -e  '/^logouttime=/!p'          -i -e  '$alogouttime=30'          /etc/webmin/miniserv.conf

#
# Add plans and templates for WikiSuite
#
cp ${ASSETS_DIR}/plans/10                   ${WEBMIN_ETC}/virtual-server/plans
cp ${ASSETS_DIR}/plans/20                   ${WEBMIN_ETC}/virtual-server/plans
cp ${ASSETS_DIR}/plans/30                   ${WEBMIN_ETC}/virtual-server/plans
cp ${ASSETS_DIR}/templates/10               ${WEBMIN_ETC}/virtual-server/templates
cp ${ASSETS_DIR}/templates/20               ${WEBMIN_ETC}/virtual-server/templates
cp ${ASSETS_DIR}/templates/30               ${WEBMIN_ETC}/virtual-server/templates

# Set the default plan and template to be used
sed -n  -e  '/^init_plan=/!p'      -i -e  '$ainit_plan=10'    ${WEBMIN_ETC}/virtual-server/config
sed -n  -e  '/^init_template=/!p'  -i -e  '$ainit_template=10' ${WEBMIN_ETC}/virtual-server/config

#
# Setup default page template
#
mkdir -p ${WEBMIN_ETC}/authentic-theme
rsync -a ${ASSETS_DIR}/authentic-theme/ ${WEBMIN_ETC}/authentic-theme/

run "cat ${ASSETS_DIR}/index.html > ${WEBMIN_PATH}/virtual-server/default/index.html" "Deploying new default page template"

#
# Setup mysql module
#
run "${WEBMIN_CLI} set-config -m mysql -o max_dbs -v 500" "Increase maximum number of tables to display so Tiki tables can be inspected on a fresh install"

#
# Execute the wizard steps and setup the default vhost for the server
#

cp ${ASSETS_DIR}/wikisuite-auto-wizard.pl ${WEBMIN_PATH}/virtual-server/wikisuite-auto-wizard.pl
chmod a+x ${WEBMIN_PATH}/virtual-server/wikisuite-auto-wizard.pl

run "WIKISUITE_DEFHOST=$HOST virtualmin wikisuite-auto-wizard" "Auto executing configuration wizard"

rm ${WEBMIN_PATH}/virtual-server/wikisuite-auto-wizard.pl

#
# Register post domain change command
#

# If the config value does not exists yet, the command will return 1, but does set the config, so just forcing to return success
run "${WEBMIN_CLI} set-config -m virtual-server -o post_command -v ${ASSETS_DIR}/bin/wikisuite-server-post-command.sh -f" "Configure Virtualmin post domain changes commands" || true

#
# Refreshing Virtualmin configuration
#

run "virtualmin check-config" "Check Virtualmin configuration"

# cron job is installed by the package, so we just need to activate
# If the config value does not exists yet the command will return 1, but does set the config, so just forcing to return success
run "${WEBMIN_CLI} set-config -m package-updates -o sched_action -v 2 -f" "Configure Webmin to update weekly" || true
