#!/bin/bash
# wup -- display a WhatsUp network map in terminal

. lib.bash || exit

usage() {
	echo "Usage: $progname [-S] [-L] [mapname]"
	echo
	echo_opt "-S" "output plain ANSI instead of SIXEL"
	echo_opt "-o" "open map via image viewer"
	echo_opt "-oo" "open map page via browser"
	echo_opt "-L" "use LITNET map server instead of Dunelab"
}

opt_sixel=1
opt_chafafmt=""
opt_litnet=0
opt_openmap=0

while getopts :LoSs OPT; do
	case $OPT in
	L) let ++opt_litnet;;
	o) let ++opt_openmap;;
	S) let opt_sixel=0;;
	s) let ++opt_sixel;;
	*) lib:die_getopts;;
	esac
done; shift $[OPTIND-1]

if (( opt_litnet >= 2 )); then
	host="http://lokys.litnet.lt"
	defmap="Backbone.wup"
elif (( opt_litnet )); then
	host="http://lokys.litnet.lt"
	defmap="LITNET.wup"
else
	host="http://echo.dunelab.sym"
	defmap="Dunelab.wup"
fi

map=${1:-"$defmap"}
map=${map%.wup}.wup

tmphost=${host#*://}
tmphost=${tmphost%%/*}
tmpbase=${XDG_CACHE_HOME:-"$HOME/.cache"}/wup_${tmphost}_${map%.wup}

# If opted in to sixel, let chafa autodetect. Otherwise default to ANSI.
if (( !opt_sixel )); then
	chafa_fmtarg="--format=symbols"
fi

# Pre-scroll to avoid slow scrolling in Xterm
if (( !opt_openmap )); then
	test -t 1 || vdie "not a tty"

	# Hardcode my shell prompt 'visible' height and 'total' height (visible
	# + preceding blanks/separators). Currently the height is 3 lines, with
	# the 1st line being blank so it can be safely scrolled out of view.
	hvisible=2
	htotal=3

	# Plus some extra padding to avoid scrolling after hitting Enter on the
	# *next* command. (Two lines to deal with an Xterm quirk which sseems
	# to round sixel sizes up to a multiple of two?)
	let htotal+=2

	# Calculate image height (leaving space for old and new prompts)
	ttysize=$(stty size) || vdie "not a tty"
	imgsize=$(echo "$ttysize" | awk -v h=$[hvisible+htotal] '{print $2 "x" ($1-h)}')

	# Scroll full terminal minus old prompt (and 1 extra line to account
	# for already starting below prompt)
	ttyheight=$[${ttysize% *}-(hvisible+1)]
	printf "%*s" "$ttyheight" "" | tr " " '\n'
	printf '\e[%sA' "$ttyheight"
fi

# Find and download the map
mapurl="$host/map.asp?map=$(urlencode -a "$map")"
if (( opt_openmap >= 2 )); then
	xdg-open "$mapurl"
	exit
fi
maptmp=$tmpbase.html
curl -nfsS "$mapurl" -o "$maptmp" || vdie "could not fetch '$mapurl'"
imgurl=$(grep -a '<img.*ISMAP' "$maptmp" | grep -ao 'WUG[-0-9]*\.jpg') || vdie "could not find map '$map'"
imgurl="$host/$imgurl"
rm -f "$maptmp"
imgtmp=$tmpbase.jpg
curl -nfsS "$imgurl" -o "$imgtmp" || vdie "could not fetch '$imgurl'"
if (( opt_openmap )); then
	xdg-open "$imgtmp"
	exit
fi

# --size will stretch, --view-size will only clamp
chafa $chafa_fmtarg --dither=fs --colors=full --symbols=vhalf --size="$imgsize" "$imgtmp"
