#!/bin/sh

# aerc filter to view HTML emails with w3m.
#
# Networking access will be disabled unless the script is named 'html-unsafe'.
#
# If stdout is connected to a TTY, the interactive pager of w3m will be enabled.

set -- w3m \
	-I UTF-8 -O UTF-8 -T text/html \
	-s -graph \
	-o fold_textarea=true \
	-o fold_line=true \
	-o decode_url=true \
	-o display_link=true \
	"$@"

if [ -t 1 ]; then
	# stdout is connected to a terminal, enable interactive mode
	set -- "$@" -o display_borders=true

	if w3m --help 2>&1 | head -n1 | grep -q "options.*image"; then
		# display inline images if support is enabled
		set -- "$@" -o display_image=true -o auto_image=true
	fi
else
	# stdout is connected to a pager, dump output without interaction
	set -- "$@" -cols 100 -dump -o disable_center=true
fi

if ! [ "$(basename $0)" = "html-unsafe" ]; then
	# attempt network isolation to prevent any phoning home by rendered emails
	set -- "$@" -o no_cache=true -o use_cookie=false

	if command -v unshare >/dev/null 2>&1; then
		# run the command in a separate network namespace
		set -- unshare --map-root-user --net "$@"
	elif command -v socksify >/dev/null 2>&1; then
		# if socksify (from dante-utils) is available, use it
		export SOCKS_SERVER="127.0.0.1:1"
		set -- socksify "$@"
	else
		# best effort, use an invalid address as http proxy
		set -- "$@" -o use_proxy=true
		for opt in http_proxy https_proxy gopher_proxy ftp_proxy; do
			if w3m -o | grep -q $opt; then
				set -- "$@" -o $opt='127.0.0.1:1'
			fi
		done
	fi
fi

exec "$@"
