#!/bin/sh

PORTSDIR=${PORTSDIR:-"/usr/ports"}
[ -d $PORTSDIR ] || exit 1

echo "Update TDE ports"
echo "+ trinity.port.mk > Mk/bsd.trinity.mk"
rsync -a $(dirname $0)/trinity.port.mk $PORTSDIR/Mk/bsd.trinity.mk

find $(dirname $0) -name "Makefile" |\
xargs -r grep -l "^# TDE port map: "|\
sort |\
while read TDE_PORT; do
  TDE_PORT_MAP=$(sed -n "s|^# TDE port map: ||p" $TDE_PORT)
  TDE_PORT_SOURCE=$(echo $TDE_PORT_MAP | sed "s| > .*||")
  if echo "$TDE_PORT_MAP" | grep -q " > "; then
    TDE_PORT_TARGET=$(echo $TDE_PORT_MAP | sed "s|.* > ||")
  else
    PORTNAME=$(sed -n "s|^PORTNAME[\t ]*=[\t ]*||p" $TDE_PORT)
    CATEGORY=$(sed -n "s|^CATEGORIES[\t ]*=[\t ]*\([^\t ]*\).*|\1|p" $TDE_PORT)
    TDE_PORT_TARGET=$CATEGORY/$PORTNAME
  fi

  echo "+ $TDE_PORT_SOURCE > $TDE_PORT_TARGET"
  rsync -a --del ${TDE_PORT%/Makefile}/ $PORTSDIR/$TDE_PORT_TARGET/
done