#!/bin/awk -f

# SPDX-License-Identifier: CC0-1.0
# License: CC0-1.0 <https://creativecommons.org/publicdomain/zero/1.0/>
# Andreas K. Foerster

# Filter to make a gopher menu more readable for humans
#
# usage:
#   $ curl gopher://gopher.example.net/1/ | gophermenu | less
# use it only for type 1 and 7

BEGIN { FS = "\t" }

# dot alone on a line
/^\.$/ { exit }

# ignore entries with less than 4 fields
NF < 4 { next }

# for every entry
{
  type = substr ($1, 1, 1)
  name = substr ($1, 2)
  selector = $2
  host = $3
  port = int ($4)

  # is host an IPv6 address?
  if (host ~ /:/) host = "[" host "]"

  if (type == "0")      sym = "TEXT"
  else if (type == "1") sym = "DIR"
  else if (type == "2") sym = "CCSO"
  else if (type == "3") sym = "!!!!"
  else if (type == "4") sym = "HQX"
  else if (type == "5") sym = "ARCH"
  else if (type == "6") sym = "UUE"
  else if (type == "7") sym = "[?]:"
  else if (type == "8") sym = "TELN"
  else if (type == "9") sym = "BIN"
  else if (type == "+") sym = "ALT"
  else if (type == "g") sym = "GIF"
  else if (type ~ /^[Ip:]/) sym = "PICT"
  else if (type == "T") sym = "3270"
  else if (type == ";") sym = "VID"
  else if (type ~ /^[s<]/) sym = "AUD"
  else if (type == "d") sym = "DOCU"
  else if (type == "h") sym = "HTML"
  else if (type == "r") sym = "RTF"
  else if (type == "P") sym = "PDF"
  else if (type == "X") sym = "XML"
  else if (type == "M") sym = "MIME"
  else if (type == "c") sym = "CAL"
  else if (type == "i") sym = ""
  else sym = "????"

  printf "%4.4s| ", sym
}

# URL (for any type, suggested: h)
selector ~ /^URL:/ {
  print name
  printf " -> | <%s>\n", substr (selector, 5)
  next
}

# Error / Information
/^[3i]/ { print name; next }

# Gopher type
/^[0145679+gIhsdrpPXMc:;<]/ {
  print name

  printf " -> | <gopher://%s", host

  if (port != 70) printf ":%d", port

  printf "/%c%s", type, selector

  # search string appended by %09
  if (/^7/) printf "%%09..."

  print ">"
  next
}

# Telnet / Telnet 3270
/^[8T]/ {
  cmd = /^T/ ? "x3270" : "telnet"

  print name
  printf " -> | $ %s %s", cmd, host

  # not default port?
  if (port != 23) printf " %d", port

  # login given?
  if (selector != "" && selector !~ /^\/?none/)
    printf "\t\t[login: %s]", selector

  print ""
  next
}

# CCSO/ph
/^2/ {
  print name
  printf " -> | $ ph -s %s", host

  # not default port?
  if (port != 105) printf " -p %d", port

  print ""
  next
}

# unknown
{ print name; next }
