#!/bin/bash -eu

IN="schema/v1.json"
OUT="schema/v1-json.go"
GEN="schema/v1-gen.go"

# See scripts/schema_generator_import.go for instructions on updating the dependency
PKG="google.golang.org/api/google-api-go-generator"

# First, write the discovery document into a go file so it can be served statically by the API
cat << 'EOF' > "${OUT}"
package schema
//
// This file is automatically generated by scripts/schema-generator
//
// **** DO NOT EDIT ****
//
EOF

echo -n 'const DiscoveryJSON = `' >> ${OUT}
cat ${IN} >> "${OUT}"
echo -n '`' >> "${OUT}"

# Now build google-api-go-generator - we vendor so this is consistently reproducible
GEN_PATH="bin/google-api-go-generator"
if [ ! -f ${GEN_PATH} ]; then
	GOPATH="${PWD}/Godeps/_workspace" go build -o ${GEN_PATH} ${PKG}
fi

# Build the bindings
GOPATH=${PWD}/gopath ./bin/google-api-go-generator \
    -googleapi_pkg "google.golang.org/api/googleapi" \
    -api_json_file "${IN}" \
    -output "${GEN}"


# Finally, fix the import in the bindings to refer to the vendored google-api package
sed -i -e "s%google.golang.org%github.com/coreos/fleet/Godeps/_workspace/src/google.golang.org%" "${GEN}"
goimports -w ${GEN}
