#!/usr/bin/env bash

set -f

if [ $# -ne 1 ]; then
	echo usage: $0 repository
	echo "Repositories:"
	ls extend/addon
	exit 1
fi

if [ -d extend/addon/$1 ] ; then
        cd extend/addon/$1
else
        echo "$1 not found. Aborting..."
        exit 1
fi

if [ -d .git ] ; then
	git pull
fi

cd ../../..

filelist=(`ls extend/addon/$1`)

cd addon

for a in "${filelist[@]}" ; do
	base=`basename $a`
	if [ $base = '.git' ]; then
#		echo 'ignoring git'
		continue;
	fi
	if [ ! -d ../extend/addon/$1/$base ]; then
#		echo $a 'not a directory'
		continue;
	fi
	if [ -x $base ]; then
#		echo $base 'file exists'
		continue;
	fi

	echo linking $base 
	ln -s ../extend/addon/$1/$base $base
done

for x in `ls` ; do 
	if [ -L "$x" ] && ! [ -e "$x" ]; then 
		echo "removing dead symlink $x" ; 
		rm -- "$x"; 
	fi;
done