#!/bin/bash
# info: disables support for single sign on PHPMYADMIN
# options: [mode]
#
# example: v-delete-sys-pma-sso
#
# Disables 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

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

if [ ! -e "$PMA_INSTALL/tulio-sso.php" ]; then
	echo 'Error:  PMA Single Sign On already disabled'
	exit 1
fi

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

# NOTE(tulio): this used to look for the key between single quotes, which the
# client has never used, so the key it revoked was always the empty string and
# the real one stayed valid after the sign-on was disabled.
apikey="$(pma_sso_read_define "$PMA_INSTALL/tulio-sso.php" 'API_KEY')"

if [ -z "$apikey" ]; then
	echo "Warning: no API key found in $PMA_INSTALL/tulio-sso.php"
	echo "         Check v-list-access-keys for a leftover phpmyadmin-sso key"
elif [[ "$apikey" == *:* ]]; then
	$BIN/v-delete-access-key "${apikey%%:*}"
else
	$BIN/v-revoke-api-key "$apikey"
fi

#remove new files
rm /usr/share/phpmyadmin/tulio-sso.php
rm /etc/phpmyadmin/tulio-sso.inc.php

#revert config
sed -i "/tulio-sso.inc.php/d" $PMA_CONFIG/config.inc.php

# disable key
$BIN/v-change-sys-config-value 'PHPMYADMIN_KEY' ""

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

if [ "$MODE" != "quiet" ]; then
	echo "PMA Tulio-SSO plugin has been successfully removed/disabled"
fi

# Logging
$BIN/v-log-action "system" "Info" "Plugins" "phpMyAdmin Single Sign-On (SSO) disabled."
log_event "$OK" "$ARGUMENTS"

exit
