#!/bin/bash
# info: enables support for single sign on phpMyAdmin
# options: [mode]
#
# example: v-add-sys-pma-sso
#
# This function enables support for SSO to phpMyAdmin

#----------------------------------------------------------#
#                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
# shellcheck source=/usr/local/tulio/func/pma.sh
source $TULIO/func/pma.sh
# load config file
source_conf "$TULIO/conf/tulio.conf"

PMA_INSTALL="/usr/share/phpmyadmin"
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 [ -n "$PHPMYADMIN_KEY" ] && [ "$PHPMYADMIN_KEY" != "" ]; then
	echo "Error: SSO has been installed before to reenable it please run v-delete-sys-pma-sso first"
	exit 1
fi

if [ -f "/usr/share/phpmyadmin/tulio-sso.php" ]; then
	echo "Error: tulio-sso.php is already installed"
	exit 2
fi

# NOTE(tulio): upstream had this guard pointing at a misspelled path
# (/usr/local/hesta/...), so it never matched and the check was dead code. The
# path is corrected here for the rebrand; the condition is also negated to match
# the error message, which is what the guard was clearly meant to do.
if [ ! -f "/usr/local/tulio/web/api/index.php" ]; then
	echo "Error: API script not installed"
	exit 2
fi

if [ "API_SYSTEM" = "0" ]; then
	echo "Error: API is not enabled"
	exit 2
fi

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

# Generate the keys to secure everything
phpmyadminkey=$(generate_password)
apikey=$($BIN/v-add-access-key "$ROOT_USER" 'phpmyadmin-sso' 'phpMyAdmin' 'plain')

# Render the sign-on client into /usr/share/phpmyadmin/. It verifies the panel
# certificate, so it is told where to find a trust anchor for it when the system
# trust store does not already have one.
api_host="$(hostname -f)"
ca_file="$(pma_sso_ca_file "$api_host" "$BACKEND_PORT")"

if ! pma_sso_render "$TULIO_INSTALL_DIR/phpmyadmin/tulio-sso.php" \
	"$PMA_INSTALL/tulio-sso.php" \
	"$phpmyadminkey" "$api_host" "$BACKEND_PORT" "$apikey" "$ca_file"; then
	echo "Error: unable to install $PMA_INSTALL/tulio-sso.php"
	log_event "$E_UPDATE" "$ARGUMENTS"
	exit "$E_UPDATE"
fi

# Check if config already contains the keys
touch $PMA_CONFIG/tulio-sso.inc.php
chmod 640 $PMA_CONFIG/tulio-sso.inc.php
chown root:tuliomail $PMA_CONFIG/tulio-sso.inc.php

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';
}
?>" >> $PMA_CONFIG/tulio-sso.inc.php

file=$(cat $PMA_CONFIG/config.inc.php)
if ! [[ "$file" =~ tulio-sso.inc.php ]]; then
	if [[ $file =~ "//Add Tulio SSO code here" ]]; then
		sed -i "s|//Add Tulio SSO code here|//Add Tulio SSO code here\n     include ('$PMA_CONFIG/tulio-sso.inc.php');|g" $PMA_CONFIG/config.inc.php
	else
		echo "include ('$PMA_CONFIG/tulio-sso.inc.php');" >> $PMA_CONFIG/config.inc.php
	fi
fi

$BIN/v-change-sys-config-value 'PHPMYADMIN_KEY' "$phpmyadminkey"

if [ -z "$(echo $API_ALLOWED_IP | grep 127.0.0.1)" ]; then
	$BIN/v-add-sys-api-ip "127.0.0.1"
fi

#----------------------------------------------------------#
#                       Logging                            #
#----------------------------------------------------------#

if [ "$MODE" != "quiet" ]; then
	echo "PMA Tulio-SSO plugin has been successfully installed"
fi
$BIN/v-log-action "system" "Info" "Plugins" "phpMyAdmin Single Sign-On has been enabled."
log_event "$OK" "$ARGUMENTS"
