#!/bin/sh
#
# b - trivial commandline browser

# shellcheck disable=SC2312

# STORE="/tmp/b-$(hostname).$USER"
STORE="${TMPDIR:-/tmp}/b-$(hostname).${LOGNAME:-${USER}}"

case "${TERM}" in
  9term | win) PAGER="cat" ;;
  *)
    PAGER="less -FX"
    # PAGER=less
    # LESS=-FX
    ;;
esac

# shellcheck disable=SC2046,SC2250
case "$1" in
  [0-9]*)
    $0 "$(awk '/^References/,0' <"${STORE}" | awk -v n="$1" '$1 == n { print $2 }')"
    ;;
  */* | *.*)
    echo "$1" >"$STORE.url"
    # lynx --dump "$1" | tee "${STORE}" | "${PAGER}"
    lynx -useragent="Lyynx/42.0" --dump "$1" | tee "${STORE}" | ${PAGER}
    ;;
  -e*) elinks $(cat "$STORE.url") ;;
  -f*) firefox $(cat "$STORE.url") ;;
  -l*) lynx $(cat "$STORE.url") ;;
  -w*) w3m $(cat "$STORE.url") ;;
  ?*)
    if [ -x /usr/lib/surfraw/"$1" ]; then
      SURFRAW_browser=$0 sr "$@"
    else
      $0 "https://duckduckgo.com/s=?ie=utf-8&oe=utf-8&q=$*"
      # $0 "http://www.google.com/search?ie=utf-8&oe=utf-8&q=$*"
    fi
    ;;
  *)
    # empty
    ${PAGER} "${STORE}" 2>/dev/null
    ;;
esac
