#!/bin/bash

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

    # Extract token from query string
    TOKEN=$(echo "$QUERY_STRING" | sed -n 's/^.*token=\([^&]*\).*$/\1/p')

    # Check if the token exists and is valid (not expired)
    DB_PATH="/var/lib/monotreme/data/monotreme.db"
    VALID_TOKEN=$(sqlite3 $DB_PATH "SELECT COUNT(*) FROM users WHERE reset_token='$TOKEN' AND reset_expires > strftime('%s','now');")

    if [ "$VALID_TOKEN" -eq 0 ]; then
        cat <<EOF
    <html>
    <head><title>Invalid Token</title></head>
    <body>
    <h1>Invalid or expired token!</h1>
    <a href="/login/forgot/">Request a new reset link</a>
    </body>
    </html>
    EOF
        exit 1
    fi

    # Display reset form
    cat <<EOF
    <html>
    <head><title>Reset Your Password</title></head>
    <body>
    <h1>Reset Your Password</h1>
    <form action="/cgi-bin/reset_password_confirm.cgi" method="post">
        <input type="hidden" name="token" value="$TOKEN">   
        <label for="password">New Password:</label>
        <input type="password" id="password" name="password" required>
        <br>
        <label for="confirm_password">Confirm Password:</label>
        <input type="password" id="confirm_password" name="confirm_password" required>
        <br>
        <input type="submit" value="Reset Password">
    </form>
    </body>
    </html>
    EOF