#!/bin/bash

set -e

# ensure gosub is installed (this will recompile it only if necessary)
# go get github.com/vito/gosub
go install github.com/vito/gosub

function sync_package() {
  bosh_pkg=${1}

  shift

  (
    set -e

    cd packages/${bosh_pkg}

    {
      cat spec | grep -v '# gosub'

      for package in $(gosub list "$@"); do
        repo=$(echo ${2} | cut -f1-3 -d/)
        if [ -d "../../src/${repo}/Godeps/_workspace/src/${package}" ]; then
          package="${repo}/Godeps/_workspace/src/${package}"
        fi
        echo ${package} | sed -e 's/\(.*\)/  - \1\/*.go # gosub/g'
        if ls ../../src/${package}/*.s >/dev/null 2>&1; then
          echo ${package} | sed -e 's/\(.*\)/  - \1\/*.s # gosub/g'
        fi
      done
    } > spec.new

    mv spec.new spec
  )
}

## Create a sync_package line for each BOSH package in this release
## add a -app line or -test line to include a particular app or test
## along with all of its dependencies

sync_package vxlan-policy-agent \
  -app vxlan-policy-agent/cmd/vxlan-policy-agent &

sync_package flannel-watchdog \
  -app flannel-watchdog/cmd/flannel-watchdog &

sync_package policy-server \
  -app policy-server/cmd/policy-server &

sync_package netmon \
  -app netmon/cmd/netmon &

sync_package cf-networking-acceptance \
  -test test/acceptance \
  -app cli-plugin \
  -app cf-pusher/cmd/cf-pusher \
  -app github.com/onsi/ginkgo/ginkgo &

GOOS=linux sync_package runc-cni \
  -app github.com/containernetworking/cni/plugins/main/bridge \
  -app github.com/containernetworking/cni/plugins/ipam/host-local \
  -app garden-external-networker &

GOOS=linux sync_package flannel \
  -app github.com/containernetworking/cni/plugins/main/bridge \
  -app github.com/containernetworking/cni/plugins/ipam/host-local \
  -app github.com/containernetworking/cni/plugins/meta/flannel \
  -app cni-wrapper-plugin &

wait

git diff --name-only packages/*/spec
