#!/bin/bash -x

#Company:       PowerCraft Technology
#Author:        Copyright Jelle de Jong <jelledejong@powercraft.nl>
#Note:          Please send me an email if you enhanced the script
#Version:       0.0.3
#Date:          2008-08-21 / 2009-05-14
#Description:   create symbolic links of all *.??? files in one place

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.

#~ echo "ITEMS: $ITEMS"
#~ echo "TOPDIR: $TOPDIR"
#~ echo "SYMDIR: $SYMDIR"
# symdir is resources/<SUBDIR>
# and ITEMS are .sym files

# This is an evil hack
pwd="$PWD"
pwd=${pwd%"openarm"*}
pwd+="/openarm/working/scripts/"
cd "$pwd"
#~ echo "pwd: $PWD"

# OPTIONS+="-mmin -1"

if [ -n "$1" ] && [ "$1" == "clean" ]
then
    unset OPTIONS
    clean="true"
fi

if [ -z "$2" ]
then
    DESTINATION="../pcb/footprints/all"
    # ls -hal "$DESTINATION"
else
    DESTINATION="$1"
fi

if [ -z "$3" ]
then
    SOURCE="../../doc/"
    # ls -hal "$SOURCE"
else
    SOURCE="$1"
fi

if [ -n "$clean" ]
then
    find -P "$DESTINATION" -maxdepth 1 -type l -print0 | xargs -0 rm --verbose ;
fi

IFS=$'\n'
unset list
list=($(find "$SOURCE" -maxdepth 3 $OPTIONS -type f -iname "*.fp"))

for file in "${list[@]}"
do
    echo "$file"
    filename=${file##*/}
    location=${file#*"doc"}
    location=${location%/*}
    path="../../../../doc"
    path+="$location"
    if [ -e "$DESTINATION"/"$filename" ]
    then
        rm "$DESTINATION"/"$filename"
    fi
    ln --symbolic "$path"/"$filename" "$DESTINATION"/"$filename"
done

exit
