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

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

MODE=$1

# Includes
# shellcheck source=/etc/tuliocp/tulio.conf
source /etc/tuliocp/tulio.conf
# shellcheck source=/usr/local/tulio/func/main.sh
source $TULIO/func/main.sh
# load config file
source_conf "$TULIO/conf/tulio.conf"

PMA_CONFIG="/etc/phpmyadmin"

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

# Perform verification if read-only mode is enabled
check_tulio_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/tulio-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['tulio_token']) || isset(\$_COOKIE['SignonSession'])){
\$cfg['Servers'][\$i]['auth_type'] = 'signon';
\$cfg['Servers'][\$i]['SignonSession'] = 'SignonSession';
\$cfg['Servers'][\$i]['SignonURL'] = 'tulio-sso.php';
\$cfg['Servers'][\$i]['LogoutURL'] = 'tulio-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/tulio-sso.inc.php

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

#----------------------------------------------------------#
#                       Tulio                             #
#----------------------------------------------------------#

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

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

exit
