#!/command/with-contenv bash

cd /app/smtp

# Get verbosity level (0=minimal, 1=normal, 2=verbose)
VERBOSITY="${ALIASVAULT_VERBOSITY:-0}"

# Read PostgreSQL password from file
POSTGRES_PASSWORD=$(cat /secrets/postgres_password)

# Wait for PostgreSQL to be ready
if [ "$VERBOSITY" -ge 1 ]; then
    echo "[smtp] Waiting for PostgreSQL to be ready..."
fi

for i in {1..30}; do
    if PGPASSWORD="$POSTGRES_PASSWORD" /usr/lib/postgresql/16/bin/psql -h localhost -U aliasvault -d aliasvault -c "SELECT 1;" >/dev/null 2>&1; then
        if [ "$VERBOSITY" -ge 1 ]; then
            echo "[smtp] PostgreSQL ready, starting SMTP..."
        fi
        break
    fi
    if [ $i -eq 30 ]; then
        echo "[smtp] Timeout waiting for PostgreSQL"
        exit 1
    fi
    sleep 2
done

export PRIVATE_EMAIL_DOMAINS="${PRIVATE_EMAIL_DOMAINS:-}"
export HIDDEN_PRIVATE_EMAIL_DOMAINS="${HIDDEN_PRIVATE_EMAIL_DOMAINS:-}"
export SMTP_TLS_ENABLED="${SMTP_TLS_ENABLED:-false}"

# Set .NET logging level based on verbosity
if [ "$VERBOSITY" -ge 2 ]; then
    export Logging__LogLevel__Default="Information"
elif [ "$VERBOSITY" -ge 1 ]; then
    export Logging__LogLevel__Default="Warning"
    export Logging__LogLevel__Microsoft__Hosting__Lifetime="Warning"
else
    export Logging__LogLevel__Default="Error"
    export Logging__LogLevel__Microsoft__Hosting__Lifetime="Error"
    export Logging__LogLevel__Microsoft="Error"
fi

echo "Starting SMTP service..."

exec dotnet AliasVault.SmtpService.dll