#!/bin/bash -e

# Configuration file for Tomcat database settings
CFG=/usr/share/tomcat/default/conf/intigua.properties

# Function to retrieve the major version of PostgreSQL installed on the system
function get_postgresql_version() {
  local version
  # Retrieve PostgreSQL version (e.g., "psql (PostgreSQL) 15.2")
  # Extract only the major version number (e.g., "15")
  version=$(psql -V | awk '{print $3}' | cut -d'.' -f1)
  echo "$version"
}

# Function to create the PostgreSQL database and user for JetPatch
function create_db() {
  echo "Setting up a PostgreSQL database for JetPatch"
  
  local tdir
  tdir=$(mktemp -d)  # Create a temporary directory to store the SQL file

  # Create the initial database setup script
  {
    echo 'CREATE DATABASE jetpatchdb;'
    echo "CREATE USER jetpatch WITH encrypted PASSWORD '$1';"
    echo 'GRANT ALL PRIVILEGES ON DATABASE jetpatchdb TO jetpatch;'
  } >"${tdir}"/init.sql

  # Retrieve the PostgreSQL major version
  local pg_version
  pg_version=$(get_postgresql_version)

  # If PostgreSQL version is 15 or higher, add extra SQL commands for schema privileges
  if [[ "$pg_version" -ge 15 ]]; then
    {
      echo '\c jetpatchdb;'
      echo 'GRANT ALL ON SCHEMA public TO jetpatch;'
      echo 'ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO jetpatch;'
    } >>"${tdir}"/init.sql
  fi

  # Ensure the PostgreSQL user owns the SQL file to avoid permission issues
  chown -R postgres "${tdir}"

  # Execute the SQL commands as the 'postgres' system user
  su postgres -c "/usr/bin/psql -f ${tdir}/init.sql"

  # Clean up by removing the temporary directory
  rm -rf "${tdir}"

  echo "Database setup complete."
}

# Function to configure Tomcat to use the local PostgreSQL database
function connect_tomcat() {
  echo "Configuring Tomcat to use the local PostgreSQL database"

  # Append database connection details to the Tomcat configuration file
  {
    echo ""
    echo "# DB config automatically created by intigua_ensure_db script:"
    echo "db.databasePlatform=org.eclipse.persistence.platform.database.PostgreSQLPlatform"
    echo "db.driver=org.postgresql.Driver"
    echo "db.url=jdbc:postgresql://localhost:5432/jetpatchdb"
    echo "db.username=jetpatch"
    echo "db.password=$1"
    echo "# End of auto-added DB configuration"
    echo ""
  } >>$CFG

  echo "Tomcat configuration completed."
}

# Function to create the database and configure Tomcat if the database is not already set up
function create_and_connect_local_db() {
  # Generate a random 24-character password for the database user
  local pwd
  pwd=$(cat /dev/urandom | tr -dc A-Za-z0-9 | head -c 24)

  # Call function to create the database with the generated password
  create_db "$pwd"

  # Call function to configure Tomcat with the same password
  connect_tomcat "$pwd"
}

# Main function to check if the database is already configured; if not, set it up
function main() {
  # Check if 'db.url' exists in the Tomcat config file. If not, set up the database.
  grep -q '^db.url=' $CFG 2>/dev/null || create_and_connect_local_db
}

# Execute the main function
main