#!/bin/sh
set -e

echo "🔧 Entrypoint: Ensuring .pgpass directory and file"

PGADMIN_HOME="/var/lib/pgadmin"
PGPASS_PATH="${PGADMIN_HOME}/pgpass"
SERVERS_JSON_PATH="/var/lib/pgadmin/servers.json"

# Ensure parent directory exists
mkdir -p "$PGADMIN_HOME"

# Create or overwrite .pgpass file
echo "${PGPASS_HOST}:${PGPASS_PORT}:${PGPASS_DB}:${PGPASS_USER}:${PGPASS_PASSWORD}" > "$PGPASS_PATH"
chmod 600 "$PGPASS_PATH"
chown 5050:5050 "$PGPASS_PATH"
export PGPASSFILE="$PGPASS_PATH"

echo "✅ .pgpass ready at $PGPASS_PATH"
echo "🛠️ Generating servers.json for pgAdmin..."

# Try to ensure /pgadmin4 is owned by 5050 if possible
if [ -d /pgadmin4 ]; then
  echo "🔧 Attempting to chown /pgadmin4 to 5050:5050"
  chown 5050:5050 /pgadmin4 2>/dev/null || echo "⚠️ Could not chown /pgadmin4 (likely read-only or permission issue)"
fi

cat <<EOF > "$SERVERS_JSON_PATH"
{
  "Servers": {
    "1": {
      "Name": "Phoenix DB",
      "Group": "PHX GROUP",
      "Host": "${PGPASS_HOST}",
      "Port": ${PGPASS_PORT},
      "MaintenanceDB": "${PGPASS_DB}",
      "Username": "${PGPASS_USER}",
      "SSLMode": "prefer",
      "PassFile": "$PGPASSFILE"
    }
  }
}
EOF

chmod 600 "$SERVERS_JSON_PATH"
chown 5050:5050 "$SERVERS_JSON_PATH"
echo "✅ servers.json created at $SERVERS_JSON_PATH"

exec /entrypoint.sh "$@"