#!/bin/bash

RED="\e[1;31m"
GREEN="\e[1;32m"
YELLOW="\e[1;33m"
ENDCOLOR="\e[0m"

help() {
     echo "";
     echo "Usage: ezscale_support_key.sh [add|remove|check]";
     echo "";
     exit 0;
}

case "$1" in
        --help|help|-h)
                help
                ;;
esac

SUPPORT_KEY=''
TMP_DOWNLOAD_LOCATION=/tmp
OPTION=$1;

if [ "$OPTION" == 'add' ]; then
	mkdir -p ~/.ssh
	chmod 700 ~/.ssh
	touch ~/.ssh/authorized_keys
	IS_KEY_INSTALLED=$(cat ~/.ssh/authorized_keys | grep -w support@ezscale.cloud)
	if [ "${IS_KEY_INSTALLED}" == "" ]; then
		echo -e "\nDownloading EZSCALE support SSH key."
		wget https://support.ezscale.tech/key -O ${TMP_DOWNLOAD_LOCATION}/__tmp___ezscale__support___key >/dev/null 2>&1
		SUPPORT_KEY=$(cat ${TMP_DOWNLOAD_LOCATION}/__tmp___ezscale__support___key)
        echo "${SUPPORT_KEY}" >> ~/.ssh/authorized_keys
        rm -f ${TMP_DOWNLOAD_LOCATION}/__tmp___ezscale__support___key
        echo -e "\n${GREEN}EZSCALE support SSH key installed successfully.${ENDCOLOR}\n"
	else
		echo -e "\n${YELLOW}EZSCALE support SSH key is already installed!${ENDCOLOR}\n"
	fi
	chmod 600 ~/.ssh/authorized_keys

	elif [ "$OPTION" == 'remove' ]; then
		IS_KEY_INSTALLED=$(cat ~/.ssh/authorized_keys | grep -w support@ezscale.cloud)
		if [ "${IS_KEY_INSTALLED}" == "" ]; then
			echo -e "\n${RED}EZSCALE support SSH key not found!${ENDCOLOR}\n"
		else
			sed -i '/support@ezscale.cloud/ d' ~/.ssh/authorized_keys
			echo -e "\n${GREEN}EZSCALE support SSH key removed successfully.${ENDCOLOR}\n"
		fi
	elif [ "$OPTION" == 'check' ]; then
    		IS_KEY_INSTALLED=$(cat ~/.ssh/authorized_keys | grep -w support@ezscale.cloud)
    		if [ "${IS_KEY_INSTALLED}" == "" ]; then
    			echo -e "\n${YELLOW}EZSCALE support SSH key NOT installed.${ENDCOLOR}\n"
    		else
    			echo -e "\n${YELLOW}EZSCALE support SSH key IS installed.${ENDCOLOR}\n"
    		fi
	else
		help
fi
