#!/bin/bash

# Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -o errexit
set -o nounset
set -o pipefail

ROOT=$(dirname "${BASH_SOURCE}")
cd "${ROOT}"

REGISTRY_NAME=gcs-docker-registry
ZONE=us-central1-a
MACHINE_SIZE=g1-small
IMAGE_NAME=container-vm-v20141016
PROJECT=
REGISTRY_BUCKET=

if [[ -z "${PROJECT}" ]]; then
  PROJECT=$(gcloud config list project | tail -n 1 | cut -f 3 -d ' ')
fi

if [[ -z "${REGISTRY_BUCKET}" ]]; then
  REGISTRY_BUCKET="docker-registry-${PROJECT}"
fi

if ! gsutil ls "gs://${REGISTRY_BUCKET}" >/dev/null 2>&1 ; then
  echo "Creating Google Cloud Storage bucket: $REGISTRY_BUCKET"
  gsutil mb -p "${PROJECT}" "gs://${REGISTRY_BUCKET}"
fi

TEMPDIR=$(mktemp -d -t registry-containervm.XXXXXX)
trap 'rm -rf "${TEMPDIR}"' EXIT

sed -e "s/!!REGISTRY_BUCKET/${REGISTRY_BUCKET}/g" manifest-template.yaml >"${TEMPDIR}/manifest.yaml"

echo "Starting VM to run docker registry: ${REGISTRY_NAME}"
gcloud compute instances create "${REGISTRY_NAME}" \
    --image="${IMAGE_NAME}" \
    --image-project=google-containers \
    --metadata-from-file google-container-manifest="${TEMPDIR}/manifest.yaml" \
    --zone="${ZONE}" \
    --machine-type="${MACHINE_SIZE}" \
    --scopes=storage-rw