#!/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
        if ls ../../src/${package}/*.h >/dev/null 2>&1; then
          echo ${package} | sed -e 's/\(.*\)/  - \1\/*.h # gosub/g'
        fi
      done
    } > spec.new

    mv spec.new spec
  )
}

sync_package auctioneer              -app  code.cloudfoundry.org/auctioneer/cmd/auctioneer &
sync_package bbs                     -app  code.cloudfoundry.org/bbs/cmd/bbs &
sync_package cfdot                   -app  code.cloudfoundry.org/cfdot &
sync_package diego-sshd              -app  code.cloudfoundry.org/diego-ssh/cmd/sshd &
sync_package file_server             -app  code.cloudfoundry.org/fileserver/cmd/file-server &
sync_package locket                  -app  code.cloudfoundry.org/locket/cmd/locket &
sync_package rep                     -app  code.cloudfoundry.org/rep/cmd/rep -app  code.cloudfoundry.org/rep/cmd/gocurl &
sync_package rep_windows             -app  code.cloudfoundry.org/rep/cmd/rep -app  code.cloudfoundry.org/rep/cmd/gocurl &
sync_package route_emitter           -app  code.cloudfoundry.org/route-emitter/cmd/route-emitter &
sync_package route_emitter_windows   -app  code.cloudfoundry.org/route-emitter/cmd/route-emitter &
sync_package ssh_proxy               -app  code.cloudfoundry.org/diego-ssh/cmd/ssh-proxy &
sync_package certsplitter            -app  code.cloudfoundry.org/certsplitter/cmd/certsplitter &

sync_package docker_app_lifecycle    -app  code.cloudfoundry.org/dockerapplifecycle/builder \
  -app code.cloudfoundry.org/dockerapplifecycle/launcher &

sync_package buildpack_app_lifecycle -app  code.cloudfoundry.org/buildpackapplifecycle/builder \
  -app code.cloudfoundry.org/buildpackapplifecycle/launcher \
  -app code.cloudfoundry.org/buildpackapplifecycle/shell/shell &

sync_package windows_app_lifecycle -app  code.cloudfoundry.org/buildpackapplifecycle/builder \
  -app code.cloudfoundry.org/buildpackapplifecycle/launcher &

sync_package vizzini \
  -test code.cloudfoundry.org/vizzini/... \
  -app github.com/onsi/ginkgo/ginkgo &

sync_package benchmark-bbs \
  -test code.cloudfoundry.org/benchmarkbbs/... \
  -app github.com/onsi/ginkgo/ginkgo &

wait

git diff --name-only packages/*/spec | tee # pipe through tee to avoid issues with non-interactive shells
