#!/bin/bash

# script/minikube_setup: Set up local AT-AT cluster on Minikube

source "$(dirname "${0}")"/../script/include/global_header.inc.sh

output_divider "Start Minikube"
minikube start

output_divider "Use Minikube Docker environment"
eval $(minikube docker-env)

output_divider "Build AT-AT Docker image for Minikube registry"
docker build . -t atat:latest

output_divider "Pull images for AT-AT cluster"
docker pull redis:5.0-alpine
docker pull postgres:11-alpine
docker pull nginx:alpine

output_divider "Apply AT-AT Kubernetes config to Minikube cluster"
kubectl --context=minikube create namespace atat
kubectl --context=minikube apply -f deploy/minikube/

output_divider "Create database and apply migrations"
# wait for the datastore deployment to become available
kubectl --context=minikube -n atat wait --for=condition=Available deployment/datastores
# postgres isn't necessarily running as soon as the pod is available, so wait a few
sleep 3
DB_POD=$(kubectl --context=minikube -n atat get pods -l app=db-cache -o custom-columns=NAME:.metadata.name --no-headers | sed -n 1p)
ATST_POD=$(kubectl --context=minikube -n atat get pods -l app=atst -o custom-columns=NAME:.metadata.name --no-headers | sed -n 1p)
kubectl --context=minikube -n atat exec -it $DB_POD -c postgres -- createdb -U postgres atat
kubectl --context=minikube -n atat exec -it $ATST_POD -c atst -- .venv/bin/python .venv/bin/alembic upgrade head
