#!/bin/bash

set -e

echo "Starting Healthchecks Cloudron package..."

# Database connection from Cloudron
DB_NAME=${CLOUDRON_POSTGRESQL_DATABASE:-healthchecks}
DB_USER=${CLOUDRON_POSTGRESQL_USERNAME:-hc}
DB_PASSWORD=${CLOUDRON_POSTGRESQL_PASSWORD}
DB_HOST=${CLOUDRON_POSTGRESQL_HOST:-127.0.0.1}
DB_PORT=${CLOUDRON_POSTGRESQL_PORT:-5432}

echo "Database host: $DB_HOST"
echo "Database port: $DB_PORT"
echo "Database name: $DB_NAME"

# Wait for PostgreSQL to be ready
echo "Waiting for PostgreSQL to be ready..."
until PGPASSWORD=$DB_PASSWORD psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -c '\q' 2>/dev/null; do
  echo "PostgreSQL is unavailable - sleeping"
  sleep 2
done

echo "PostgreSQL is ready!"

# Django configuration
export DEBUG=False
export SECRET_KEY=${SECRET_KEY:-cloudron-secret-key-change-in-production}
export ALLOWED_HOSTS=${ALLOWED_HOSTS:-'*'}
export SITE_ROOT=${SITE_ROOT:-https://$CLOUDRON_APP_DOMAIN}
export EMAIL_HOST=${EMAIL_HOST:-}
export EMAIL_PORT=${EMAIL_PORT:-587}
export EMAIL_HOST_USER=${EMAIL_HOST_USER:-}
export EMAIL_HOST_PASSWORD=${EMAIL_HOST_PASSWORD:-}
export EMAIL_USE_TLS=${EMAIL_USE_TLS:-True}
export DEFAULT_FROM_EMAIL=${DEFAULT_FROM_EMAIL:-healthchecks@$CLOUDRON_APP_DOMAIN}

# Database configuration
export DB=postgresql
export DB_HOST=$DB_HOST
export DB_NAME=$DB_NAME
export DB_USER=$DB_USER
export DB_PASSWORD=$DB_PASSWORD
export DB_PORT=$DB_PORT
export DB_CONN_MAX_AGE=60

# Run Django migrations
echo "Running Django migrations..."
python /opt/healthchecks/manage.py migrate --noinput

# Collect static files
echo "Collecting static files..."
python /opt/healthchecks/manage.py collectstatic --noinput

# Create superuser if specified
if [ -n "$SUPERUSER_EMAIL" ] && [ -n "$SUPERUSER_PASSWORD" ]; then
  echo "Creating superuser..."
  echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('$SUPERUSER_EMAIL', '', '$SUPERUSER_PASSWORD')" | \
    python /opt/healthchecks/manage.py shell || echo "Superuser may already exist"
fi

# Start Healthchecks
echo "Starting Healthchecks..."
exec uwsgi /opt/healthchecks/docker/uwsgi.ini
