#!/bin/bash

date +"%R STARTING BUILD"

ONLINE_TRIAL_PATH="$HOME/tmp/packer/online-trial"
COOKBOOK_PATHS="$ONLINE_TRIAL_PATH/cookbooks"
DATA_BAGS_PATH="$ONLINE_TRIAL_PATH/data_bags"

if [ -d $ONLINE_TRIAL_PATH ]
  then rm -rf $ONLINE_TRIAL_PATH/*
  else mkdir -p $ONLINE_TRIAL_PATH
fi

mkdir -p $COOKBOOK_PATHS $DATA_BAGS_PATH

export GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
export DATABAGS_FOLDER_PATH=$DATA_BAGS_PATH
export COOKBOOK_FOLDER_PATH=$COOKBOOK_PATHS

if [ -z "$AWS_ACCESS_KEY_ID" ]; then
  while [ -z "$AWS_ACCESS_KEY_ID" ]; do
    printf '%s ' 'Insert valid AWS ACCESS KEY '
    read AWS_ACCESS_KEY_ID
    export AWS_ACCESS_KEY_ID
  done
fi
if [ -z "$AWS_SECRET_ACCESS_KEY" ]; then
  while [ -z "$AWS_SECRET_ACCESS_KEY" ]; do
    printf '%s ' 'Insert valid AWS SECRET KEY '
    read -s AWS_SECRET_ACCESS_KEY
    export AWS_SECRET_ACCESS_KEY
  done
fi

if [ -z "$MVN_CHEF_REPO_USERNAME" ]; then
  while [ -z "$MVN_CHEF_REPO_USERNAME" ]; do
    printf '%s ' 'Insert valid maven username '
    read MVN_CHEF_REPO_USERNAME
    export MVN_CHEF_REPO_USERNAME
  done
fi
if [ -z "$MVN_CHEF_REPO_PASSWORD" ]; then
  while [ -z "$MVN_CHEF_REPO_PASSWORD" ]; do
    printf '%s ' 'Insert valid maven password '
    read -s MVN_CHEF_REPO_PASSWORD
    export MVN_CHEF_REPO_PASSWORD
  done
fi

rm -f Berksfile.lock

packer validate packer/img-trials-packer.json

#packer build -debug packer/img-trials-packer.json | gawk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0; fflush(); }'
packer build packer/img-trials-packer.json
