#!/bin/bash
###############################################################################
# Gitea Database Initialization Script
###############################################################################
# Creates a separate PostgreSQL database for Gitea git hosting.
#
# Database: gitea
# Purpose: Stores Gitea repositories, users, and configuration
# Runs: Automatically on first PostgreSQL container startup via docker-entrypoint-initdb.d
###############################################################################
set -e

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    -- Create Gitea database if it doesn't exist
    SELECT 'CREATE DATABASE gitea'
    WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'gitea')\gexec

    -- Grant all privileges to the main user
    GRANT ALL PRIVILEGES ON DATABASE gitea TO ${POSTGRES_USER};
EOSQL

echo "Gitea database 'gitea' created successfully"
