#!/usr/bin/env bash

# Usage: p42 build [<component>...]
# Summary: Build one or more components for an application.
# Help: Build one or more components for an application.
#
#    p42 build www
#

source ${lib}/context.sh

if [ $# -gt 0 ]; then
  components="$@"
else
  if [ ! -d ./launch ]; then
    echo p42: nothing to build
    exit
  fi
  components=$(ls ./launch)
fi

# TODO: what if the swarm master dies?
eval $(docker-machine env --swarm ${cluster}-00)

eval $(aws ecr get-login --region us-east-1) > /dev/null

for component in $components; do
  label=$name-$component
  echo "Building ${label} component..."

  # instantiate mixin templates, if any
  yaml=./launch/$component/config.yaml
  templates=$(ls ./launch/$component/*.template 2> /dev/null)
  for template in $templates; do
    output=${template%.template}
    cat > $output <<EOF
# WARNING:
# This file was automatically generated!
#
# To make changes, edit
#   $(basename $template)
# instead.

$(yaml template $yaml $template)
EOF
  done

  docker build \
    -t "${registry}/${label}" \
    -f "launch/${component}/Dockerfile" \
    .

  if [ ! "$(aws ecr describe-repositories \
    --repository-name ${label} \
    --region us-east-1)" ]; then
    echo "Creating repository '${label}'..."
    aws ecr create-repository \
      --repository-name "${label}" \
      --region us-east-1 \
      > /dev/null
    policy=$(yaml json write "${share}/ecr/policy.yaml")
    aws ecr set-repository-policy \
      --repository-name "${label}" \
      --region us-east-1 \
      --policy-text "${policy}"
  fi

  echo "Pushing $label component..."
  docker push "${registry}/${label}"

done
