#!/bin/bash
# info: restrict phpMyAdmin access to Hestia Single Sign-On only
# options: [mode]
#
# example: v-add-sys-pma-restrict
#
# This function blocks direct/anonymous access to phpMyAdmin. Without a
# valid Hestia SSO token or an already established SSO session, requests
# are redirected to the Hestia login page instead of falling back to
# phpMyAdmin's own login form.

#----------------------------------------------------------#
#                Variables & Functions                     #
#----------------------------------------------------------#

MODE=$1

# Includes
# shellcheck source=/etc/hestiacp/hestia.conf
source /etc/hestiacp/hestia.conf
# shellcheck source=/usr/local/hestia/func/main.sh
source $HESTIA/func/main.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

PMA_CONFIG="/etc/phpmyadmin"

#----------------------------------------------------------#
#                    Verifications                         #
#----------------------------------------------------------#

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

# Checking root permissions
if [ "x$(id -u)" != 'x0' ]; then
	echo "Error: Script can be run executed only by root"
	exit 10
fi

if [ ! -e "$PMA_CONFIG/hestia-sso.inc.php" ]; then
	echo "Error: phpMyAdmin SSO is not enabled, please run v-add-sys-pma-sso first"
	exit 2
fi

if [ "$PMA_RESTRICT_ACCESS" = "yes" ]; then
	echo "Error: phpMyAdmin access is already restricted"
	exit 1
fi

#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#

echo "<?php
if(isset(\$_GET['hestia_token']) || isset(\$_COOKIE['SignonSession'])){
\$cfg['Servers'][\$i]['auth_type'] = 'signon';
\$cfg['Servers'][\$i]['SignonSession'] = 'SignonSession';
\$cfg['Servers'][\$i]['SignonURL'] = 'hestia-sso.php';
\$cfg['Servers'][\$i]['LogoutURL'] = 'hestia-sso.php?logout=1';
} else {
\$pma_restrict_host = explode(':', \$_SERVER['HTTP_HOST'] ?? '')[0];
if (!preg_match('/^[a-zA-Z0-9.-]+\$/', \$pma_restrict_host)) {
http_response_code(400);
exit('Invalid host');
}
header('Location: https://' . \$pma_restrict_host . '/');
exit;
}
?>" > $PMA_CONFIG/hestia-sso.inc.php

$BIN/v-change-sys-config-value 'PMA_RESTRICT_ACCESS' "yes"

#----------------------------------------------------------#
#                       Hestia                             #
#----------------------------------------------------------#

if [ "$MODE" != "quiet" ]; then
	echo "phpMyAdmin access has been restricted to Hestia Single Sign-On only"
fi

# Logging
$BIN/v-log-action "system" "Info" "Plugins" "phpMyAdmin access restricted to Hestia Single Sign-On."
log_event "$OK" "$ARGUMENTS"

exit
