#!/bin/bash
set -e

go get github.com/vito/gosub

if [ ! $(which gosub) ]; then
    echo "Gosub required to update dependencies in bosh/*/spec files."
    echo 'Please install with `go get github.com/vito/gosub`'
    exit 1
fi

function sync_package() {
  bosh_pkg=${1}

  shift

  (
    set -e

    cd packages/${bosh_pkg}

    gosublist=$(gosub list "$@")

    {
      cat spec | grep -v '# gosub'
      for i in $gosublist; do
          echo $i | sed -e 's|\(.*\)|- \1/*.go # gosub|g'

          if ls $GOPATH/src/$i/*.s &> /dev/null; then
              echo $i | sed -e 's|\(.*\)|- \1/*.s # gosub|g'
          fi
      done
    } > spec.new

    mv spec.new spec

  )
}

sync_package log-cache                  -app code.cloudfoundry.org/log-cache/cmd/log-cache &
sync_package log-cache-gateway          -app code.cloudfoundry.org/log-cache/cmd/gateway &
sync_package log-cache-nozzle           -app code.cloudfoundry.org/log-cache/cmd/nozzle &
sync_package log-cache-expvar-forwarder -app code.cloudfoundry.org/log-cache/cmd/expvar-forwarder &
sync_package log-cache-cf-auth-proxy    -app code.cloudfoundry.org/log-cache/cmd/cf-auth-proxy &
sync_package log-cache-scheduler        -app code.cloudfoundry.org/log-cache/cmd/scheduler &
sync_package log-cache-blackbox         -app code.cloudfoundry.org/log-cache/cmd/blackbox-test &

wait
