#!/bin/bash

echo "Content-type: text/html"
echo ""

# Log the raw POST data for debugging
read POST_DATA

# Parse the form data
TOKEN=""
PASSWORD=""
CONFIRM_PASSWORD=""

IFS='&' # Split fields by "&"
for param in $POST_DATA; do
    IFS='=' read -r key value <<< "$param"
    key=$(urldecode "$key")
    value=$(urldecode "$value")
    
    case $key in
        token) TOKEN="$value" ;;
        password) PASSWORD="$value" ;;
        confirm_password) CONFIRM_PASSWORD="$value" ;;
    esac
done

# Check if passwords match
if [ "$PASSWORD" != "$CONFIRM_PASSWORD" ]; then
    cat <<EOF
<html>
<head><title>Password Reset Failed</title></head>
<body>
<h1>Passwords do not match!</h1>
<a href="/login/reset_password.cgi?token=$TOKEN">Try again</a>
</body>
</html>
EOF
    exit 1
fi

# Hash the password
PASSWORD_HASH=$(echo -n "$PASSWORD" | sha256sum | awk '{print $1}')

# Update the user's password and remove the reset token
DB_PATH="/var/lib/monotreme/data/monotreme.db"
sqlite3 $DB_PATH "UPDATE users SET password_hash='$PASSWORD_HASH', reset_token=NULL, reset_expires=NULL WHERE reset_token='$TOKEN';"

# Confirmation
cat <<EOF
<html>
<head><title>Password Reset Successful</title></head>
<body>
<h1>Your password has been reset!</h1>
<a href="/login/">Go to login page</a>
</body>
</html>
EOF