#!/bin/bash
# Automatically complete Authentik initial setup

set -euo pipefail

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Configuration
DOMAIN=${DOMAIN:-local}
AUTHENTIK_URL="https://auth.${DOMAIN}"
ADMIN_EMAIL="admin@local.lan"
ADMIN_PASSWORD="${AUTHENTIK_ADMIN_PASSWORD:-admin123}"

echo -e "${BLUE}🤖 Automatically completing Authentik initial setup...${NC}"
echo

# Function to complete initial setup
complete_initial_setup() {
    local host
    host=$(echo "$AUTHENTIK_URL" | sed -E 's#^https?://([^/]+).*$#\1#')
    local resolve=(--resolve "${host}:443:127.0.0.1")

    echo -e "${YELLOW}📋 Completing initial setup form...${NC}"

    # Get the initial setup page and extract CSRF token
    local setup_page
    setup_page=$(curl -ks "${resolve[@]}" -c /tmp/authentik_setup_cookies.txt "$AUTHENTIK_URL/if/flow/initial-setup/" || echo "")

    if [ -z "$setup_page" ]; then
        echo -e "${RED}❌ Could not access setup page${NC}"
        return 1
    fi

    # Extract CSRF token
    local csrf_token
    csrf_token=$(echo "$setup_page" | grep -o 'csrfmiddlewaretoken[^>]*value="[^"]*"' | sed 's/.*value="\([^"]*\)".*/\1/' | head -1 || echo "")

    if [ -z "$csrf_token" ]; then
        echo -e "${RED}❌ Could not extract CSRF token${NC}"
        return 1
    fi

    echo -e "${GREEN}✅ CSRF token extracted${NC}"

    # Submit the initial setup form
    local setup_response
    setup_response=$(curl -ks "${resolve[@]}" -b /tmp/authentik_setup_cookies.txt -c /tmp/authentik_setup_cookies.txt \
        -X POST "$AUTHENTIK_URL/if/flow/initial-setup/" \
        -H "Content-Type: application/x-www-form-urlencoded" \
        -H "Referer: $AUTHENTIK_URL/if/flow/initial-setup/" \
        -d "csrfmiddlewaretoken=$csrf_token&email=$ADMIN_EMAIL&password=$ADMIN_PASSWORD&password_repeat=$ADMIN_PASSWORD" \
        -w '%{http_code}' -o /tmp/setup_response.html || echo "")

    if [[ "$setup_response" =~ ^(200|302)$ ]]; then
        echo -e "${GREEN}✅ Initial setup completed successfully${NC}"

        # Wait a moment for setup to complete
        sleep 3

        # Verify setup is complete by checking if setup page returns 404
        local verify_code
        verify_code=$(curl -ks "${resolve[@]}" -o /dev/null -w '%{http_code}' "$AUTHENTIK_URL/if/flow/initial-setup/" || true)

        if [[ "$verify_code" == "404" ]]; then
            echo -e "${GREEN}✅ Setup verification successful${NC}"
            return 0
        else
            echo -e "${YELLOW}⚠️  Setup may not be complete (verification returned $verify_code)${NC}"
            return 1
        fi
    else
        echo -e "${RED}❌ Setup failed (HTTP $setup_response)${NC}"
        return 1
    fi
}

# Function to check if setup is needed
check_setup_needed() {
    local host
    host=$(echo "$AUTHENTIK_URL" | sed -E 's#^https?://([^/]+).*$#\1#')
    local resolve=(--resolve "${host}:443:127.0.0.1")
    local setup_code
    setup_code=$(curl -ks "${resolve[@]}" -o /dev/null -w '%{http_code}' "$AUTHENTIK_URL/if/flow/initial-setup/" || true)

    #TODO: this is not a valid check if setup is already complete, needs work. Authentik returns 200 even if setup is complete
    if [[ "$setup_code" == "200" ]]; then
        return 0  # Setup is needed
    else
        return 1  # Setup is not needed
    fi
}

# Main function
main() {
    if check_setup_needed; then
        echo -e "${YELLOW}📋 Initial setup is required${NC}"

        if complete_initial_setup; then
            echo -e "${GREEN}🎉 Authentik initial setup completed automatically!${NC}"
            echo
            echo -e "${BLUE}📋 Next steps:${NC}"
            echo -e "  1. Run ${BLUE}make complete-authentik-setup${NC} to get API token"
            echo -e "  2. Run ${BLUE}make setup-authentik${NC} to import blueprint configuration"
            echo -e "  3. Or run ${BLUE}make setup-sso${NC} to do both automatically"
        else
            echo -e "${RED}❌ Automatic setup failed${NC}"
            echo -e "${YELLOW}📋 Manual setup required:${NC}"
            echo -e "  1. Open ${BLUE}https://auth.local.lan.lan/if/flow/initial-setup/${NC}"
            echo -e "  2. Use credentials: ${BLUE}$ADMIN_EMAIL${NC} / ${BLUE}$ADMIN_PASSWORD${NC}"
        fi
    else
        echo -e "${GREEN}✅ Authentik setup is already complete${NC}"
    fi

    # Cleanup
    rm -f /tmp/authentik_setup_cookies.txt /tmp/setup_response.html
}

# Run main function
main "$@"
