#!/usr/bin/env n0m $ #!/bin/bash Content-Type: text/html # Constants # ========= $ true=1; $ false=0; # $ restaurant_file="restaurants.txt"; $ title="FeedMe"; # # Components # ========== # # $1: string: input value # $2: number: 0=existing restaurant, 1=new restaurant $ restaurant_form () { $ enforce_arguments "${FUNCNAME[0]}" "$#" 2; $ local icon_class; $ if [ "$2" -eq 0 ]; then $ icon_class="ri-save-2-fill"; $ else $ icon_class="ri-add-line"; $ fi
$ if [ "$2" -eq 0 ]; then $ fi
$ } # # Utility Functions # ================= # # $1: string: function name # $2: number: $# # $3: number: expected number of arguments $ enforce_arguments () { $ if [ "$2" -lt "$3" ]; then $ printf '%s %s %s\n' 'Function:' "$1" 'called with too few arguments'; $ exit 1; $ elif [ "$2" -gt "$3" ]; then $ printf '%s %s %s\n' 'Function:' "$1" 'called with too many arguments'; $ exit 1; $ fi; $ } # $ decode_uri () { $ local i="${*//+/ }"; $ echo -e "${i//%/\\x}"; $ } # # # Restaurant List Functions # ========================= # # $1: string: restaurant to remove $ remove_restaurant () { $ enforce_arguments "${FUNCNAME[0]}" "$#" 1; $ grep -Fxv "$1" "$restaurant_file" | tee "$restaurant_file" >/dev/null; $ } # # $1: string: restuarant to add $ add_restaurant () { $ enforce_arguments "${FUNCNAME[0]}" "$#" 1; $ (grep -Fxv "$1" "$restaurant_file"; printf '%s\n' "$1") |\ $ tee "$restaurant_file" >/dev/null; $ } # # $1 (optional): number: 0=don't overwrite, 1=overwrite $ todays_restaurant () { $ local today; $ today="$(date +'%Y%m%d')"; $ local filename="$today.pick"; $ if [ -n "$1" ] && [ "$1" -ne 0 ]; then $ rm "$filename"; $ fi; $ if [ ! -f "$filename" ]; then $ shuf -n 1 "$restaurant_file" > "$filename"; $ fi; $ cat "$filename"; $ } # # Initialization # ============== # # Make sure restaurant file eixsts $ touch -a "$restaurant_file"; # # Parse body # ---------- $ declare -A body; $ while IFS= read -d '&' -r pair || [ "$pair" ]; do $ name=$(decode_uri "${pair%%=*}"); $ value=$(decode_uri "${pair#*=}"); $ if [ -n "$name" ]; then $ body["$name"]="$value"; $ fi; $ done #> # # Perform requested action # ------------------------ $ case "${body['action']}" in $ add) $ add_restaurant "${body['new']}"; $ ;; $ delete) $ remove_restaurant "${body['old']}"; $ ;; $ save) $ remove_restaurant "${body['old']}"; $ add_restaurant "${body['new']}"; $ ;; $ new_restaurant) $ todays_restaurant $true >/dev/null; $ ;; $ esac # # <% $title %>

<% $title %>

Today's Restaurant: <$% todays_restaurant %>