#!/bin/bash
# Reset Gitea password for mike@azcomputerguru.com
# Run this on Jupiter server (172.16.3.20) as root
# Note: Gitea runs in Docker container

echo "=== Gitea Password Reset (Docker) ==="
echo ""

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo "[ERROR] This script must be run as root"
    exit 1
fi

# Find Gitea Docker container
echo "[1] Finding Gitea Docker container..."
CONTAINER=$(docker ps --filter 'name=gitea' --format '{{.Names}}' | head -n 1)

if [ -z "$CONTAINER" ]; then
    echo "[ERROR] Cannot find Gitea container"
    echo ""
    echo "Available containers:"
    docker ps --format '{{.Names}}'
    exit 1
fi

echo "[OK] Found container: $CONTAINER"
echo ""

echo "[2] Current Gitea users:"
docker exec $CONTAINER gitea admin user list 2>/dev/null || \
    echo "[WARNING] Could not list users"

echo ""
echo "[3] Resetting password for: mike@azcomputerguru.com"
echo ""

# Prompt for new password
read -sp "Enter new password: " NEW_PASSWORD
echo ""
read -sp "Confirm password: " CONFIRM_PASSWORD
echo ""

if [ "$NEW_PASSWORD" != "$CONFIRM_PASSWORD" ]; then
    echo "[ERROR] Passwords do not match"
    exit 1
fi

if [ -z "$NEW_PASSWORD" ]; then
    echo "[ERROR] Password cannot be empty"
    exit 1
fi

echo ""
echo "[4] Executing password change..."

# Reset password using docker exec (try username 'mike' first, then email)
docker exec $CONTAINER gitea admin user change-password --username mike --password "$NEW_PASSWORD" 2>&1 || \
    docker exec $CONTAINER gitea admin user change-password --username mike@azcomputerguru.com --password "$NEW_PASSWORD" 2>&1

if [ $? -eq 0 ]; then
    echo ""
    echo "[SUCCESS] Password reset complete!"
    echo ""
    echo "You can now login at: https://git.azcomputerguru.com/"
    echo "Username: mike@azcomputerguru.com (or just 'mike')"
    echo "Password: (the one you just set)"
else
    echo ""
    echo "[ERROR] Password reset failed"
    echo "Try running manually with different username format"
fi
