#!/bin/bash
echo "Content-Type: text/html; charset=utf-8"
echo
echo "<html><head><style>"
echo "table { border-collapse: collapse }"
echo "td, th { border: 1px solid; padding: 4px }"
echo "th { background-color: lightyellow }"
echo "tr:nth-child(even) { background-color: #ccc }"
echo "</style>"
echo "<script>function del(r){"
echo "var tr=document.getElementsByTagName(\"table\")[0].rows[r];"
echo "document.getElementById(\"f\").first.value = tr.cells[0].innerText;"
echo "document.getElementById(\"f\").last.value = tr.cells[1].innerText;"
echo "document.getElementById(\"f\").add.checked = false;"
echo "}</script></head><body><h1>Table of Stored Names</h1>"
echo "<form id=\"f\" action=\"http://localhost/~sandiway/get3.cgi\" method=\"GET\">"
echo "First: <input type=\"text\" name="first" size=12>"
echo "Last:  <input type=\"text\" name="last" size=12>"
# checked: "on" as value
echo "Add: <input type=\"checkbox\" name=\"add\" checked>"
echo "<input type=\"submit\"></form>"
origIFS=$IFS
IFS='=&'
set -- $QUERY_STRING
IFS=$origIFS
# names.txt must exist and
# be write-able for everyone (www)!
if [ "$6" = 'on' ]; then
    if [ "$2" != '' ] && [ "$4" != '' ]; then
	echo "$2 $4" >> names.txt
    fi
else
    perl -i -ne "print unless m/^$2 $4$/" names.txt
fi
echo "<table><tr><th>First</th><th>Last</th><th></th></tr>"
i=1
while read -r first last
do
    echo "<tr><td>$first</td><td>$last</td><td><button onclick=\"del($i)\">Delete</button></td></tr>"
    ((i++))
done < names.txt
echo "</table>"
echo "</body></html>"
exit 0
