#!/bin/sh

if test $# -ne 2
then	printf 'Usage: addurimethod [scheme] [program name]\n' >&2
	exit 1
fi
PAGER=${PAGER:-cat}

urimethodmap=$HOME/.urimethodmap
scheme="$1"
cgi="/cgi-bin/$2?%s"

if ! test -f "$urimethodmap"
then	printf '%s:	%s\n' "$scheme" "$cgi" > "$urimethodmap"
	exit 0
fi

grep -- "^$scheme:[[:space:]]*$cgi"'$' "$urimethodmap" >/dev/null && exit 0

space_kind=$(sed -En '/^[a-zA-Z+-]+:[[:space:]]/s/[^[:space:]]//gp' "$urimethodmap" | \
	tail -c2)

space_mul=1
if test "$space_kind" != ' '; then space_mul=8; space_kind='	'; fi
space_num=$(sed -nE 's/^([a-zA-Z+-]+:[[:space:]]*).*/\1/p' "$urimethodmap" | \
	while IFS= read -r line
	do	spaces=$(printf '%s\n' "$line" | sed 's/[^[:space:]]//g')
		nscheme=$((${#line} - ${#spaces}))
		printf '%d\n' $(((${#spaces} * $space_mul + $nscheme) / $space_mul))
	done | \
	sort -rn | \
	head -1)

space_num=$((($space_num * $space_mul + ($space_mul - 1) - ${#scheme} - 1) / $space_mul))

spaces=
if test "$space_num" -gt 0
then	spaces=$(printf "%${space_num}s" | sed "s/ /$space_kind/g")
fi

tmpf=$(mktemp)

printf "%s:${spaces}%s\n" "$scheme" "$cgi" > "$tmpf"
grep -v "^$scheme:" "$urimethodmap" >> "$tmpf"

{
	printf 'Updating %s to:\n\n' "$urimethodmap"
	cat "$tmpf"
} | $PAGER
printf 'OK? (y/n) '
read -r res

if test "$res" = y
then	cp "$tmpf" "$urimethodmap"
else	printf 'Aborting. (temp file is %s)\n' "$tmpf"
fi
