#!/bin/bash

# WHP User Password Reset Script
# Resets and re-encrypts a user's password if encryption fails

set -e

KEY_FILE="/etc/whp/encryption.key"

echo "🔐 WHP User Password Reset"
echo "========================="

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

# Check if encryption key exists
if [ ! -f "$KEY_FILE" ]; then
    echo "❌ Encryption key not found: $KEY_FILE"
    echo "   Run update-add-encryption.sh first"
    exit 1
fi

# Get username
if [ -z "$1" ]; then
    echo "Usage: $0 <username> [new_password]"
    echo ""
    echo "If new_password is not provided, you'll be prompted to enter it."
    echo ""
    echo "Available users:"
    mysql -N -e "SELECT username FROM whp.user_passwords ORDER BY username" | sed 's/^/   /'
    exit 1
fi

USERNAME="$1"
NEW_PASSWORD="$2"

# Verify user exists
USER_EXISTS=$(mysql -N -e "SELECT COUNT(*) FROM whp.user_passwords WHERE username = '$USERNAME'")
if [ "$USER_EXISTS" = "0" ]; then
    echo "❌ User '$USERNAME' not found in database"
    echo ""
    echo "Available users:"
    mysql -N -e "SELECT username FROM whp.user_passwords ORDER BY username" | sed 's/^/   /'
    exit 1
fi

# Get password if not provided
if [ -z "$NEW_PASSWORD" ]; then
    echo "Enter new password for $USERNAME:"
    read -s NEW_PASSWORD
    echo ""
    
    if [ -z "$NEW_PASSWORD" ]; then
        echo "❌ Password cannot be empty"
        exit 1
    fi
fi

echo "🔄 Resetting password for user: $USERNAME"

# Validate password strength (basic check)
if [ ${#NEW_PASSWORD} -lt 8 ]; then
    echo "⚠️  Warning: Password is less than 8 characters"
    echo -n "Continue anyway? (y/N): "
    read -r CONFIRM
    if [[ ! $CONFIRM =~ ^[Yy]$ ]]; then
        echo "❌ Password reset cancelled"
        exit 1
    fi
fi

# Step 1: Update system password
echo "📝 Updating system password..."
echo "$USERNAME:$NEW_PASSWORD" | chpasswd
if [ $? -eq 0 ]; then
    echo "✅ System password updated"
else
    echo "❌ Failed to update system password"
    exit 1
fi

# Step 2: Encrypt password using PHP
echo "🔐 Encrypting password for database storage..."
ENCRYPTED_PASSWORD=$(php -r "
    require_once('/docker/whp/web/libs/usermgmt.php');
    \$usermgmt = new usermgmt();
    \$reflection = new ReflectionClass(\$usermgmt);
    \$method = \$reflection->getMethod('encryptPassword');
    \$method->setAccessible(true);
    try {
        echo \$method->invoke(\$usermgmt, '$NEW_PASSWORD');
    } catch (Exception \$e) {
        echo 'ERROR: ' . \$e->getMessage();
        exit(1);
    }
")

if [[ $ENCRYPTED_PASSWORD == ERROR:* ]]; then
    echo "❌ Password encryption failed: ${ENCRYPTED_PASSWORD#ERROR: }"
    echo "   System password was updated but database password was not"
    echo "   User may experience login issues until this is resolved"
    exit 1
fi

# Step 3: Hash password for PAM authentication
echo "🔐 Generating password hash..."
PASSWORD_HASH=$(php -r "echo password_hash('$NEW_PASSWORD', PASSWORD_DEFAULT);")

# Step 4: Update database
echo "💾 Updating database..."
mysql -e "
    UPDATE whp.user_passwords 
    SET password_hash = '$PASSWORD_HASH', 
        mysql_password = '$ENCRYPTED_PASSWORD' 
    WHERE username = '$USERNAME'
"

if [ $? -eq 0 ]; then
    echo "✅ Database updated successfully"
else
    echo "❌ Database update failed"
    exit 1
fi

# Step 5: Update MySQL user password if exists
echo "🔄 Updating MySQL user password..."
MYSQL_USER_EXISTS=$(mysql -N -e "SELECT COUNT(*) FROM mysql.user WHERE User = '$USERNAME'")
if [ "$MYSQL_USER_EXISTS" -gt 0 ]; then
    mysql -e "ALTER USER '$USERNAME'@'%' IDENTIFIED BY '$NEW_PASSWORD'" 2>/dev/null || \
    mysql -e "SET PASSWORD FOR '$USERNAME'@'%' = PASSWORD('$NEW_PASSWORD')" 2>/dev/null || \
    echo "⚠️  MySQL password update failed (user may not have MySQL access)"
    
    if [ $? -eq 0 ]; then
        echo "✅ MySQL user password updated"
    fi
else
    echo "ℹ️  No MySQL user found for $USERNAME"
fi

# Step 6: Test decryption
echo "🧪 Testing password decryption..."
DECRYPTED_TEST=$(php -r "
    require_once('/docker/whp/web/libs/usermgmt.php');
    \$usermgmt = new usermgmt();
    \$reflection = new ReflectionClass(\$usermgmt);
    \$method = \$reflection->getMethod('decryptPassword');
    \$method->setAccessible(true);
    try {
        echo \$method->invoke(\$usermgmt, '$ENCRYPTED_PASSWORD');
    } catch (Exception \$e) {
        echo 'ERROR: ' . \$e->getMessage();
        exit(1);
    }
")

if [[ $DECRYPTED_TEST == ERROR:* ]]; then
    echo "❌ Decryption test failed: ${DECRYPTED_TEST#ERROR: }"
    echo "   Password was stored but may not be retrievable"
    exit 1
elif [ "$DECRYPTED_TEST" = "$NEW_PASSWORD" ]; then
    echo "✅ Encryption/decryption test passed"
else
    echo "❌ Decryption test failed: password mismatch"
    exit 1
fi

echo ""
echo "🎉 Password reset complete for user: $USERNAME"
echo ""
echo "✅ System password updated"
echo "✅ Database password encrypted and stored"
echo "✅ Password hash updated"
echo "✅ Encryption/decryption verified"
echo ""
echo "🔐 The user can now log in with the new password"