#!/bin/sh
cd "$(dirname "$0")" || exit

[ "$1" = "" ] && {
  cat <<EOF

Run a CGI outside the webserver straight from the terminal.

Example:

  \$ sh $0 "apchk.cgi/actor?id=https://example.com/users/alice"

Better would be:

  # \$ sh $0 "https://example.com/apchk.cgi/actor?id=https://example.com/users/alice"

EOF
  exit
}

pre="$(echo "$1" | cut -d '?' -f 1)"
QUERY_STRING="$(echo "$1" | cut -d '?' -f 2)"
PATH_INFO="/$(echo "$pre" | cut -d '/' -f 2)"
cgi="$(echo "$pre" | cut -d '/' -f 1)"
SCRIPT_NAME="/$cgi"

[ -x "$cgi" ] || {
  echo "not executable: $1" 1>&2 ; exit 1
}

export HTTPS="on"
export PATH_INFO
export QUERY_STRING
export REMOTE_ADDR="127.0.0.1"
export REQUEST_METHOD="GET"
export SCRIPT_NAME
export SERVER_NAME="127.0.0.1"
export SERVER_PORT="443"

./"$cgi"
