# Create a local file with the PostgreSQL installation script
resource "local_file" "postgres_install_script" {
  filename = "${path.module}/tmp/install_postgres.sh"
  content  = <<-EOT
#!/bin/bash
set -e

echo "Checking PostgreSQL installation..."
sudo apt-get update
sudo apt-get install -y postgresql-14 postgresql-client-14 postgresql-contrib-14

# Stop PostgreSQL before configuration
echo "Stopping PostgreSQL service..."
sudo systemctl stop postgresql

# Configure PostgreSQL data directory
POSTGRES_DATA_DIR="/mnt/k8s/postgres"
POSTGRES_VERSION=14  # Hardcoding to version 14 as that's what's installed
POSTGRES_CONF_DIR="/etc/postgresql/$POSTGRES_VERSION/main"

echo "PostgreSQL version: $POSTGRES_VERSION"
echo "Config directory: $POSTGRES_CONF_DIR"

# # Clean up and create new data directory
# echo "Setting up fresh data directory..."
# sudo rm -rf "$POSTGRES_DATA_DIR"
# sudo mkdir -p "$POSTGRES_DATA_DIR"

# Set initial permissions
echo "Setting initial permissions on $POSTGRES_DATA_DIR"
sudo chown postgres:postgres "$POSTGRES_DATA_DIR"
sudo chmod 700 "$POSTGRES_DATA_DIR"

# Initialize PostgreSQL cluster
echo "Initializing new PostgreSQL cluster..."
sudo -u postgres /usr/lib/postgresql/$POSTGRES_VERSION/bin/initdb -D "$POSTGRES_DATA_DIR"

# Configure PostgreSQL to listen only on loopback and the LAN address.
echo "Configuring postgresql.conf..."
echo "listen_addresses = 'localhost,192.168.1.2'" | sudo -u postgres tee -a "$POSTGRES_DATA_DIR/postgresql.conf"

# Configure remote access for LAN clients and K3S pods only.
echo "Configuring pg_hba.conf..."
sudo -u postgres tee -a "$POSTGRES_DATA_DIR/pg_hba.conf" > /dev/null << 'EOF'
host    all             all             192.168.1.0/24          md5
host    all             all             10.42.0.0/16            md5
EOF

# Update system service configuration
echo "Updating system service configuration..."
sudo sed -i "s|^data_directory.*|data_directory = '$POSTGRES_DATA_DIR'|" "$POSTGRES_CONF_DIR/postgresql.conf"

# Start PostgreSQL
echo "Starting PostgreSQL service..."
sudo systemctl start postgresql
sleep 5
sudo systemctl status postgresql --no-pager || true

# Set password for postgres user
echo "Setting password for postgres user..."
sudo -u postgres psql -c "ALTER USER postgres PASSWORD 'postgres';"

# Verify PostgreSQL is running and accessible
echo "Checking PostgreSQL status..."
sudo -u postgres psql -c "\l"
echo "PostgreSQL installation completed!"
EOT

  file_permission = "0755"
}

# Create the scripts directory if it doesn't exist
resource "null_resource" "create_scripts_dir_postgres" {
  provisioner "local-exec" {
    command = "mkdir -p ${path.module}/scripts"
  }
}

# Upload and execute the PostgreSQL installation script
resource "ssh_resource" "postgres_install" {
  depends_on = [local_file.postgres_install_script, null_resource.create_scripts_dir_postgres]

  host        = local.ssh_host
  user        = local.ssh_user
  port        = local.ssh_port
  private_key = local.ssh_private_key
  timeout     = "4m"

  when = "create"

  file {
    source      = local_file.postgres_install_script.filename
    destination = "/tmp/install_postgres.sh"
    permissions = "0755"
  }

  commands = [
    "bash /tmp/install_postgres.sh"
  ]
}
