#!/bin/sh
# mkgrcp: pack recipe directories into recipe bundles (BUILD_DESIGN.txt
# section 4), for a NAME-src repository that grepo then indexes.
#
#   mkgrcp [-o DIR] RECIPEDIR...
#
#   -o DIR    write DIR/NAME-VER.grcp (default: .)
#
# RECIPEDIR holds `recipe` and optionally `build` and patches/*.patch;
# NAME and VER are taken from the recipe's top-level `NAME = "..."` and
# `VER = "..."` lines (at the start of a line). Nothing else is packed.
# The bundle is checked by the library when grepo indexes it.
#
# Example:
#   mkgrcp -o /srv/extra-src ~/Projects/everest/recipes/extra-src/*/
#   grepo -s KEY.sec -r extra-src /srv/extra-src

usage() { echo "usage: mkgrcp [-o DIR] RECIPEDIR..." >&2; exit 1; }

out=.
while getopts o:h opt; do
	case $opt in
	o) out=$OPTARG ;;
	*) usage ;;
	esac
done
shift $((OPTIND - 1))
[ $# -ge 1 ] || usage
mkdir -p "$out" || exit 1

work=$(mktemp -d) || exit 1
trap 'rm -rf "$work"' EXIT

field() { sed -n "s/^$1[[:space:]]*=[[:space:]]*\"\([^\"]*\)\".*/\1/p" "$2" | head -1; }

rc=0
for r in "$@"; do
	r=${r%/}
	name=$(field NAME "$r/recipe") ver=$(field VER "$r/recipe")
	if [ -z "$name" ] || [ -z "$ver" ]; then
		echo "mkgrcp: $r/recipe: no NAME or VER line" >&2
		rc=1
		continue
	fi
	d=$work/$name-$ver
	mkdir "$d" || exit 1
	cp "$r/recipe" "$d/"
	[ -f "$r/build" ] && cp "$r/build" "$d/"
	if [ -d "$r/patches" ]; then
		mkdir "$d/patches"
		cp "$r"/patches/*.patch "$d/patches/" 2>/dev/null
	fi
	chmod -R u=rwX,go=rX "$d"
	b=$out/$name-$ver.grcp
	tar czf "$b" -C "$work" "$name-$ver" || exit 1
	chmod 644 "$b"
	echo "$b"
done
exit $rc
