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

if ! [[ -z ${ENABLE_DEBUG+undefined-guard} ]] ; then
  set -x
fi
region=${REGION:-"us-west-2"}

ROOT=$(cd $(dirname ${BASH_SOURCE[0]}) && pwd)

if [[ -z ${ENV} ]] ; then
  echo "ENV must be set" && exit 1
fi
S3_BUCKET=${S3_BUCKET:-${ENV}-garden-state}

cd $ROOT
mkdir -p ${ENV}
cd ${ENV}

echo "`date` Prepare kubeconfig and acre.yaml"
aws eks --region $region update-kubeconfig --name ${ENV}-base-${region} --kubeconfig kubeconfig > /dev/null
$ROOT/${ENV}-acre.sh > acre.yaml

# only fallback to docker command when sow command is not present
if ! [ -x "$(command -v sow)" ]; then
  sow_image=gardener/sow:local
  docker build $ROOT/bin -t ${sow_image}
  export GOOGLE_APPLICATION_CREDENTIALS
  export SOW_IMAGE="${sow_image}"
  export PATH=$PATH:$ROOT/bin
fi

echo "`date` Start deploying Gardener"

if [[ ! -L "crop" ]]; then
  ln -s ../crop crop
fi

echo "`date` load state from s3"
aws s3 sync s3://${S3_BUCKET} ./ 1>/dev/null
tf_bin=gen/etcd/backupinfra/terraform/.terraform/plugins/linux_amd64/terraform-provider-aws_v2.60.0_x4
if [ -f $tf_bin ]; then
 chmod +x $tf_bin
fi
# if the landscape is already deployed, mark seed state to re-process seeds, so that we can add new seeds to current landscape
# TODO: a seed of an new provider cannot be added directly and requires sow deploy -A to refresh the whole landscape
if [[ -f state/gardencontent/seeds/soils/state.info ]]; then
    echo "reconcile" > state/gardencontent/coreproject/state.info
    echo "reconcile" > state/gardencontent/profiles/state.info
    echo "reconcile" > state/gardencontent/seeds/soils/state.info
fi
function snapshotData() {
  bucket=${1}
  if [[ ${2} == "deploy" ]]; then
    echo "`date` snapshot state to s3"
    aws s3 sync --delete ./export s3://${S3_BUCKET}/export 1>/dev/null || echo "no /export to snapshot"
    aws s3 sync --delete ./gen s3://${S3_BUCKET}/gen 1>/dev/null || echo "no /gen to snapshot"
    aws s3 sync --delete ./state s3://${S3_BUCKET}/state 1>/dev/null || echo "no /state to snapshot"
  fi
}
trap 'snapshotData ${S3_BUCKET} ${@}' TERM INT EXIT

sow ${@}

