gc (2308B) [raw]
1 #!/bin/sh 2 # gc -- gopher client 3 die() { 4 echo "$*" 1>&2 5 exit 1 6 } 7 8 [ -z "$1" ] && die "usage: gc URL" 9 10 pretty() { 11 awk -F" " " 12 /^[^01i\.]/ { sub(\"^.\", \"\", \$1); printf \" ???| %s\\n\", \$1 } 13 /^i/ { sub(\"^i\", \"\", \$1); printf \" | %s\\n\", \$1 } 14 /^0/ { sub(\"^0\", \"\", \$1); links[n++] = sprintf(\"%s/0%s\", \$3, \$2); printf \"%2d TXT| %s\\n\", n, \$1 } 15 /^1/ { sub(\"^1\", \"\", \$1); links[n++] = sprintf(\"%s/1%s\", \$3, \$2); printf \"%2d DIR| %s\\n\", n, \$1 } 16 END { 17 printf \"\" > \"$LINKS\" 18 for (i=0; i < length(links); i++) { 19 printf \"[%d]: %s\\n\", i + 1, links[i] >>\"$LINKS\" 20 } 21 } 22 " 23 } 24 25 parseurl() { 26 bare=${URL##gopher://} 27 host=${bare%%/*} 28 target=${bare##$host} 29 } 30 31 catlike() { 32 parseurl 33 case "$target" in 34 /0/*) echo "${target##/0}" | nc "$host" 70 ;; 35 /1/*) echo "${target##/1}" | nc "$host" 70 | pretty ;; 36 *) echo "$target" | nc "$host" 70 | pretty ;; # TODO: handle other types? 37 esac 38 } 39 40 goto() { 41 printf "goto> " 42 read -r URL 43 echo "$URL" >> "$HISTORY" 44 } 45 46 goback() { 47 sed -i '$d' "$HISTORY" 48 URL=$(tail -n 1 "$HISTORY") 49 } 50 51 graburl() { 52 N="$1" 53 link=$(grep "^\[$N\]:" "$LINKS") 54 URL=${link##\[*\]: } 55 echo "$URL" >> "$HISTORY" 56 } 57 58 ui() { 59 while [ -n "$URL" ]; do 60 catlike | tee "$BUF" 61 62 URL="" 63 while true; do 64 printf "> " 65 read -r opt 66 case $opt in 67 [0-9]*) graburl "$opt" && if [ -n "$URL" ]; then break; else echo "no such link"; fi ;; 68 l*) cat "$LINKS" ;; 69 g*) goto ; break ;; 70 u*) goback ; break ;; 71 p*) ${PAGER:-less} "$BUF" ;; 72 H*) cat "$HISTORY" ;; 73 h*) cat <<EOM ;; 74 NUM -- go to this target 75 g[oto] -- specify new URL 76 u[p] -- go up a directory 77 p[age] -- view the content in $PAGER 78 H[istory] -- list the history 79 h[elp] -- print this message 80 l[ist] -- list targets 81 q[uit] -- quit 82 EOM 83 q*) break;; 84 *) echo "no such command; 'h' for help, 'q' to quit" ;; 85 esac 86 done 87 done 88 } 89 90 URL=$1 91 LINKS=$(mktemp) 92 HISTORY=$(mktemp) 93 BUF=$(mktemp) 94 echo "$URL" > "$HISTORY" 95 96 if ! tty >/dev/null; then 97 catlike 98 else 99 ui 100 fi 101 102 rm -f "$LINKS" "$HISTORY" "$BUF"