#!/usr/bin/env bash
set -euo pipefail

PROJECT=${PROJECT:-""}
if [[ -z $PROJECT ]] ; then
    echo "PROJECT must be set" >&2
    exit 1
fi

REGION=${REGION:-""}
if [[ -z $REGION ]] ; then
    echo "REGION must be set" >&2
    exit 1
fi
region=${REGION}

ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
DEPLOY_ROOT="${ROOT}/deploy"
cd "${DEPLOY_ROOT}/scripts"
source "lib.sh"
lib::ensure_pulumi

pulumistate_bucket_name="dbaas-pulumistate-${PROJECT}"
if ! aws s3api head-bucket --bucket "${pulumistate_bucket_name}" ; then
    aws s3api create-bucket \
        --region "${region}" \
        --create-bucket-configuration LocationConstraint="${region}" \
        --bucket "${pulumistate_bucket_name}"
fi

cd "./pulumi"

# if node_modules dir does not exist then do npm install
[[ ! -d "./node_modules" ]] && npm install

# config to use remote s3 bucket as state backend
${PULUMI_BIN} login --cloud-url "s3://${pulumistate_bucket_name}"

# this will create a new pulumi stack using the project name and sets it to the active stack
${PULUMI_BIN} stack init "${PROJECT}"
# this will set the project value in the config
${PULUMI_BIN} config set central:project "${PROJECT}"
${PULUMI_BIN} config set aws:region "${region}"
