#!/bin/bash


cd "$(dirname "$0")/.."

doit() {
  if [ -n "$DRYRUN" ]; then
    echo "$@"
  else
    "$@"
  fi
}

depend()
{
  for found in "vendor/$1"/*; do
    if [ ! -h "vendor/$1/$file" ]; then
      doit rm -Rf "$found"
    fi
  done

  for used in "$WS/src/$1"/*; do
    file="$(basename "$used")"
    if [ ! -h "vendor/$1/$file" -a "$file" != vendor ]; then
      back=$(echo -n "$1" | sed -e "s/[^/]*/../g")
      doit ln -s "$back/../../../../$1/$file" "vendor/$1/$file" 
    fi
  done    
}

###############################################################################
# main

while [ $# -gt 0 ]; do
  case "$1" in
    -d) ENSURE=X
        shift;;
    -n) DRYRUN=X
        shift;;
    -*) echo "invalid option $1" >&2
        exit 1;;
    *) break;;
  esac
done

ROOT="$(pwd)"
while [ ! -d "$ROOT/pkg" -a "$ROOT" != / ]; do
  ROOT="$(dirname "$ROOT")"
done
if [ "$ROOT" == / ]; then
  echo "ERROR: cannot determine project root" >&2
  exit 1
fi

if [ "$ROOT" == / ]; then
  echo "ERROR: cannot determine project root" >&2
  exit 1
fi

cd "$ROOT"
echo PROJECT_ROOT="$ROOT"

WS="$ROOT"
while [ ! -d "$WS/src" -a "$WS" != / ]; do
  WS="$(dirname "$WS")"
done

if [ "$WS" == / ]; then
  echo "ERROR: cannot determine go workspace" >&2
  exit 1
fi
echo WORKSPACE="$WS"

if [ -n "$ENSURE" ]; then
  echo "update dependencies $@"
  dep ensure "$@"
fi
DEF="commondev.lst"
if [ ! -f "$DEF" ]; then
  DEF="local/commondev.lst"
fi
if [ -f "$DEF" ]; then
   while read -r line; do
     if [ "${line###}" == "$line" ]; then
       if [ ! -d "$WS/src/$line/pkg" ]; then
          echo "project $line not found in workspace"
          exit 1
       fi
       if [ ! -d "vendor/$line/pkg" ]; then
         echo "project $line not used in vendor folder"
       else
	 echo "common development with $line"
         depend "$line"
       fi

     fi
   done <"$DEF"
else
  echo "no common developments defined"
fi
