#!/bin/bash

# Update admin user password with Argon2id hash
# This is needed after implementing password hashing

set -e

DB_HOST="${CALYPSO_DB_HOST:-localhost}"
DB_PORT="${CALYPSO_DB_PORT:-5432}"
DB_USER="${CALYPSO_DB_USER:-calypso}"
DB_NAME="${CALYPSO_DB_NAME:-calypso}"
DB_PASSWORD="${CALYPSO_DB_PASSWORD:-calypso123}"
ADMIN_USER="${ADMIN_USER:-admin}"
ADMIN_PASS="${ADMIN_PASS:-admin123}"

echo "Updating admin user password with Argon2id hash..."

# Create a temporary Go program to hash the password
cat > /tmp/hash-password.go << 'EOF'
package main

import (
	"fmt"
	"os"
	"github.com/atlasos/calypso/internal/common/config"
	"github.com/atlasos/calypso/internal/common/password"
)

func main() {
	if len(os.Args) < 2 {
		fmt.Fprintf(os.Stderr, "Usage: %s <password>\n", os.Args[0])
		os.Exit(1)
	}
	
	pwd := os.Args[1]
	params := config.Argon2Params{
		Memory:      64 * 1024,
		Iterations:  3,
		Parallelism: 4,
		SaltLength:  16,
		KeyLength:   32,
	}
	
	hash, err := password.HashPassword(pwd, params)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
		os.Exit(1)
	}
	
	fmt.Println(hash)
}
EOF

cd /development/calypso/backend
HASH=$(go run /tmp/hash-password.go "$ADMIN_PASS" 2>/dev/null)

if [ -z "$HASH" ]; then
    echo "Failed to generate password hash"
    exit 1
fi

echo "Generated hash: ${HASH:0:50}..."

# Update database
PGPASSWORD="$DB_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" << EOF
UPDATE users 
SET password_hash = '$HASH', updated_at = NOW()
WHERE username = '$ADMIN_USER';
SELECT username, LEFT(password_hash, 50) as hash_preview FROM users WHERE username = '$ADMIN_USER';
EOF

echo ""
echo "Admin password updated successfully!"
echo "You can now login with username: $ADMIN_USER"

