#!/usr/bin/env bash
# ==========================================================================
#     _   _ _ ____            ____          _____
#    | | | (_)  _ \ ___ _ __ / ___|___  _ _|_   _| __ __ _  ___ ___ _ __
#    | |_| | | |_) / _ \ '__| |   / _ \| '_ \| || '__/ _` |/ __/ _ \ '__|
#    |  _  | |  __/  __/ |  | |__| (_) | | | | || | | (_| | (_|  __/ |
#    |_| |_|_|_|   \___|_|   \____\___/|_| |_|_||_|  \__,_|\___\___|_|
#
#       ---  High-Performance Connectivity Tracer (HiPerConTracer)  ---
#                 https://www.nntb.no/~dreibh/hipercontracer/
# ==========================================================================
#
# High-Performance Connectivity Tracer (HiPerConTracer)
# Copyright (C) 2015-2025 by Thomas Dreibholz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: dreibh@simula.no

# Bash options:
set -eu


if [ $# -lt 2 ] ; then
   echo >&2 "Usage: $0 mariadb|mongodb|mysql|postgresql users.conf [--force-removal-without-confirmation]"
   exit 1
fi
if [ ! -e "$2" ] ; then
   echo >&2 "ERROR: Use configuration $2 does not exist!"
fi

DOMAIN="test.local"
DATABASE="just_a_test_database"
MAINTAINER_PASSWORD="!maintainer!"
IMPORTER_PASSWORD="!importer!"
RESEARCHER_PASSWORD="!researcher!"
CONFIG="$2"
if [ ! -e "${CONFIG}" ] ; then
   echo >&2 "ERROR: Use configuration $2 does not exist!"
fi
if [ $# -gt 2 ] ; then
   OPTION="$3"
else
   OPTION=""
fi
# shellcheck disable=SC1090
. "${CONFIG}"

if [ "${ROOT_PASSWORD}"       == "!root!"       ] || \
   [ "${MAINTAINER_PASSWORD}" == "!maintainer!" ] || \
   [ "${IMPORTER_PASSWORD}"   == "!importer!"   ] || \
   [ "${RESEARCHER_PASSWORD}" == "!researcher!" ] ; then
   echo >&2 "DO NOT USE THE EXAMPLE PASSWORDS!"
   exit 1
fi

if [ "${OPTION}" != "--force-removal-without-confirmation" ] ; then
   echo -n "WARNING: THIS SCRIPT WILL ERASE THE EXISTING DATABASES. To proceed, type \"I am sure!\": "
   read -er agree
   if [ "$agree" != "I am sure!" ] ; then
      echo "Exiting."
      exit
   fi
fi


# ###### MySQL/MariaDB ######################################################
if [ "$1" == "mysql" ] || [ "$1" == "mariadb" ] ; then
   # Documentation: https://www.digitalocean.com/community/tutorials/how-to-install-mariadb-on-ubuntu-22-04
   server="mariadb"

   echo -e "\x1b[34m$(date +"%F %H:%M:%S"): Preparing admin user for MySQL/MariaDB ...\x1b[0m"

   # ====== Create database =================================================
   echo -e "\x1b[33m$(date +"%F %H:%M:%S"): Creating database ...\x1b[0m"
   sed -e "s%\${DATABASE}%${DATABASE}%" \
       <../SQL/mariadb-database.sql | \
      tee | \
      mysql \
         --host="${server}.${DOMAIN}" \
         --port 3306 \
         --protocol=tcp \
         --ssl \
         --ssl-verify-server-cert \
         --ssl-ca=/etc/ssl/TestLevel1/certs/TestLevel1.crt \
         --ssl-crl=/etc/ssl/TestGlobal.crl \
         --user=root \
         --password="${ROOT_PASSWORD}"

   # ====== Create schema, views, functions and procedures ==================
   for item in functions procedures schema views ; do
      if [ -e ../SQL/mariadb-${item}.sql ] ; then
         echo -e "\x1b[33m$(date +"%F %H:%M:%S"): Creating ${item} ...\x1b[0m"
         mysql \
            --host="${server}.${DOMAIN}" \
            --port 3306 \
            --protocol=tcp \
            --ssl \
            --ssl-verify-server-cert \
            --ssl-ca=/etc/ssl/TestLevel1/certs/TestLevel1.crt \
            --ssl-crl=/etc/ssl/TestGlobal.crl \
            --user=root \
            --password="${ROOT_PASSWORD}" \
            --database="${DATABASE}" \
            <../SQL/mariadb-${item}.sql
      fi
   done

   # ====== Create users and roles ==========================================
   echo -e "\x1b[33m$(date +"%F %H:%M:%S"): Creating users and roles ...\x1b[0m"
   sed -e "s%\${DATABASE}%${DATABASE}%" \
       -e "s%\${ROOT_PASSWORD}%${ROOT_PASSWORD}%" \
       -e "s%\${MAINTAINER_PASSWORD}%${MAINTAINER_PASSWORD}%" \
       -e "s%\${RESEARCHER_PASSWORD}%${RESEARCHER_PASSWORD}%" \
       -e "s%\${IMPORTER_PASSWORD}%${IMPORTER_PASSWORD}%" \
       <../SQL/mariadb-users.sql | \
      tee | \
      mysql \
      --host="${server}.${DOMAIN}" \
      --port 3306 \
      --protocol=tcp \
      --ssl \
      --ssl-verify-server-cert \
      --ssl-ca=/etc/ssl/TestLevel1/certs/TestLevel1.crt \
      --ssl-crl=/etc/ssl/TestGlobal.crl \
      --user=root \
      --password="${ROOT_PASSWORD}" \
      --database="${DATABASE}"


# ###### PostgreSQL #########################################################
elif [ "$1" == "postgresql" ] ; then
   # Documentation: https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-22-04-quickstart
   server="postgresql"

   echo -e "\x1b[34m$(date +"%F %H:%M:%S"): Preparing admin user for PostgreSQL ...\x1b[0m"

   # ====== Create database =================================================
   echo -e "\x1b[33m$(date +"%F %H:%M:%S"): Creating database ...\x1b[0m"
   sed -e "s%\${DATABASE}%${DATABASE}%" \
       <../SQL/postgresql-database.sql | \
      tee | \
      sudo -u postgres psql

   # ====== Create schema, views, functions and procedures ==================
   for item in functions procedures schema views ; do
      if [ -e ../SQL/postgresql-${item}.sql ] ; then
         echo -e "\x1b[33m$(date +"%F %H:%M:%S"): Creating ${item} ...\x1b[0m"
         # shellcheck disable=SC2024
         sudo -u postgres psql -d "${DATABASE}" <../SQL/postgresql-${item}.sql
      fi
   done

   # ====== Create users and roles ==========================================
   echo -e "\x1b[33m$(date +"%F %H:%M:%S"): Creating users and roles ...\x1b[0m"
   sed -e "s%\${DATABASE}%${DATABASE}%" \
       -e "s%\${ROOT_PASSWORD}%${ROOT_PASSWORD}%" \
       -e "s%\${MAINTAINER_PASSWORD}%${MAINTAINER_PASSWORD}%" \
       -e "s%\${RESEARCHER_PASSWORD}%${RESEARCHER_PASSWORD}%" \
       -e "s%\${IMPORTER_PASSWORD}%${IMPORTER_PASSWORD}%" \
       <../SQL/postgresql-users.sql | \
      tee | \
      sudo -u postgres psql -d "${DATABASE}"


# ###### MongoDB ############################################################
elif [ "$1" == "mongodb" ] ; then
   # Documentation: https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-ubuntu/
   server="mongodb"

   echo -e "\x1b[34m$(date +"%F %H:%M:%S"): Preparing admin user for MongoDB ...\x1b[0m"

   # ====== Create database =================================================
   echo -e "\x1b[33m$(date +"%F %H:%M:%S"): Creating database ...\x1b[0m"
   sed -e "s%\${DATABASE}%${DATABASE}%" \
       <../NoSQL/mongodb-database.ms | \
      tee | \
      mongosh \
         "mongodb://${server}.${DOMAIN}:27017" \
         --tls \
         --tlsDisabledProtocols TLS1_0,TLS1_1,TLS1_2 \
         --tlsCAFile /etc/ssl/TestLevel1/certs/TestLevel1.crt \
         --username root --password "${ROOT_PASSWORD}" \
         --quiet

      # --tlsCertificateKeyFile /etc/ssl/root@mongodb.domain.test/root@mongodb.domain.test-chain+key.pem \

   # ====== Create schema ===================================================
   echo -e "\x1b[33m$(date +"%F %H:%M:%S"): Creating schema ...\x1b[0m"
   sed -e "s%\${DATABASE}%${DATABASE}%" \
       <../NoSQL/mongodb-schema.ms | \
      tee | \
      mongosh \
         "mongodb://${server}.${DOMAIN}:27017" \
         --tls \
         --tlsDisabledProtocols TLS1_0,TLS1_1,TLS1_2 \
         --tlsCAFile /etc/ssl/TestLevel1/certs/TestLevel1.crt \
         --username root --password "${ROOT_PASSWORD}" \
         --quiet

   # ====== Create users and roles ==========================================
   echo -e "\x1b[33m$(date +"%F %H:%M:%S"): Creating user and roles ...\x1b[0m"
   sed -e "s%\${DATABASE}%${DATABASE}%" \
       -e "s%\${MAINTAINER_PASSWORD}%${MAINTAINER_PASSWORD}%" \
       -e "s%\${RESEARCHER_PASSWORD}%${RESEARCHER_PASSWORD}%" \
       -e "s%\${IMPORTER_PASSWORD}%${IMPORTER_PASSWORD}%" \
       <../NoSQL/mongodb-users.ms | \
      tee | \
      mongosh \
         "mongodb://${server}.${DOMAIN}:27017" \
         --tls \
         --tlsDisabledProtocols TLS1_0,TLS1_1,TLS1_2 \
         --tlsCAFile /etc/ssl/TestLevel1/certs/TestLevel1.crt \
         --username root --password "${ROOT_PASSWORD}" \
         --quiet
   echo ""


# ###### Error ##############################################################
else
   echo >&2 "ERROR: Unsupported database: $1"
   exit 1
fi
