#!/bin/sh

branch_name="$(git branch --show-current)"
targets=""
install=false

distribute() {
  rsync -P -r "${XBPS_DISTDIR}/hostdir/binpkgs/${branch_name}" "$1":
}

install() {
  package_dir=$(basename "$branch_name")
  ssh "$1" "xi -R $package_dir -Suy && rm -rf $package_dir"
}

if [ "$1" = "-i" ]; then
  install=true
  shift
fi

if [ $# = 0 ]; then
  targets="daybreak epoch"
elif [ "$1" = "repo" ]; then
	cd "${XBPS_DISTDIR}/hostdir/binpkgs/${branch_name}" || exit 1
	for p in *.xbps; do
		rsync -P "$p" daybreak:/srv/repo
		ssh daybreak "xbps-rindex --add /srv/repo/$p;
		xbps-rindex --privkey /srv/repo/private.pem --sign-pkg /srv/repo/*.xbps"
	done
else
  targets="$1"
fi

for t in $targets; do
  distribute "$t"
  if [ "$install" = true ]; then
    install "$t"
  fi
done