#!/command/with-contenv bash

# 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 "[client] 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 "[client] PostgreSQL ready, starting client..."
        fi
        break
    fi
    if [ $i -eq 30 ]; then
        echo "[client] Timeout waiting for PostgreSQL"
        exit 1
    fi
    sleep 2
done

# Client service entrypoint
DEFAULT_PRIVATE_EMAIL_DOMAINS=""
DEFAULT_HIDDEN_PRIVATE_EMAIL_DOMAINS=""
DEFAULT_SUPPORT_EMAIL=""
PRIVATE_EMAIL_DOMAINS=${PRIVATE_EMAIL_DOMAINS:-$DEFAULT_PRIVATE_EMAIL_DOMAINS}
HIDDEN_PRIVATE_EMAIL_DOMAINS=${HIDDEN_PRIVATE_EMAIL_DOMAINS:-$DEFAULT_HIDDEN_PRIVATE_EMAIL_DOMAINS}
SUPPORT_EMAIL=${SUPPORT_EMAIL:-$DEFAULT_SUPPORT_EMAIL}
PUBLIC_REGISTRATION_ENABLED=${PUBLIC_REGISTRATION_ENABLED:-true}

mkdir -p /etc/nginx/ssl

if [ ! -f /etc/nginx/ssl/nginx.crt ] || [ ! -f /etc/nginx/ssl/nginx.key ]; then
    if [ "$VERBOSITY" -ge 2 ]; then
        openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \
            -keyout /etc/nginx/ssl/nginx.key \
            -out /etc/nginx/ssl/nginx.crt \
            -subj "/C=US/ST=State/L=City/O=Organization/CN=localhost"
    else
        openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \
            -keyout /etc/nginx/ssl/nginx.key \
            -out /etc/nginx/ssl/nginx.crt \
            -subj "/C=US/ST=State/L=City/O=Organization/CN=localhost" >/dev/null 2>&1
    fi
    chmod 644 /etc/nginx/ssl/nginx.crt
    chmod 600 /etc/nginx/ssl/nginx.key
fi

# Convert comma-separated PRIVATE_EMAIL_DOMAINS to JSON array
if [ -z "$PRIVATE_EMAIL_DOMAINS" ]; then
    json_array="[]"
else
    # Convert comma-separated list to JSON array
    json_array=$(echo "$PRIVATE_EMAIL_DOMAINS" | awk '{split($0,a,","); printf "["; for(i=1;i<=length(a);i++) {printf "\"%s\"", a[i]; if(i<length(a)) printf ","} printf "]"}')
fi

# Convert comma-separated HIDDEN_PRIVATE_EMAIL_DOMAINS to JSON array
if [ -z "$HIDDEN_PRIVATE_EMAIL_DOMAINS" ]; then
    hidden_json_array="[]"
else
    # Convert comma-separated list to JSON array
    hidden_json_array=$(echo "$HIDDEN_PRIVATE_EMAIL_DOMAINS" | awk '{split($0,a,","); printf "["; for(i=1;i<=length(a);i++) {printf "\"%s\"", a[i]; if(i<length(a)) printf ","} printf "]"}')
fi

# Create JSON with environment variables
cat > /app/client/wwwroot/appsettings.json << EOF
{
    "PrivateEmailDomains": $json_array,
    "HiddenPrivateEmailDomains": $hidden_json_array,
    "SupportEmail": "$SUPPORT_EMAIL",
    "PublicRegistrationEnabled": "$PUBLIC_REGISTRATION_ENABLED"
}
EOF

sed -i "s|/usr/share/nginx/html|/app/client/wwwroot|g" /app/client/nginx.conf

echo "Starting Client service..."

# Set nginx error log level based on verbosity
if [ "$VERBOSITY" -ge 2 ]; then
    # Verbose: info level
    exec nginx -c /app/client/nginx.conf -g "daemon off; error_log /dev/stderr info;"
elif [ "$VERBOSITY" -ge 1 ]; then
    # Normal: warn level
    exec nginx -c /app/client/nginx.conf -g "daemon off; error_log /dev/stderr warn;"
else
    # Minimal: error level only
    exec nginx -c /app/client/nginx.conf -g "daemon off; error_log /dev/stderr error;"
fi