#!/bin/bash
### Farbdefinitionen ####
#   TEXT in Weiss       #
#   DATEIEN in Gelb     #
#   ORDNER in HellBlau  #
#########################
# Version Tomcat
TOMCAT="tomcat10"
# Version number of Guacamole to install
# Homepage ~ https://guacamole.apache.org/releases/
GUACVERSION="1.5.5"
# Latest Version of MySQL Connector/J if manual install is required (if libmariadb-java/libmysql-java is not available via apt)
# Homepage ~ https://dev.mysql.com/downloads/connector/j/
MCJVER="8.0.27"
# Farbdefinitionen zur Ausgabe 
ROT='\033[0;31m'
HELLROT='\033[1;31m'
GRUEN='\033[0;32m'
HELLGRUEN='\033[1;32m'
GELB='\033[1;33m'
BLAU='\033[0;34m'
HELLBLAU='\033[1;34m'
LILA='\033[0;35m'
HELLLILA='\033[1;35m'
DUNKELESTUERKIS='\033[0;36m'
TUERKIS='\033[1;36m'
HELLGRAU='\033[0;37m'
WEISS='\033[1;37m'
# Colors to use for output
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
RED='\033[1;31m'
GREEN='\033[1;32m'
CYAN='\033[1;36m'
NC='\033[0m' # No Color

# Log Location
LOG="/tmp/guacamole_${GUACVERSION}_build.log"

# Initialize variable values
installTOTP=""
installDuo=""
installMySQL=""
mysqlHost=""
mysqlPort=""
mysqlRootPwd=""
guacDb=""
guacUser=""
guacPwd=""
PROMPT=""
MYSQL=""

# Get script arguments for non-interactive mode
while [ "$1" != "" ]; do
    case $1 in
        # Install MySQL selection
        -i | --installmysql )
            installMySQL=true
            ;;
        -n | --nomysql )
            installMySQL=false
            ;;

        # MySQL server/root information
        -h | --mysqlhost )
            shift
            mysqlHost="$1"
            ;;
        -p | --mysqlport )
            shift
            mysqlPort="$1"
            ;;
        -r | --mysqlpwd )
            shift
            mysqlRootPwd="$1"
            ;;

        # Guac database/user information
        -db | --guacdb )
            shift
            guacDb="$1"
            ;;
        -gu | --guacuser )
            shift
            guacUser="$1"
            ;;
        -gp | --guacpwd )
            shift
            guacPwd="$1"
            ;;

   esac
    shift
done
echo
if [[ -z ${installMySQL} ]]; then
    # Prompt the user to see if they would like to install MySQL, default of yes
    echo "MySQL is required for installation, if you're using a remote MySQL Server select 'n'"
    echo -e -n "${CYAN}Would you like to install MySQL? (Y/n): ${NC}"
    read PROMPT
    if [[ ${PROMPT} =~ ^[Nn]$ ]]; then
        installMySQL=false
    else
        installMySQL=true
    fi
fi

if [ "${installMySQL}" = false ]; then
    # We need to get additional values
    [ -z "${mysqlHost}" ] \
      && read -p "Enter MySQL server hostname or IP: " mysqlHost
    [ -z "${mysqlPort}" ] \
      && read -p "Enter MySQL server port [3306]: " mysqlPort
    [ -z "${guacDb}" ] \
      && read -p "Enter Guacamole database name [guacamole_db]: " guacDb
    [ -z "${guacUser}" ] \
      && read -p "Enter Guacamole user [guacamole_user]: " guacUser
fi

# Checking if mysql host given
if [ -z "${mysqlHost}" ]; then
    mysqlHost="localhost"
fi

# Checking if mysql port given
if [ -z "${mysqlPort}" ]; then
    mysqlPort="3306"
fi

# Checking if mysql user given
if [ -z "${guacUser}" ]; then
    guacUser="guacamole_user"
fi

# Checking if database name given
if [ -z "${guacDb}" ]; then
    guacDb="guacamole_db"
fi

if [ -z "${mysqlRootPwd}" ]; then
    # Get MySQL "Root" and "Guacamole User" password
    while true; do
        echo
        read -s -p "Enter ${mysqlHost}'s MySQL root password: " mysqlRootPwd
        echo
        read -s -p "Confirm ${mysqlHost}'s MySQL root password: " PROMPT2
        echo
        [ "${mysqlRootPwd}" = "${PROMPT2}" ] && break
        echo -e "${RED}Passwords don't match. Please try again.${NC}" 1>&2
    done
else
    echo -e "${BLUE}Read MySQL root's password from command line argument${NC}"
fi
echo

if [ -z "${guacPwd}" ]; then
    while true; do
        echo -e "${BLUE}A new MySQL user will be created (${guacUser})${NC}"
        read -s -p "Enter ${mysqlHost}'s MySQL guacamole user password: " guacPwd
        echo
        read -s -p "Confirm ${mysqlHost}'s MySQL guacamole user password: " PROMPT2
        echo
        [ "${guacPwd}" = "${PROMPT2}" ] && break
        echo -e "${RED}Passwords don't match. Please try again.${NC}" 1>&2
        echo
    done
else
    echo -e "${BLUE}Read MySQL ${guacUser}'s password from command line argument${NC}"
fi
echo

if [ "${installMySQL}" = true ]; then
    # Seed MySQL install values
    debconf-set-selections <<< "mysql-server mysql-server/root_password password ${mysqlRootPwd}"
    debconf-set-selections <<< "mysql-server mysql-server/root_password_again password ${mysqlRootPwd}"
fi


echo
echo -e "${WEISS}Installation der Pakete. ${HELLROT}Der Installationsverlauf wir nicht angezeigt!!! ${WEISS}Wenn alles geklappt hat erscheint ein ${GREEN} OK ${NC}"
echo
sleep 3
apt install -y mariadb-server  
echo

# Set MySQL password
export MYSQL_PWD=${mysqlRootPwd}

if [ "${installMySQL}" = true ]; then

    # Restart MySQL service
    echo -e "${BLUE}Restarting MySQL service & enable at boot...${NC}"
    service mysql restart
    if [ $? -ne 0 ]; then
        echo -e "${RED}Failed${NC}" 1>&2
        exit 1
    else
        echo -e "${GREEN}OK${NC}"
    fi
    # Start at boot
    systemctl enable mysql
    echo

    # Default locations of MySQL config file
    for x in /etc/mysql/mariadb.conf.d/50-server.cnf \
             /etc/mysql/mysql.conf.d/mysqld.cnf \
             /etc/mysql/my.cnf \
             ; do
        # Check the path exists
        if [ -e "${x}" ]; then
            # Does it have the necessary section
            if grep -q '^\[mysqld\]$' "${x}"; then
                mysqlconfig="${x}"
                # no point keep checking!
                break
            fi
        fi
    done

    if [ -z "${mysqlconfig}" ]; then
        echo -e "${YELLOW}Couldn't detect MySQL config file - you may need to manually enter timezone settings${NC}"
    else
        # Is there already a value?
        if grep -q "^default_time_zone[[:space:]]?=" "${mysqlconfig}"; then
            echo -e "${YELLOW}Timezone already defined in ${mysqlconfig}${NC}"
        else
            timezone="$( cat /etc/timezone )"
            if [ -z "${timezone}" ]; then
                echo -e "${YELLOW}Couldn't find timezone, using UTC${NC}"
                timezone="UTC"
            fi
            echo -e "${YELLOW}Setting timezone as ${timezone}${NC}"
            # Fix for https://issues.apache.org/jira/browse/GUACAMOLE-760
            mysql_tzinfo_to_sql /usr/share/zoneinfo 2>/dev/null | mysql -u root -D mysql -h ${mysqlHost} -P ${mysqlPort}
            crudini --set ${mysqlconfig} mysqld default_time_zone "${timezone}"
            # Restart to apply
            service mysql restart
            echo
        fi
    fi
fi

# Create ${guacDb} and grant ${guacUser} permissions to it

# SQL code
guacUserHost="localhost"

if [[ "${mysqlHost}" != "localhost" ]]; then
    guacUserHost="%"
    echo -e "${YELLOW}MySQL Guacamole user is set to accept login from any host, please change this for security reasons if possible.${NC}"
fi

# Check for ${guacDb} already being there
echo -e "${BLUE}Checking MySQL for existing database (${guacDb})${NC}"
SQLCODE="
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='${guacDb}';"

# Execute SQL code
MYSQL_RESULT=$( echo ${SQLCODE} | mysql -u root -D information_schema -h ${mysqlHost} -P ${mysqlPort} )
if [[ $MYSQL_RESULT != "" ]]; then
    echo -e "${RED}It appears there is already a MySQL database (${guacDb}) on ${mysqlHost}${NC}" 1>&2
    echo -e "${RED}Try:    mysql -e 'DROP DATABASE ${guacDb}'${NC}" 1>&2
    #exit 1
else
    echo -e "${GREEN}OK${NC}"
fi

# Check for ${guacUser} already being there
echo -e "${BLUE}Checking MySQL for existing user (${guacUser})${NC}"
SQLCODE="
SELECT COUNT(*) FROM mysql.user WHERE user = '${guacUser}';"

# Execute SQL code
MYSQL_RESULT=$( echo ${SQLCODE} | mysql -u root -D mysql -h ${mysqlHost} -P ${mysqlPort} | grep '0' )
if [[ $MYSQL_RESULT == "" ]]; then
    echo -e "${RED}It appears there is already a MySQL user (${guacUser}) on ${mysqlHost}${NC}" 1>&2
    echo -e "${RED}Try:    mysql -e \"DROP USER '${guacUser}'@'${guacUserHost}'; FLUSH PRIVILEGES;\"${NC}" 1>&2
    #exit 1
else
    echo -e "${GREEN}OK${NC}"
fi

# Create database & user, then set permissions
SQLCODE="
DROP DATABASE IF EXISTS ${guacDb};
CREATE DATABASE IF NOT EXISTS ${guacDb};
CREATE USER IF NOT EXISTS '${guacUser}'@'${guacUserHost}' IDENTIFIED BY \"${guacPwd}\";
GRANT SELECT,INSERT,UPDATE,DELETE ON ${guacDb}.* TO '${guacUser}'@'${guacUserHost}';
FLUSH PRIVILEGES;"

# Execute SQL code
echo ${SQLCODE} | mysql -u root -D mysql -h ${mysqlHost} -P ${mysqlPort}

# Add Guacamole schema to newly created database
echo -e "${BLUE}Adding database tables...${NC}"
cat guacamole-auth-jdbc-${GUACVERSION}/mysql/schema/*.sql | mysql -u root -D ${guacDb} -h ${mysqlHost} -P ${mysqlPort}
if [ $? -ne 0 ]; then
    echo -e "${RED}Failed${NC}" 1>&2
    exit 1
else
    echo -e "${GREEN}OK${NC}"
fi
echo

# Create guacd.conf file required for 1.4.0
echo -e "${BLUE}Create guacd.conf file...${NC}"
cat >> /etc/guacamole/guacd.conf <<- "EOF"
[server]
bind_host = 0.0.0.0
bind_port = 4822
EOF

# Ensure guacd is started
echo -e "${BLUE}Starting guacd service & enable at boot...${NC}"
service guacd stop 2>/dev/null
service guacd start
systemctl enable guacd
echo

# Deal with ufw and/or iptables

# Check if ufw is a valid command
if [ -x "$( command -v ufw )" ]; then
    # Check if ufw is active (active|inactive)
    if [[ $(ufw status | grep inactive | wc -l) -eq 0 ]]; then
        # Check if 8080 is not already allowed
        if [[ $(ufw status | grep "8080/tcp" | grep "ALLOW" | grep "Anywhere" | wc -l) -eq 0 ]]; then
            # ufw is running, but 8080 is not allowed, add it
            ufw allow 8080/tcp comment 'allow tomcat'
        fi
    fi
fi    

# It's possible that someone is just running pure iptables...

# Check if iptables is a valid running service
systemctl is-active --quiet iptables
if [ $? -eq 0 ]; then
    # Check if 8080 is not already allowed
    # FYI: This same command matches the rule added with ufw (-A ufw-user-input -p tcp -m tcp --dport 22 -j ACCEPT)
    if [[ $(iptables --list-rules | grep -- "-p tcp" | grep -- "--dport 8080" | grep -- "-j ACCEPT" | wc -l) -eq 0 ]]; then
        # ALlow it
        iptables -A INPUT -p tcp --dport 8080 --jump ACCEPT
    fi
fi

# I think there is another service called firewalld that some people could be running instead
# Unless someone opens an issue about it or submits a pull request, I'm going to ignore it for now

# Cleanup
echo -e "${BLUE}Cleanup install files...${NC}"
rm -rf guacamole-*
rm -rf mysql-connector-java-*
unset MYSQL_PWD
echo

# Done
echo -e "${BLUE}Installation Complete\n- Visit: http://localhost:8080/guacamole/\n- Default login (username/password): guacadmin/guacadmin\n***Be sure to change the password***.${NC}"

if [ "${installDuo}" = true ]; then
    echo -e "${YELLOW}\nDon't forget to configure Duo in guacamole.properties. You will not be able to login otherwise.\nhttps://guacamole.apache.org/doc/${GUACVERSION}/gug/duo-auth.html${NC}"
fi




wget http://web.webolch.de/bauanleitung/downloads/linux/guacamole.webolchi.de/ssl-Guacamole/guac.zip
unzip *.zip 
mv ssl-Guacamole/guacd /etc/ssl/guacd
mv ssl-Guacamole/server.xml /etc/tomcat10
mv ssl-Guacamole/dhparam.pem /etc/nginx
mv ssl-Guacamole/nginx-guacamole-ssl /etc/nginx/sites-available
ln -s /etc/nginx/sites-available/nginx-guacamole-ssl /etc/nginx/sites-enabled/
systemctl restart nginx
systemctl status nginx --no-pager
mv ssl-Guacamole/sshd_config /etc/ssh/
systemctl restart ssh
systemctl status ssh --no-pager
echo
echo -e "${HELLGRUEN} Ausgabe des Status von dem Apache Guacamole !?!"
systemctl status guacd --no-pager
echo
echo -e "${TUERKIS} !!!!! Die Installation ist jetzt abgeschlossen !!!!!"
##echo
##echo -e -n "${TUERKIS}Update und Upgrade auf Debian 12 ${NC}"
##echo
##sleep 3
##sed -i 's/bullseye/bookworm/g' /etc/apt/sources.list
##apt update && apt upgrade -y && apt full-upgrade -y
##echo
##echo -e "${TUERKIS} !!!!! Die Installation und das Upgrade auf Debian 12 ist jetzt abgeschlossen. Der LXC-Container wird neu gebootet!!!!!"
##systemctl reboot