#!/usr/local/bin/bash

# --- 1. THE INPUT TRIGGER ---
# If the link with ?do=sign is clicked, force the input ba
if [ "$QUERY_STRING" = "do=sign" ]; then
    printf "10 Enter your message for the guestbook:\r\n"
    exit
fi

# --- 2. THE SAVING & ANTI-SPAM ---
if [ -n "$QUERY_STRING" ]; then
    # Decode URL characters (spaces, ?, !, etc.)
    CLEAN=$(echo "$QUERY_STRING" | tr '+' ' ' | sed 's/%20/ /g;s/%3F/?/g;s/%21/!/g;s/%2C/,/g;s/%27/'\''/g')
    NEW_ENTRY="$(date +%Y-%m-%d): $CLEAN"
    
    # Peek at the last line of the file to prevent refresh-spam
    LAST_ENTRY=$(tail -n 1 guestbook.txt 2>/dev/null)

    if [ "$NEW_ENTRY" != "$LAST_ENTRY" ]; then
        echo "$NEW_ENTRY" >> guestbook.txt
        SIGNED="true"
    else
        ALREADY_SIGNED="true"
    fi
fi

# --- 3. THE DISPLAY ---
# The double \r\n\r\n prevents the "hanging" bug
printf "20 text/gemini\r\n\r\n"
printf "# Hydraz's Guestbook\n\n"

if [ "$SIGNED" = "true" ]; then
    printf "> Thanks for signing!\n\n"
elif [ "$ALREADY_SIGNED" = "true" ]; then
    printf "> (Your message was already saved.)\n\n"
fi

printf "=> guestbook.sh?do=sign Click here to sign the guestbook\n\n"

printf "### Recent Signatures:\n"
if [ -f guestbook.txt ]; then
    # Shows newest at the top. If 'tac' fails, it uses 'tail', then 'cat'
    tac guestbook.txt || tail -r guestbook.txt || cat guestbook.txt
else
    printf "No entries yet. Be the first to sign!\n"
fi

printf "\n---\n"
printf "=> /~hydraz/ Back to Home\n"
