#!/bin/bash
# shellcheck disable=SC2034,SC2086

#
# Name:         easy-ssl-v2
# Version:      1.5.12
# Description:  Seedbox SSL Manager (`my.seedbox.vip` domain, ZeroSSL personal certificate)
#
# (c) 2021-2023, Rapidseedbox, alexey@rapidseedbox.com
#

export LANG=en_US
export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

SC_NAME="$( basename "${0}" )"
SC_VER="$( grep -m 1 -E '^#\s*Version:\s+' "${0}" | awk '{print $NF}' )"

# Primary client subdomain
SUBDOMAIN="my.seedbox.vip"

# `certbot` default options
CERTBOT_OPTS=""
CERTBOT_SERVER="https://acme.zerossl.com/v2/DV90"

# Certificates storage on the box
SSL_ROOT_DIR="/etc/letsencrypt/live"

# Log directory
LOG_DIR="/var/log/rsbssl"
[ -d "${LOG_DIR}" ] || mkdir -p "${LOG_DIR}"

LSB_VENDOR="$( lsb_release -si 2>&1 | awk '{print $1}' )"
LSB_RELEASE="$( lsb_release -sr )"
[ "${LSB_VENDOR}" = "CentOS" -o "${LSB_VENDOR}" = "Debian" ] \
    && LSB_RELEASE="$( echo "${LSB_RELEASE}" | awk -F'.' '{print $1}' )"
LSB_VER="${LSB_VENDOR}${LSB_RELEASE}"


a2ensite_centos () {
    local _site="${1}"
    local _site_available
    local _rc=1

    _site_conf="${_site}"
    if [ ! -e "/etc/apache2/sites-available/${_site}" ] ; then
        if [ -e "/etc/apache2/sites-available/${_site}.conf" ] ; then
            _site_conf="${_site}.conf"
        fi
    fi
    if [ -e "/etc/apache2/sites-available/${_site_conf}" ] ; then
        ln -sf "/etc/apache2/sites-available/${_site_conf}" \
               "/etc/apache2/sites-enabled/${_site_conf}"
    fi
    _rc=$?
    return ${_rc}
}


# ----------------------------------------------- #
# Color output functions                          #
# ----------------------------------------------- #
__RAINBOWPALETTE="1"
__colortext () {
    if [ "${COLORS}" = "yes" ] ; then
        echo -n "\e[${__RAINBOWPALETTE};${2}m${1}\e[0m"
    else
        echo -n "${1}"
    fi
}
echogreen () {
    echo -ne "$(__colortext "${1}" "32")"
}
echored () {
    echo -ne "$(__colortext "${1}" "31")"
}
echoblue () {
    echo -ne "$(__colortext "${1}" "34")"
}
echopurple () {
    echo -ne "$(__colortext "${1}" "35")"
}
echoyellow () {
    echo -ne "$(__colortext "${1}" "33")"
}
echocyan () {
    echo -ne "$(__colortext "${1}" "36")"
}
echodarkgray () {
    echo -ne "$(__colortext "${1}" "30")"
}
echolightgray () {
    echo -ne "$(__colortext "${1}" "37")"
}


# 'apache2' config directory
case "${LSB_VENDOR}" in
  "CentOS")
      APACHE2_SVC="httpd"
      APACHE2_CFG_DIR="/etc/httpd"
      APACHE2_LOG_DIR="/var/log/httpd"
      A2ENSITE="a2ensite_centos"
      if [ ! -d "${APACHE2_CFG_DIR}/userconf-enabled" ] ; then
          echodarkgray "$( mkdir -vp "${APACHE2_CFG_DIR}/userconf-enabled" 2>&1 )\n"
          echo "IncludeOptional userconf-enabled/*.conf" > "${APACHE2_CFG_DIR}/conf.d/userconf.conf"
      fi
      [ ! -e "/var/www/html/index.html" ] \
          && echo -n "" > "/var/www/html/index.html"
      if [ ! -e "/etc/ssl/certs/dhparam.pem" ] ; then
          openssl dhparam -out "/etc/ssl/certs/dhparam.pem" 2048
      fi
      ;;
  "Debian"|"Ubuntu")
      APACHE2_SVC="apache2"
      APACHE2_CFG_DIR="/etc/apache2"
      APACHE2_LOG_DIR="/var/log/apache2"
      A2ENSITE="a2ensite"
      ;;
esac

#IP="$( ip route get 8.8.8.8 | head -1 | sed -e 's/.*\s*src\s*\([0-9.]*\).*$/\1/' )"
#IP="$( ip -o route get to 8.8.8.8 | sed -nre 's/.*\s+src\s+([0-9.]+).*/\1/p' )"
##IP="$( ip -4 -o ro ls | awk -v dev="$( ip -4 -o ro ls | grep ^default | awk '{print $5}' )" '$3 == dev && $4 == "proto" && $5 == "kernel" {print $NF}' )"
#IP="$( hostname -i )"

echodarkgray "Checking network configuration"
IP="$( curl -s ifconfig.me 2>&1 )"
_rc=$?
if [ "${_rc}" != "0" ] ; then
    echodarkgray ":  $( echored "FAILED: CURL return code: [${_rc}]" )\n"
    if [ -n "${IP}" ] ; then
        echodarkgray "CURL message:  $( echored "${IP}" )\n"
    fi
    exit 1
fi
if [ -z "${IP}" ] ; then
    echodarkgray ":  $( echored "FAILED: Can't determine IP address!" )\n"
    exit 1
fi
echodarkgray ":  $( echogreen "OK" )\n"
echodarkgray "IP address:  $( echogreen "${IP}" )\n"

IP_WITH_DASH="$( echo "${IP}" | tr '.' '-' )"
SERVER_NAME="${IP_WITH_DASH}.${SUBDOMAIN}"
SSL_DIR="${SSL_ROOT_DIR}/${IP_WITH_DASH}.${SUBDOMAIN}"

usage () {
        cat <<-EOF

	Request SSL certificate for https://${SERVER_NAME}

	Usage:
	------------
	    ${SC_NAME} [-h] [-b|-n] [-f]

	    -h         - Display this help message
	    -b or -n   - Batch  mode - useful for cronjobs
	    -f         - Force configuration reload 
	    -t         - Use development version

	EOF
}


# -- Check if script upgrade is available
RSB_URL="http://installers.rapidseedbox.com/scripts/whmcs_client_installers"
DEVELOPMENT="no"
for _s in "${@}" ; do
    if [ "${_s}" = "-t" ] ; then
        RSB_URL="https://installers.seedbox.vip/oci"
        DEVELOPMENT="yes"
        echored "==================================\n"
        echored "==== >>> DEVELOPMENT MODE <<< ====\n"
        echored "==================================\n"
    fi
done
#
if wget -nc -q --no-check-certificate \
     -O "/var/tmp/${SC_NAME}.${SC_PID}" \
     --timeout=20 --tries=5 \
     "${RSB_URL}/support/rsb-scripts/common/${SC_NAME}" > /dev/null 2>&1
then
    _rc=0
    _sfx=""
    _NEW_VER="$( grep -m 1 -E '^#\s*Version:\s+' "/var/tmp/${SC_NAME}.${SC_PID}" \
                     | awk '{print $NF}' )"
    if which diff > /dev/null 2>&1 ; then
        diff "/var/tmp/${SC_NAME}.${SC_PID}" "/usr/local/bin/${SC_NAME}" > /dev/null 2>&1
        _rc=$?
        [ ${_rc} -ne 0 -a "${_NEW_VER}" = "${SC_VER}" ] \
            && _sfx=" (modified)"
    else
        [ "${_NEW_VER}" != "${SC_VER}" ] \
            && _rc=1
    fi
    if [ ${_rc} -ne 0 ] ; then
        >&2 echo "${SC_NAME} ${SC_VER}: updating to ${_NEW_VER}${_sfx} and restarting..."
        mv -f "/var/tmp/${SC_NAME}.${SC_PID}" "/usr/local/bin/${SC_NAME}"
        chmod -f 755 "/usr/local/bin/${SC_NAME}"
        >&2 exec "${0}" -f ${SCRIPT_ARGS}
        exit 0
    else
        rm -f "/var/tmp/${SC_NAME}.${SC_PID}" > /dev/null 2>&1
    fi
fi
[ -e "/var/tmp/${SC_NAME}.${SC_PID}" ] \
    && rm -v "/var/tmp/${SC_NAME}.${SC_PID}" > /dev/null 2>&1
# --


# Parse command line
COLORS="yes"
OPTIND=1
PARSE_ERR=0
BATCH="no"
FORCE="no"
while getopts ":hbnft" params; do
    case "${params}" in
      h)
          usage ; exit 0
          ;;
      b|n)
          COLORS="no"
          BATCH="yes"
          continue
          ;;
      f)
          FORCE="yes"
          continue
          ;;
      t)
          continue
          ;;
      \?) 
          echo "Invalid option: $( echored "-${OPTARG}" )\n"
          PARSE_ERR=1
          ;;
    esac
done

if [ ${PARSE_ERR} -ne 0 ] ; then
    usage ; exit 1
fi
shift "$(( OPTIND - 1 ))"


# Get PLEX setting
getPref () {
    local key="$1"
    sed -n -E "s/^.*${key}=\"([^\"]*)\".*$/\1/p" "${prefFile}"
}

# Set PLEX setting
setPref () {
    local key="$1"
    local value="$2"
    count="$( grep -c "${key}" "${prefFile}" )"
    count=$(( count + 0 ))
    if [[ $count -gt 0 ]] ; then
        sed -i -E "s/${key}=\"([^\"]*)\"/${key}=\"$value\"/" "${prefFile}"
    else
        sed -i -E "s/\/>/ ${key}=\"$value\"\/>/" "${prefFile}"
    fi
}

[ "${BATCH}" = "no" ] \
    && echoyellow "${SC_NAME} ${SC_VER} (${LSB_VENDOR} ${LSB_RELEASE}): Starting\n"

# ---------------------------------------------
# Sanity checks
# ---------------------------------------------

[ "${BATCH}" = "no" ] && echodarkgray "Checking 'certbot' availability"
if ! which "certbot" > /dev/null 2>&1 ; then
    echored "'certbot' is not installed!\n"
    exit 1
fi
[ "${BATCH}" = "no" ] && echodarkgray ":  $( echogreen "OK" )\n"

[ "${BATCH}" = "no" ] && echodarkgray "Checking Apache2 status"
if [ ! -e "${APACHE2_CFG_DIR}/sites-available" ] ; then
    echored "Service '${APACHE2_SVC}' is not installed!\n"
    exit 1
fi
[ "${BATCH}" = "no" ] && echodarkgray ":  $( echogreen "OK" )\n"

if ! apachectl -t > /dev/null 2>&1 ; then
    echodarkgray "Apache configuration test: $( echored "FAILED" )\n"
    echored "Please run $( echocyan "apachectl -t" ) to check and correct the errors first!\n"
    exit 2
fi


if [ ! -d "/var/www/html/.well-known/acme-challenge" ] ; then
    echodarkgray "$( mkdir -vp "/var/www/html/.well-known/acme-challenge" )\n"
fi


# ---------------------------------------------
# Cleaning up some stuff
# ---------------------------------------------

if [ "${FORCE}" = "yes" ] ; then
    echodarkgray "$( rm -vf ${APACHE2_CFG_DIR}/sites-enabled/rsbssl_easyV2_*.conf 2>&1 )\n"
    echodarkgray "$( rm -vf ${APACHE2_CFG_DIR}/sites-available/rsbssl_easyV2_*.conf 2>&1 )\n"
    echodarkgray "$( rm -vf /etc/ssl/certs/${SERVER_NAME}.* 2>&1 )\n"
    echodarkgray "$( rm -vf /var/local/rsbssl/anondownloads.cfg 2>&1 )\n"
    certbot \
          -n \
          delete \
          ${CERTBOT_OPTS}  \
          --server "${CERTBOT_SERVER}" \
          --agree-tos \
          --cert-name "${SERVER_NAME}" \
        2> /dev/null
    if systemctl is-active "${APACHE2_SVC}" > /dev/null 2>&1 ; then
        echodarkgray "Reloading '${APACHE2_SVC}' service"
        if service "${APACHE2_SVC}" reload > /dev/null 2>&1 ; then
            echodarkgray ":  $( echogreen "OK" )\n"
        else
            echodarkgray ":  $( echored "FAILED" )\n"
        fi
    else
        echored "'${APACHE2_SVC}' service is not active\n"
        exit 3
    fi
fi


case "${LSB_VENDOR}" in
  "CentOS")
      if [ ! -e "${APACHE2_CFG_DIR}/conf.d/non-ssl.conf" ] ; then
          cat <<-EOF > "${APACHE2_CFG_DIR}/conf.d/non-ssl.conf"
		<VirtualHost _default_:80>
		    DocumentRoot "/var/www/html"
		    Alias /.well-known/acme-challenge/ "/var/www/html/.well-known/acme-challenge/"
		    <Directory "/var/www/html/">
		        AllowOverride None
		        Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
		        Require method GET POST OPTIONS
		    </Directory>
		</VirtualHost>
		EOF
          echodarkgray "Configuring Apache2 non-SSL default site...\n"
          systemctl is-active "${APACHE2_SVC}" > /dev/null 2>&1 \
              && systemctl restart "${APACHE2_SVC}"
      fi
      ;;
esac


APACHE_RESTART="no"


# ---------------------------------------------------------
# Have we already requested the certificate earlier ?
# ---------------------------------------------------------
[ "${BATCH}" = "no" ] && echodarkgray "Checking '${SERVER_NAME}' certificate status\n"
if ! certbot certificates -d "${SERVER_NAME}" 2> /dev/null \
       | grep -q -E "^\s*Domains:\s*${SERVER_NAME}"
then
    # Request new certificate from ZeroSSL
    [ "${BATCH}" = "no" ] && echodarkgray "Requesting new certificate\n"
    _username="rsb-$( shuf -i 1-300000 -n 1 )@rsb.great.com"
    _certbot_extra_opts="$( curl -s \
               https://api.zerossl.com/acme/eab-credentials-email \
                  --data "email=${_username}" \
             | jq -r '"--eab-kid " + .eab_kid + " --eab-hmac-key " + .eab_hmac_key' )"
    certbot \
          -n \
          certonly \
          ${CERTBOT_OPTS} \
          ${_certbot_extra_opts} \
          --webroot \
          --webroot-path "/var/www/html" \
          -m "${_username}" \
          --agree-tos \
          -d "${SERVER_NAME}" \
          -d "plex-${SERVER_NAME}" \
          -d "emby-${SERVER_NAME}" \
          -d "jellyfin-${SERVER_NAME}" \
          --server "${CERTBOT_SERVER}" \
          --post-hook \
              "systemctl is-active ${APACHE2_SVC} > /dev/null 2>&1 && systemctl reload ${APACHE2_SVC} > /dev/null 2>&1" \
        2> /dev/null
else
    # Just renew the certificate
    [ "${BATCH}" = "no" ] && echodarkgray "Sending certificate renew request\n"
    certbot ${CERTBOT_OPTS} renew --cert-name "${SERVER_NAME}" 2> /dev/null
fi
if ! certbot certificates -d "${SERVER_NAME}" 2> /dev/null \
       | grep -q -E "^\s*Domains:\s*${SERVER_NAME}"
then
    echored "Error requesting / renewing the certificate for '${SERVER_NAME}' !\n"
    exit 1
fi
[ "${BATCH}" = "no" ] && echodarkgray "Cerrtificate creation / renewal:  $( echogreen "SUCCESS" )\n"

#
# Configure Apache2
#
case "${LSB_VENDOR}" in
  "CentOS")
      _cert_file="/etc/ssl/certs/${SERVER_NAME}.dh.pem"
      ;;
  "Debian"|"Ubuntu")
      _cert_file="${SSL_DIR}/fullchain.pem"
      if [ ! -e "${APACHE2_CFG_DIR}/conf-available/port-80.conf" ] ; then
          sed -i -e 's|^\s*\(Listen 80\)\s*$|#\1|' "/etc/apache2/ports.conf"
          cat <<-EOF > "${APACHE2_CFG_DIR}/conf-available/port-80.conf"
		Listen 80
		EOF
          a2enconf "port-80.conf" > /dev/null 2>&1
          APACHE_RESTART="yes"
      elif [ ! -e "${APACHE2_CFG_DIR}/conf-enabled/port-80.conf" ] ; then
          a2enconf "port-80.conf" > /dev/null 2>&1
          APACHE_RESTART="yes"
      fi
      ;;
esac


MAIN_CONFIG="no"
if [    ! -e "${APACHE2_CFG_DIR}/sites-available/rsbssl_easyV2_${SUBDOMAIN}.conf" \
     -o ! -e "${APACHE2_CFG_DIR}/sites-enabled/rsbssl_easyV2_${SUBDOMAIN}.conf" ]
then
    MAIN_CONFIG="yes"
elif ! grep -q -E "\s*ServerName\s*${SERVER_NAME}" \
              "${APACHE2_CFG_DIR}/sites-available/rsbssl_easyV2_${SUBDOMAIN}.conf"
then
    MAIN_CONFIG="yes"
elif [ -e "/etc/ssl/certs/${SERVER_NAME}.dh.pem" ]
then
    _tm_1="$( stat -c "%Y" "/etc/ssl/certs/${SERVER_NAME}.dh.pem" )"
    _tm_2="$( stat -c "%Y" "$( readlink -f "/etc/letsencrypt/live/${SERVER_NAME}/cert.pem" )" )"
    _tm_diff="$(( _tm_2 - _tm_1 ))"
    if [ ${_tm_diff} -gt 120 ] ; then
        MAIN_CONFIG="yes"
    fi
fi
if [ "${MAIN_CONFIG}" = "yes" ] ; then
    echodarkgray "Configuring Apache main site...\n"
    APACHE_RESTART="yes"
    cat <<-EOF > "${APACHE2_CFG_DIR}/sites-available/rsbssl_easyV2_${SUBDOMAIN}.conf"
	SSLProtocol TLSv1.2
	EOF
    case "${LSB_VER}" in
      "CentOS7")
          cat "${SSL_DIR}/cert.pem" "/etc/ssl/certs/dhparam.pem" \
              > "${_cert_file}"
          echodarkgray "$( chmod -v 0600 "/etc/ssl/certs/${SERVER_NAME}.dh.pem" )\n"
          ;;
      *)
          cat <<-EOF >> "${APACHE2_CFG_DIR}/sites-available/rsbssl_easyV2_${SUBDOMAIN}.conf"
		SSLOpenSSLConfCmd Curves secp521r1:secp384r1:prime256v1
		EOF
          ;;
    esac
    cat <<-EOF >> "${APACHE2_CFG_DIR}/sites-available/rsbssl_easyV2_${SUBDOMAIN}.conf"
	SSLHonorCipherOrder on
	SSLCipherSuite "!ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:!ECDHE-ECDSA-AES128-SHA:!ECDHE-ECDSA-AES256-SHA:!ECDHE-ECDSA-AES128-SHA256:!ECDHE-ECDSA-AES256-SHA384:!ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:!ECDHE-RSA-AES128-SHA:!ECDHE-RSA-AES256-SHA:!ECDHE-RSA-AES128-SHA256:!ECDHE-RSA-AES256-SHA384:!DHE-RSA-AES128-GCM-SHA256:!DHE-RSA-AES256-GCM-SHA384:!DHE-RSA-AES128-SHA:!DHE-RSA-AES256-SHA:!DHE-RSA-AES128-SHA256:!DHE-RSA-AES256-SHA256"
	SSLPassPhraseDialog builtin
	SSLCompression off
	SSLSessionTickets off

	Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"

	<VirtualHost *:80>

	    ServerName ${SERVER_NAME}

	    # This VirtualHost redirects everything to HTTPS on port 443.
	    RewriteEngine On
	    RewriteCond %{REQUEST_URI} !^/\.well-known/
	    RewriteCond %{HTTPS} off
	    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

	</VirtualHost>

	<VirtualHost _default_:443>

	    ServerName ${SERVER_NAME}
	    ServerAdmin webmaster@localhost
	    DocumentRoot /var/www/html

	    ErrorLog ${APACHE2_LOG_DIR}/error.log
	    #CustomLog ${APACHE2_LOG_DIR}/access.log combined
	    CustomLog /dev/null combined

	    SSLEngine on
	    SSLCertificateFile ${_cert_file}
	    SSLCertificateKeyFile ${SSL_DIR}/privkey.pem
	    SSLCertificateChainFile ${SSL_DIR}/chain.pem

	    <FilesMatch "\.(cgi|shtml|phtml|php)$">
	        SSLOptions +StdEnvVars
	    </FilesMatch>

	    <Directory /usr/lib/cgi-bin>
	        SSLOptions +StdEnvVars
	    </Directory>

	    UserDir /home/*
	    UserDir disabled root

	    HeaderName HEADER.html
	    ReadmeName README.html

	    <Directory /home/*>
	        AllowOverride FileInfo AuthConfig Limit Indexes
	        Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
	#        php_flag engine off
	        <Limit GET POST OPTIONS>
	            Require all granted
	        </Limit>
	        <LimitExcept GET POST OPTIONS>
	            Require all denied
	        </LimitExcept>
	    </Directory>

	    ProxyRequests off
	    ProxyPreserveHost On

	    RewriteEngine on
	    RewriteRule ^/rutorrent$ /rutorrent/ [R]

	    ProxyPass /rutorrent http://127.0.0.1:8080/
	    ProxyPassReverse /rutorrent http://127.0.0.1:8080/

	    IncludeOptional userconf-enabled/*.conf

	</VirtualHost>
	EOF
    ${A2ENSITE} "rsbssl_easyV2_${SUBDOMAIN}.conf" > /dev/null 2>&1
fi


#
# Configure `plex` URL if needed
#
PLEX_CONFIG="no"
if id "plex" > /dev/null 2>&1 ; then
    home="$( echo ~plex )"
    pmsApplicationSupportDir="${PLEX_MEDIA_SERVER_APPLICATION_SUPPORT_DIR:-${home}/Library/Application Support}"
    prefFile="${pmsApplicationSupportDir}/Plex Media Server/Preferences.xml"
    #
    if [    ! -e "${APACHE2_CFG_DIR}/sites-available/rsbssl_easyV2_${SUBDOMAIN}-plex.conf" \
         -o ! -e "${APACHE2_CFG_DIR}/sites-enabled/rsbssl_easyV2_${SUBDOMAIN}-plex.conf" ]
    then
        PLEX_CONFIG="yes"
    else 
        if ! grep -q -E "\s*ServerName\s*plex-${SERVER_NAME}" \
                  "${APACHE2_CFG_DIR}/sites-available/rsbssl_easyV2_${SUBDOMAIN}-plex.conf"
        then
            PLEX_CONFIG="yes"
        fi
    fi
    if [ "${PLEX_CONFIG}" = "yes" ] ; then
        echodarkgray "Configuring Apache PLEX site...\n"
        APACHE_RESTART="yes"
        cat <<-EOF > "${APACHE2_CFG_DIR}/sites-available/rsbssl_easyV2_${SUBDOMAIN}-plex.conf"
	<VirtualHost *:443>

	    ServerName plex-${SERVER_NAME}
	    ServerAdmin webmaster@localhost
	    DocumentRoot /var/www/html

	    ErrorLog ${APACHE2_LOG_DIR}/error.log
	    #CustomLog ${APACHE2_LOG_DIR}/access.log combined
	    CustomLog /dev/null combined

	    SSLEngine on
	    SSLCertificateFile ${_cert_file}
	    SSLCertificateKeyFile ${SSL_DIR}/privkey.pem
	    SSLCertificateChainFile ${SSL_DIR}/chain.pem

	    <FilesMatch "\.(cgi|shtml|phtml|php)$">
	        SSLOptions +StdEnvVars
	    </FilesMatch>

	    <Proxy *>
	        Order deny,allow
	        Allow from all
	    </Proxy>

	    ProxyRequests off
	    ProxyPreserveHost On

	    ProxyPass / http://127.0.0.1:32400/
	    ProxyPassReverse / http://127.0.0.1:32400/

	    ProxyPass /:/ ws://127.0.0.1:32400/:/
	    ProxyPassReverse /:/ ws://127.0.0.1:32400/:/

	    ProxyPass /:/ wss://127.0.0.1:32400/:/
	    ProxyPassReverse /:/ wss://127.0.0.1:32400/:/

	</VirtualHost>
	EOF
        ${A2ENSITE} "rsbssl_easyV2_${SUBDOMAIN}-plex.conf" > /dev/null 2>&1
        #
        if [ -e "${prefFile}" ] ; then
            echodarkgray "Configuring Plex Media Server instance...\n"
            setPref "FriendlyName" "plex-${IP_WITH_DASH}"
            systemctl is-active plexmediaserver > /dev/null 2>&1 \
                && systemctl restart plexmediaserver
        fi
    fi
fi


#
# Configure `emby` URL if needed
#
EMBY_CONFIG="no"
if id "emby" > /dev/null 2>&1 ; then
    #
    if [    ! -e "${APACHE2_CFG_DIR}/sites-available/rsbssl_easyV2_${SUBDOMAIN}-emby.conf" \
         -o ! -e "${APACHE2_CFG_DIR}/sites-enabled/rsbssl_easyV2_${SUBDOMAIN}-emby.conf" ]
    then
        EMBY_CONFIG="yes"
    else 
        if ! grep -q -E "\s*ServerName\s*emby-${SERVER_NAME}" \
                  "${APACHE2_CFG_DIR}/sites-available/rsbssl_easyV2_${SUBDOMAIN}-emby.conf"
        then
            EMBY_CONFIG="yes"
        fi
    fi
    if [ "${EMBY_CONFIG}" = "yes" ] ; then
        echodarkgray "Configuring Apache EMBY site...\n"
        APACHE_RESTART="yes"
        cat <<-EOF > "${APACHE2_CFG_DIR}/sites-available/rsbssl_easyV2_${SUBDOMAIN}-emby.conf"
	<VirtualHost *:443>

	    ServerName emby-${SERVER_NAME}
	    ServerAdmin webmaster@localhost
	    DocumentRoot /var/www/html

	    ErrorLog ${APACHE2_LOG_DIR}/error.log
	    #CustomLog ${APACHE2_LOG_DIR}/access.log combined
	    CustomLog /dev/null combined

	    SSLEngine on
	    SSLCertificateFile ${_cert_file}
	    SSLCertificateKeyFile ${SSL_DIR}/privkey.pem
	    SSLCertificateChainFile ${SSL_DIR}/chain.pem

	    <FilesMatch "\.(cgi|shtml|phtml|php)$">
	        SSLOptions +StdEnvVars
	    </FilesMatch>

	    <Proxy *>
	        Order deny,allow
	        Allow from all
	    </Proxy>

	    ProxyRequests off
	    ProxyPreserveHost On

	    ProxyPass / http://127.0.0.1:8096/
	    ProxyPassReverse / http://127.0.0.1:8096/

	    ProxyPass /:/ ws://127.0.0.1:8096/:/
	    ProxyPassReverse /:/ ws://127.0.0.1:8096/:/

	    ProxyPass /:/ wss://127.0.0.1:8096/:/
	    ProxyPassReverse /:/ wss://127.0.0.1:8096/:/

	</VirtualHost>
	EOF
        ${A2ENSITE} "rsbssl_easyV2_${SUBDOMAIN}-emby.conf" > /dev/null 2>&1
    fi
fi


#
# Configure `jellyfin` URL if needed
#
JELLYFIN_CONFIG="no"
if id "jellyfin" > /dev/null 2>&1 ; then
    #
    if [    ! -e "${APACHE2_CFG_DIR}/sites-available/rsbssl_easyV2_${SUBDOMAIN}-jellyfin.conf" \
         -o ! -e "${APACHE2_CFG_DIR}/sites-enabled/rsbssl_easyV2_${SUBDOMAIN}-jellyfin.conf" ]
    then
        JELLYFIN_CONFIG="yes"
    else 
        if ! grep -q -E "\s*ServerName\s*jellyfin-${SERVER_NAME}" \
                  "${APACHE2_CFG_DIR}/sites-available/rsbssl_easyV2_${SUBDOMAIN}-jellyfin.conf"
        then
            JELLYFIN_CONFIG="yes"
        fi
    fi
    if [ "${JELLYFIN_CONFIG}" = "yes" ] ; then
        echodarkgray "Configuring Apache JELLYFIN site...\n"
        APACHE_RESTART="yes"
        cat <<-EOF > "${APACHE2_CFG_DIR}/sites-available/rsbssl_easyV2_${SUBDOMAIN}-jellyfin.conf"
	<VirtualHost *:443>

	    ServerName jellyfin-${SERVER_NAME}
	    ServerAdmin webmaster@localhost
	    DocumentRoot /var/www/html

	    ErrorLog ${APACHE2_LOG_DIR}/error.log
	    #CustomLog ${APACHE2_LOG_DIR}/access.log combined
	    CustomLog /dev/null combined

	    SSLEngine on
	    SSLCertificateFile ${_cert_file}
	    SSLCertificateKeyFile ${SSL_DIR}/privkey.pem
	    SSLCertificateChainFile ${SSL_DIR}/chain.pem

	    <FilesMatch "\.(cgi|shtml|phtml|php)$">
	        SSLOptions +StdEnvVars
	    </FilesMatch>

	    <Proxy *>
	        Order deny,allow
	        Allow from all
	    </Proxy>

	    ProxyRequests off
	    ProxyPreserveHost On

	    ProxyPass /socket ws://127.0.0.1:8096/socket
	    ProxyPassReverse /socket ws://127.0.0.1:8096/socket

	    ProxyPass / http://127.0.0.1:8096/
	    ProxyPassReverse / http://127.0.0.1:8096/

	</VirtualHost>
	EOF
        ${A2ENSITE} "rsbssl_easyV2_${SUBDOMAIN}-jellyfin.conf" > /dev/null 2>&1
    fi
fi


#
# Configure `downloads` URL if needed
#
DL_CONFIG="no"
if which uuidgen > /dev/null 2>&1 ; then
    [ -d "/var/local/rsbssl" ] || echodarkgray "$( mkdir -p /var/local/rsbssl )\n"
    if    [ "${FORCE}" = "yes" ] \
       || [ ! -e "/var/local/rsbssl/anondownloads.cfg" ]
    then
        uuidgen > "/var/local/rsbssl/anondownloads.cfg"
        DL_CONFIG="yes"
    fi
    DL_PATH="$( cat "/var/local/rsbssl/anondownloads.cfg" )"
    #
    if [ "${DL_CONFIG}" = "yes" ] ; then
        echodarkgray "Configuring Apache anonymous Downloads URI...\n"
        APACHE_RESTART="yes"
        cat <<-EOF > "${APACHE2_CFG_DIR}/userconf-enabled/downloads.conf"
	Alias /${DL_PATH} "/home/user/Downloads/"
	<Directory "/home/user/Downloads/">
	    AllowOverride None
	    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
	    Allow from all
	    Satisfy any
	</Directory>
	EOF
    fi
fi



# Reload `apache2` service if needed
if [ "${APACHE_RESTART}" = "yes" ] ; then
    echodarkgray "Checking '${APACHE2_SVC}' configuration"
    if ! apachectl -t > /dev/null 2>&1 ; then
        echodarkgray "Apache configuration test: $( echored "FAILED" )\n"
        echored "Please run 'apachectl -t' to check...\n"
        exit 2
    fi
    echogreen ":  OK\n"
    if systemctl is-active "${APACHE2_SVC}" > /dev/null 2>&1 ; then
        echodarkgray "Reloading '${APACHE2_SVC}' service"
        if service "${APACHE2_SVC}" reload > /dev/null 2>&1 ; then
            echodarkgray ":  $( echogreen "OK" )\n"
        else
            echodarkgray ":  $( echored "FAILED" )\n"
        fi
    else
        echored "'${APACHE2_SVC}' service is not active\n"
    fi
fi

# Configure `thinlinc`
# --------------------- #
# DISABLED: 2023/01/27  #
# --------------------- #
TL_CONFIG="no"
if false && [ -e "/opt/thinlinc/bin/tl-config" ] ; then
    [ "${FORCE}" = "yes" ] \
        && TL_CONFIG="yes"
    grep -q "${SERVER_NAME}" "/opt/thinlinc/etc/conf.d/vsmagent.hconf" \
        || TL_CONFIG="yes"
    grep -q "${SUBDOMAIN}" "/opt/thinlinc/etc/conf.d/webaccess.hconf" \
        || TL_CONFIG="yes"
    if [ "${TL_CONFIG}" = "yes" ] ; then
        /opt/thinlinc/bin/tl-config /webaccess/cert=${SSL_DIR}/fullchain.pem 
        /opt/thinlinc/bin/tl-config /webaccess/certkey=${SSL_DIR}/privkey.pem 
        echodarkgray "ThinLinc Web Access service"
        if service "tlwebaccess" restart > /dev/null 2>&1 ; then
            echodarkgray ":  $( echogreen "OK" )\n"
        else
            echodarkgray ":  $( echored "FAILED" )\n"
        fi
        echodarkgray "ThinLinc VsmAgent service"
        /opt/thinlinc/bin/tl-config /vsmagent/agent_hostname=${SERVER_NAME}
        if service "vsmagent" restart > /dev/null 2>&1 ; then
            echodarkgray ":  $( echogreen "OK" )\n"
        else
            echodarkgray ":  $( echored "FAILED" )\n"
        fi
    fi
    TL_CONFIG="yes"
fi

# Configure `logrotate`
if [ -d "/etc/logrotate.d" ] ; then
    cat <<-EOF > "/etc/logrotate.d/ssl-mgr"
	${LOG_DIR}/*.log
	{
	    rotate 8
	    weekly
	    missingok
	    notifempty
	    size 1M
	    compress
	    delaycompress
	}
	EOF
fi

# Configure `cron`
_flags=""
if [ "${DEVELOPMENT}" = "yes" ] ; then
    _flags=" -t"
fi
#if [ -e "/etc/cron.d/easy-ssl" ] ; then
#    echodarkgray "$( rm -vf "/etc/cron.d/easy-ssl" )\n"
#fi
if [ -d "/etc/cron.d" ] ; then
    cat <<-EOF > "/etc/cron.d/easy-ssl-v2"
	# ${SERVER_NAME}
	MAILTO=""
	PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

	@reboot root /bin/bash /usr/local/bin/easy-ssl-v2 -b${_flags} | while IFS= read -r line; do echo "[\$(date -u)]: \${line}"; done | tee -a "${LOG_DIR}/easy-ssl-v2.log"

	15 */3 * * * root /bin/bash /usr/local/bin/easy-ssl-v2 -b${_flags} | while IFS= read -r line; do echo "[\$(date -u)]: \${line}"; done | tee -a "${LOG_DIR}/easy-ssl-v2.log"
	EOF
fi


if [    "${APACHE_RESTART}" = "yes" \
     -o "${BATCH}" = "no"           \
     -o "${FORCE}" = "yes" ]
then
    cat <<-EOF

	Congratulations!
	------------------

	You can now access your server using this URL:
	    $( echocyan "https://${SERVER_NAME}" )

	EOF
    if id "plex" > /dev/null 2>&1 ; then
        cat <<-EOF
	To access Plex Media Server you can use this URL:
	    $( echocyan "https://plex-${SERVER_NAME}" )

	EOF
    fi
    if id "emby" > /dev/null 2>&1 ; then
        cat <<-EOF
	To access Emby Media Server you can use this URL:
	    $( echocyan "https://emby-${SERVER_NAME}" )

	EOF
    fi
    if id "jellyfin" > /dev/null 2>&1 ; then
        cat <<-EOF
	To access Jellyfin Media Server you can use this URL:
	    $( echocyan "https://jellyfin-${SERVER_NAME}" )

	EOF
    fi
    if [ "${TL_CONFIG}" = "yes" ] ; then
        cat <<-EOF
	To access ThinLinc Remote Desktop you can use this URL:
	    $( echocyan "https://${SERVER_NAME}:300" )

	EOF
    fi
    if [ "${DL_CONFIG}" = "yes" ] ; then
        cat <<-EOF
	To access user Downloads folder anonymously you can use this URL:
	    $( echocyan "https://${SERVER_NAME}/${DL_PATH}" )

	EOF
    fi
else
    echodarkgray "Everything is up to date. Nothing to do.\n\n"
fi

exit 0
