#!/bin/sh
# links resources from one directory to another and sorts them there
# usage: resources <source> <destination> <path to sortresources.py>

# set -x

source=$1
destination=$2
sortresources=$3

# globalize path
#test -z `echo ${sortresources} | grep "^/"` && sortresources=`pwd`/${sortresources}

# exit if source does not exist
test -d $source || exit 0

# remake directory for included resources
rm -rf ${destination}
mkdir ${destination}

# link/softlink/copy them over
cp -Rlf ${source}/* ${destination}/ > /dev/null 2>&1 || cp -Rsf ${source}/* ${destination}/ > /dev/null 2>&1 || cp -Rf ${source}/* ${destination}/ || { echo Copying or linking resources failed. ; exit 1;}

# remove CVS directories and backup files
find ${destination}/ -depth -type d -name CVS -exec rm -rf \{\} \;
find ${destination}/ -depth -type d -name .svn -exec rm -rf \{\} \;
find ${destination}/ -name "*~" -exec rm -rf \{\} \;

# rename them properly
PYTHON=`which python3 python python2 2> /dev/null | head -n 1`
echo python is ${PYTHON}
${PYTHON} ${sortresources} -v ${destination} || exit 1

# silently remove empty directories
find ${destination} -type d -depth -exec rmdir \{\} \; > /dev/null 2>&1 

# copy map dtd file to one with correct version
MAPVERSION=`grep "<!-- version=" < ${destination}/map.dtd | sed -e "s,.*=\",," -e "s,\".*,,"`
test -r ${destination}/AATeam || mkdir ${destination}/AATeam
cp ${destination}/map.dtd ${destination}/AATeam/map-$MAPVERSION.dtd
echo $MAPVERSION > ${destination}/.mapversion

# tag completion
touch ${destination} || exit 1
chmod 755 ${destination} || exit 1
