#!/bin/sh -e
# See http://jdebp.uk./FGA/slashpackage.html
if test \! -d package || test \! -d source
then
	echo "You are not in the right directory." 1>&2
	exit 100
fi
if ! test $# -ge 2
then
	echo "Two arguments are required." 1>&2
	exit 100
fi

src="${1}"
dest="${2}"
absdest="`readlink -f "${dest}"`/"

##########################################################
# distributor patchable stuff

# These are the parents of the relevant directory trees.
# Uniformly, packages go under /usr/local on FreeBSD, mixed in with actually local stuff.
# Eventually, we will switch to the NetBSD convention of /usr/pkg .
case "`uname`" in
(Linux)
	pkgbase="/usr/local"
	zshprefix="/usr"
	;;
(FreeBSD)
	pkgbase="/usr/local"
	zshprefix="/usr/local"
	;;
(*BSD)
	pkgbase="/usr/pkg"
	zshprefix="/usr/pkg"
	;;
esac

##########################################################
# derived from distributor patchable stuff or from the operating system

binprefix="${pkgbase}"
etcprefix="${pkgbase}"
libprefix="${pkgbase}"
manprefix="${pkgbase}"
incprefix="${pkgbase}"
shrprefix="${pkgbase}"
docprefix="${shrprefix}/share"

##########################################################
# binaries and doco
for i in redo cubehash pkg-helper ;
do
	if test -s package/export-manifests/"$i".commands1
	then
		install -d -m 0755 "${dest}"/"$i""${binprefix}"/bin
		install -d -m 0755 "${dest}"/"$i""${manprefix}"/man/man1
		install -d -m 0755 "${dest}"/"$i""${manprefix}"/man/docbook1
		while read c ;
		do
			ln -f -- "${src}"/command/"$c" "${dest}"/"$i""${binprefix}"/bin/
			ln -f -- "${src}"/manual/"$c".1 "${dest}"/"$i""${manprefix}"/man/man1/
			ln -f -- "${src}"/manual/"$c".xml "${dest}"/"$i""${manprefix}"/man/docbook1/
		done < package/export-manifests/"$i".commands1 ;
	fi
	if test -s package/export-manifests/"$i".aliases1
	then
		install -d -m 0755 "${dest}"/"$i""${binprefix}"/bin
		install -d -m 0755 "${dest}"/"$i""${manprefix}"/man/man1
		install -d -m 0755 "${dest}"/"$i""${manprefix}"/man/docbook1
		while read c a ;
		do
			ln -f -- "${dest}"/"$i""${binprefix}"/bin/"$c" "${dest}"/"$i""${binprefix}"/bin/"$a"
			ln -f -- "${dest}"/"$i""${manprefix}"/man/man1/"$c".1 "${dest}"/"$i""${manprefix}"/man/man1/"$a".1
			ln -f -- "${dest}"/"$i""${manprefix}"/man/docbook1/"$c".xml "${dest}"/"$i""${manprefix}"/man/docbook1/"$a".xml
		done < package/export-manifests/"$i".aliases1 ;
	fi
done

##########################################################
# more doco
for i in guide ;
do
	install -d -m 0755 -- "${dest}"/redo-"${i}"/"${docprefix}"/doc/redo
	( cd "${src}"/guide && pax -r -w -l -- * "${absdest}"/redo-"${i}"/"${docprefix}"/doc/redo/ )
done

##########################################################
# Z shell functions
for i in zsh-completions ;
do
	install -d -m 0755 -- "${dest}"/redo-"${i}"/"${zshprefix}"/share/zsh/vendor-completions
	( cd "${src}"/config/zsh && pax -r -w -l -- * "${absdest}"/redo-"${i}"/"${zshprefix}"/share/zsh/vendor-completions/ )
done
