#!/bin/sh
# text-only shar generator
# (c) 2017 Shiz, WTFPL
set -e

if test $# -lt 2 ; then
	echo "usage: $0 <output> <files>"
	exit 1
fi

save() {
	for i ; do
		printf "%s\n" "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/"
	done
	echo " "
}

out=$1
tmpout=$1.tmp
shift

rm -f "$tmpout"
for f ; do
	if test -f "$f" ; then
		cat "$f" >> "$tmpout"
	fi
done
trap 'rm "$tmpout"' EXIT

herevar="SHAREOF$$"
herecands=$(grep "^$herevar" "$tmpout" || true)
i=0
while true ; do
	if ! printf "%s\n" "$herecands" | grep -q "^$herevar$i\$" ; then
		herevar="$herevar$i"
		break
	fi
	i=$(($i + 1))
done

clear=
for f ; do
	if test -z "$clear" ; then
		set --
		clear=1
	fi

	if test -f "$f" ; then
		size=$(wc -l "$f" | awk '{ print $1 }')
		echo "adding: $f ($size lines)"
		set -- "$@" "f+$size:$f"
	elif test -d "$f" ; then
		echo "adding directory: $f"
		set -- "$@" "d:$f"
	else
		echo "can't add unknown file type $f" >&2
	fi
done

cat >"$out"<<HEADER
#!/bin/sh
set -e

set -- $(save "$@")

for file ; do
	meta="\${file%%:*}"
	fn="\${file#*:}"
	type="\${meta%%+*}"
	size="\${meta#*+}"
	base="\${fn%/*}"

	case "\$type" in
	f)
		echo "unpacking: \$fn (\$size lines)"
		if test "\$base" != "\$fn" ; then
			mkdir -p "\$base"
		fi

		: >"\$fn"
		i=0
		while test \$i -lt "\$size" && IFS= read -r line ; do
			printf "%s\n" "\$line" >>"\$fn"
			i=\$((\$i + 1))
		done
		;;
	d)
		echo "creating: \$fn"
		mkdir -p "\$fn"
		;;
	esac
done <<'$herevar'; exit 0
HEADER

cat "$tmpout" >> "$out"
echo "$herevar" >> "$out"
chmod +x "$out"
