#!/bin/bash
# Info: Script to create first Coder admin user
# Author: Provisioning System

set -e

CODER_USER=${CODER_USER:-admin}
CODER_EMAIL=${CODER_EMAIL:-admin@{{ coder.access_url | replace('http://', '') | replace('https://', '') }}}
CODER_PASSWORD=${CODER_PASSWORD:-$(openssl rand -base64 12)}

echo "Creating first Coder admin user..."

# Wait for Coder server to be ready
timeout=60
while [ $timeout -gt 0 ]; do
    if curl -f -s "{{ coder.access_url }}/api/v2/buildinfo" >/dev/null 2>&1; then
        echo "Coder server is ready"
        break
    fi
    echo "Waiting for Coder server to start... ($timeout seconds remaining)"
    sleep 2
    timeout=$((timeout - 2))
done

if [ $timeout -le 0 ]; then
    echo "Timeout waiting for Coder server to start"
    exit 1
fi

# Create first user via API
RESPONSE=$(curl -s -X POST "{{ coder.access_url }}/api/v2/users/first" \
    -H "Content-Type: application/json" \
    -d "{
        \"username\": \"$CODER_USER\",
        \"email\": \"$CODER_EMAIL\",
        \"password\": \"$CODER_PASSWORD\",
        \"trial\": false
    }")

if echo "$RESPONSE" | grep -q '"username"'; then
    echo "✅ First admin user created successfully!"
    echo "Username: $CODER_USER"
    echo "Email: $CODER_EMAIL"
    echo "Password: $CODER_PASSWORD"
    echo ""
    echo "Login at: {{ coder.access_url }}"
    
    # Save credentials to secure file
    echo "USERNAME=$CODER_USER" > {{ coder.config_path }}/admin-credentials
    echo "EMAIL=$CODER_EMAIL" >> {{ coder.config_path }}/admin-credentials
    echo "PASSWORD=$CODER_PASSWORD" >> {{ coder.config_path }}/admin-credentials
    chmod 600 {{ coder.config_path }}/admin-credentials
    chown {{ coder.run_user.name }}:{{ coder.run_user.group }} {{ coder.config_path }}/admin-credentials
    
    echo "Credentials saved to: {{ coder.config_path }}/admin-credentials"
else
    echo "❌ Failed to create first user"
    echo "Response: $RESPONSE"
    exit 1
fi