about summary refs log tree commit diff stats
path: root/bonus/addurimethod
blob: 4d52f2261639c2767e9e01915ce88429f47bac1a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/bin/sh

if test $# -ne 2
then	printf 'Usage: addurimethod [scheme] [program name]' >&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=$(grep -oE '^[a-zA-Z+-]+:[[:space:]]+' "$urimethodmap" | \
	grep -oE '[[:space:]]+' | \
	tail -c2)

space_mul=1
if test "$space_kind" = '	'; then	space_mul=8; 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