#!/bin/sh PROMPT='==' SHOW='show' cleanup () { rm -f "$TMPFILE"; } go () { printf '%s\r\n' "$1" | nc "$2" "$3" } usage() { printf '%s\n' \ 'usage:' \ ' visit a Gopher URL:' \ " $0 " \ ' init links:' \ " $0 -i" \ ' show this help:' \ " $0 -h" \ '' \ 'In a gopher page, just type:' \ " !./g % LINE" \ 'to visit the resource at LINE, or:' \ " !./d % LINE" \ 'to download the resource at LINE\n'\ " !./v URL" \ 'to visit a Gopher URL' exit 0 } goto_url(){ URL="$(echo "$1" | sed 's,gopher://,,g')" hostport=$(echo "$URL" | cut -d "/" -f 1) host="$(echo "$hostport" | cut -d ":" -f 1)" port="$(echo "$hostport" | cut -s -d ":" -f 2)" [ -z "$port" ] && port='70' type=$(echo "$URL" | cut -s -d "/" -f 2) [ -z "$type" ] && { type='1' sel="/" go "$sel" "$host" "$port" return } [ -n "${type#?}" ] && echo "Invalid Gopher URL" >&2 && exit 1 ## Check if type is a valid one type="$(echo $type | sed -n '/^[0-9ITghis+]$/p')" [ -z "${type}" ] && echo "Invalid Gopher URL" >&2 && exit 1 sel=/$(echo "$URL" | cut -s -d "/" -f 3-) go "$sel" "$host" "$port" } trap cleanup INT QUIT HUP ABRT TERM [ "$#" -lt 1 ] || [ "$1" = "-h" ] && usage script_name="$(basename "$0")" if [ "${script_name}" = "gophed" ] && [ "$1" = "-i" ]; then ln -sf "$0" g ln -sf "$0" d ln -sf "$0" v exit 0 fi if [ "$script_name" = "gophed" ] || [ "$script_name" = "v" ]; then sel="$(printf '%s' "$1" | sed -E 's:/:+:g')" TMPFILE="$(mktemp "/tmp/gophed_${2}_${sel}_$3.XXXXXXXXXXXXXXXXXXX")" goto_url "$1" > "$TMPFILE" while read -r line; do echo "$line"; done | ed -p "$PROMPT" "$TMPFILE" cleanup exit 0 fi if [ "$script_name" = "g" ] || [ "$script_name" = "d" ]; then LINE=$(awk "{if (NR == $2) print \$0;}" $1) RESOURCE="$(printf '%s' "$LINE" | cut -d ' ' -f 2)" HOST="$(printf '%s' "$LINE" | cut -d ' ' -f 3)" PORT="$(printf '%s' "$LINE" | awk -F ' ' '{ match($4,/[[:digit:]]+/); print substr($4,RSTART,RLENGTH) }')" if [ "$script_name" = "g" ]; then SEL="$(printf '%s' "$RESOURCE" | sed -E 's:/:+:g')" TMPFILE="$(mktemp "/tmp/gophed_${HOST}_${SEL}_$PORT.XXXXXXXXXXXXXXXXXXX")" go "$RESOURCE" "$HOST" "$PORT" > "$TMPFILE" while read -r line; do echo "$line"; done | ed -p "$PROMPT" "$TMPFILE" fi if [ "$script_name" = "d" ]; then DIR_RESOURCE="$(dirname "$RESOURCE")" printf 'Download %s in %s\n' "$RESOURCE" "$HOST$RESOURCE" mkdir -p "$HOST/$DIR_RESOURCE" go "$RESOURCE" "$HOST" "$PORT" > "$HOST$RESOURCE" fi cleanup exit 0 fi printf '%s: command not found\n' "$script_name" cleanup exit 1