#!/usr/bin/python

# This script sets up the _build directory to be suitable to have
# GOPATH pointed at it. The output looks much like what:
#
#     dh_auto_configure --buildsystem=golang --builddirectory=golang
#
# would produce for a normal package build despite the fact that this
# package is not at all out laid in a fashion dh_golang thinks of as
# normal.
#
# Dependencies installed from .deb packages are used in favour of
# packages from ./src.

import csv
import errno
import os
import shutil

def ensure_directory(path):
    try:
        os.makedirs(path)
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise

reader = csv.reader(open("src/github.com/juju/juju/dependencies.tsv"), delimiter="\t")

def link_pkg(pkgpath):
    target = os.path.join("_build/src", pkgpath)
    ensure_directory(os.path.dirname(target))
    for prefix in ['/usr/share/gocode/src', 'src']:
        srcpath = os.path.abspath(os.path.join(prefix, pkgpath))
        if os.path.exists(srcpath):
            os.symlink(srcpath, target)
            return
    raise Exception("%s not found", pkgpath)

for record in reader:
    link_pkg(record[0])

shutil.copytree("src/github.com/juju/juju", "_build/src/github.com/juju/juju", symlinks=True)
