# gopher - gopher protocol client
# usage: gopher host [selector [port]]
#
# Fetches pages from gopher servers using the Plan 9
# /net filesystem (RFC 1436).
#
# Requires /net mounted from a network peer (e.g. iOS
# app serving 9P over BLE L2CAP).
#
# The /net server handles DNS resolution internally
# when hostnames are used in connect commands.
#
# Examples:
#   gopher gopher.floodgap.com
#   gopher gopher.floodgap.com /fun/twitpher
#   gopher gopher.floodgap.com / 7070

if (test -z $1) {
    echo 'usage: gopher host [selector [port]]'
    exit 1
}

host=$1
sel=$2
port=$3
if (test -z $port) { port=70 }

# Allocate a TCP connection
n=`{cat /net/tcp/clone}
if (test -z $n) {
    echo 'gopher: /net not available'
    exit 1
}

netdir=/net/tcp/$n

# Dial the server
echo 'connect '$host'!'$port > $netdir/ctl
if (test $? != 0) {
    echo 'gopher: connect '$host':'$port' failed'
    exit 1
}

# Send selector and read response on same fd.
# <> opens data file read-write; echo writes the
# selector, then cat reads until the server closes.
<>$netdir/data {
    echo $sel
    cat
}

# Tear down
echo 'hangup' > $netdir/ctl
