#!/bin/sh

echo "Please make sure that EM servers (e.g., cluster-server and openapi-server) have been destroyed via command 'TIUP_HOME=<your em home> tiup em destroy <em-name>', or you have backed up the meta data to restore EM server, otherwise, it will be a dangerous operation."
read -r -p "Please type in 'I am aware of the risk to uninstall em.': " response
if [[ $response == "I am aware of the risk to uninstall em." ]]; then
	echo "start uninstalling"
else
	echo "do nothing"
	exit 1
fi

script_dir=$(cd $(dirname $0) && pwd)

CONFIG_TEMPLATE_YAML=$script_dir/config_template.yaml
if [ ! -f "$CONFIG_TEMPLATE_YAML" ]; then
    echo "$CONFIG_TEMPLATE_YAML does not exist."
    exit 1
fi

EM_PACKAGE_PATH=${script_dir}.tar.gz
EM_PACKAGE_NAME=$(basename -s .tar.gz $EM_PACKAGE_PATH)

USER=$(cat $CONFIG_TEMPLATE_YAML | grep user | sed 's/.*user: .*"\(.*\)".*/\1/')

CONFIG_YAML=/home/$USER/config.yaml
echo "##### remove config $CONFIG_YAML started #####"
rm -f $CONFIG_YAML
echo "##### remove config $CONFIG_YAML finished #####"
echo

echo "##### remove EM REPO /home/${USER}/em-repo started #####"
rm -rf /home/${USER}/em-repo
echo "##### remove EM REPO /home/${USER}/em-repo finished #####"
echo

EM_TIUP_HOME=/home/$USER/.em
echo "##### remove EM TIUP_HOME $EM_TIUP_HOME started #####"
rm -rf $EM_TIUP_HOME
echo "##### remove EM TIUP_HOME $EM_TIUP_HOME finished #####"
echo

echo "##### remove /em-deploy started #####"
rm -rf /em-deploy
echo "##### remove /em-deploy finished #####"
echo

echo "uinstalled em"

# To completely clear the installation, you may need to execute the following command, but 
# we comment the command as it might be a dangerous operation

# echo "##### remove /em-data started #####"
# rm -rf /em-data
# echo "##### remove /em-data finished #####"
# echo

# TIDB_TIUP_HOME=/home/$USER/.tiup
# echo "##### remove TiDB TIUP_HOME $TIDB_TIUP_HOME started #####"
# rm -rf $TIDB_TIUP_HOME
# echo "##### remove TiDB TIUP_HOME $TIDB_TIUP_HOME finished #####"
# echo

# And you may manually delete the line 'export PATH=/usr/local/bin:$PATH' in /home/$USER/.bash_profile
