#!/bin/sh
# eptrepo - maintain an ept package repository (runs on the host, not on ELKS)
#
# Repository layout:
#   <repo>/index                    generated package list
#   <repo>/pool/<name>/VERSION      package version, one word
#   <repo>/pool/<name>/<dest>       each file, at its install path
#                                   e.g. pool/lua/bin/lua -> /bin/lua
# Nightly builds use a second repository of the same layout in <repo>/nightly.
#
# Usage:
#   eptrepo add [-s] <repo> <name> <version> <file> <dest> [<file> <dest> ...]
#   eptrepo index <repo>
#
# If <file> is a directory, everything in it is added below <dest>,
# e.g. "include /usr/include" or "target /". A symlink is published as a
# copy of its target, which is looked up inside the package: /lib/x is the
# package's /lib/x, as it will be on ELKS.
# A package with files that cannot be published (symlinks to something not
# in the package, bad names) is refused and the old one is left as it was;
# with -s those files are reported and skipped instead.

set -e

# The oldest ept that can use a repository made by this script. It goes into
# the index as "#min <version>"; an older ept then updates itself before it
# installs anything. Raise it when the repository starts to need a newer ept.
MINEPT=1.3

usage()
{
	sed -n '2,21p' "$0" | sed 's/^# \{0,1\}//'
	exit 1
}

die()
{
	echo "eptrepo: $*" >&2
	exit 1
}

checkword()
{
	case "$1" in
	""|*[!A-Za-z0-9._/+-]*) die "'$1': only letters, digits and . _ + - allowed";;
	esac
}

index()
{
	repo=$1
	[ -d "$repo/pool" ] || die "$repo/pool: no such directory"
	out=$repo/.index.$$		# unique, so concurrent runs cannot clobber each other
	echo "#ept1" > "$out"
	echo "#min $MINEPT" >> "$out"
	npkg=0
	nfile=0
	for dir in "$repo"/pool/*/; do
		[ -d "$dir" ] || continue
		name=`basename "$dir"`
		checkword "$name"
		[ -f "$dir/VERSION" ] || die "$name: missing VERSION file"
		version=`cat "$dir/VERSION"`
		checkword "$version"
		files=`cd "$dir" && find . -type f ! -path ./VERSION | LC_ALL=C sort`
		[ "$files" ] || die "$name: package has no files"
		for f in $files; do
			dest=${f#.}
			checkword "$dest"
			sum=`md5sum "$dir/$f" | cut -d' ' -f1`
			size=`wc -c < "$dir/$f" | tr -d ' '`
			if [ -x "$dir/$f" ]; then mode=755; else mode=644; fi
			echo "$name $version $sum $size $mode $dest" >> "$out"
			nfile=`expr $nfile + 1`
		done
		npkg=`expr $npkg + 1`
	done
	echo "#end" >> "$out"
	mv "$out" "$repo/index"
	echo "$repo/index: $npkg packages, $nfile files"
}

# note <message>: report a file that cannot be published
note()
{
	echo "eptrepo: $*" >&2
	echo x >> "$stage.bad"
}

# addtree <dir> <dest>: copy the files and symlinks of a tree into the
# staging directory, below <dest>
addtree()
{
	mkdir -p "$stage$2"
	(cd "$1" && d=$stage${2%/} find . \( -type f -o -type l \) -exec sh -c '
		for f; do
			mkdir -p "$d/${f%/*}" && cp -pP "$f" "$d/$f" || exit 1
		done' sh {} +)
}

# Replace the symlinks in the staging directory by copies of what they point
# to. The staging directory is taken as the root, as it will be on ELKS, so
# /lib/x means <stage>/lib/x and never a file of this host. A link to a link
# is resolved in a later pass; what is left after that cannot be published.
resolvelinks()
{
	pass=0
	while [ $pass -lt 10 ]; do
		pass=`expr $pass + 1`
		find "$stage" -type l > "$stage.list"
		[ -s "$stage.list" ] || return 0
		progress=
		while IFS= read -r l; do
			[ -L "$l" ] || continue
			t=`readlink "$l"`
			case "$t" in
			/*) t=$stage$t;;
			*)  t=`dirname "$l"`/$t;;
			esac
			r=`readlink -f "$t" 2>/dev/null` || continue
			case "$r" in "$stage"/*) ;; *) continue;; esac
			case "$l/" in "$r"/*) continue;; esac	# points to its own parent
			if [ -f "$r" ]; then
				rm "$l"
				cp -p "$r" "$l"
			elif [ -d "$r" ]; then
				rm "$l"
				cp -RpP "$r" "$l"
			else
				continue
			fi
			progress=1
		done < "$stage.list"
		[ "$progress" ] || break
	done
	find "$stage" -type l > "$stage.list"
	while IFS= read -r l; do
		note "${l#"$stage"} -> `readlink "$l"`: symlink target is not in the package"
		rm -f "$l"
	done < "$stage.list"
}

# Remove what the index cannot list: names with other characters than
# checkword allows, and anything that is not a regular file.
dropbad()
{
	find "$stage" -mindepth 1 -name '*[!A-Za-z0-9._+-]*' -prune -print > "$stage.list"
	while IFS= read -r f; do
		note "${f#"$stage"}: name has characters other than letters, digits and . _ + -"
	done < "$stage.list"
	find "$stage" -mindepth 1 -name '*[!A-Za-z0-9._+-]*' -prune -exec rm -rf {} +
	find "$stage" ! -type f ! -type d > "$stage.list"
	while IFS= read -r f; do
		note "${f#"$stage"}: not a regular file"
		rm -f "$f"
	done < "$stage.list"
}

add()
{
	skip=
	if [ "$1" = -s ]; then skip=1; shift; fi
	[ $# -ge 5 ] || usage
	repo=$1 name=$2 version=$3
	shift 3
	checkword "$name"
	checkword "$version"
	# The package is put together in a staging directory and only replaces
	# the published one when it is complete.
	mkdir -p "$repo/pool"
	stage=`cd "$repo" && pwd -P`/.add.$$
	trap 'rm -rf "$stage" "$stage.list" "$stage.bad"' EXIT
	rm -rf "$stage"
	mkdir "$stage"
	while [ $# -ge 2 ]; do
		case "$2" in /*) ;; *) die "$2: destination must be an absolute path";; esac
		checkword "$2"
		if [ -d "$1" ]; then
			addtree "$1" "$2"
		else
			[ -f "$1" ] || die "$1: no such file"
			mkdir -p "$stage`dirname "$2"`"
			cp -pL "$1" "$stage$2"
		fi
		shift 2
	done
	[ $# -eq 0 ] || usage
	resolvelinks
	dropbad
	if [ -s "$stage.bad" ]; then
		n=`wc -l < "$stage.bad" | tr -d ' '`
		[ "$skip" ] || die "$name not changed: $n files cannot be published (-s skips them)"
		echo "eptrepo: $name: $n files skipped" >&2
	fi
	[ "`find "$stage" -type f | head -1`" ] || die "$name: no files to publish"
	# written last, so a copied tree cannot replace it
	echo "$version" > "$stage/VERSION"
	rm -rf "$repo/pool/$name"
	mv "$stage" "$repo/pool/$name"
	index "$repo"
}

case "$1" in
add)	shift; add "$@";;
index)	[ $# -eq 2 ] || usage; index "$2";;
*)	usage;;
esac
