#!/bin/bash

service=$2
env=$(git branch --show-current)

if [[ -z "$1" || -z "$service" ]]; then
  echo "Usage: ./skaffold.sh <build|dev|run|render|deploy> <service-name>"
  echo "See https://git.zooxlabs.com/zooxco/driving/blob/$env/infra/helm/skaffold/README.md for documentation"
  exit 1
fi

if [ -z "$(which skaffold)" ]; then
  echo "You need to install skaffold: https://skaffold.dev/docs/install/"
  exit 2
fi

if [ -z "$(which container-structure-test)" ]; then
  echo "You need to install container-structure-test: https://github.com/GoogleContainerTools/container-structure-test#installation"
  exit 3
fi


cd $(dirname "$0");
project=$(basename $(pwd))

if [ "$project" == "skaffold" ]; then
  echo "ERROR: skaffold.sh was designed to be run from inside a zoox-base dependent helm chart."
  echo "See https://git.zooxlabs.com/zooxco/driving/blob/$env/infra/helm/skaffold/README.md for documentation"
  exit 1
fi

helm dep up || exit 4;

if [ $1 == "build" ]; then
  helm template ../skaffold -f values.yaml --set=global.project=$project --set=global.env=$env | \
    skaffold build -p $service -f -;
fi

if [ $1 == "dev" ]; then
  helm template ../skaffold -f values.yaml --set=global.project=$project --set=global.env=$env | \
    skaffold dev -p $service -f - --render-only=true;
fi

if [ $1 == "run" ]; then
  helm template ../skaffold -f values.yaml --set=global.project=$project --set=global.env=$env | \
    skaffold run -p $service -f - --render-only=true | tee $service.tmp && \
    cat $service.tmp | awk 'f;/# Source:/{f=1}' | \
    kubectl apply -n "$project-$env" -f - -l app.kubernetes.io/name=$service;
    rm -f $service.tmp
fi

if [ $1 == "render" ]; then
  helm template ../skaffold -f values.yaml --set=global.project=$project --set=global.env=$env | \
    skaffold render -p $service -f -;
fi

if [ $1 == "deploy" ]; then
  helm template ../skaffold -f values.yaml --set=global.project=$project --set=global.env=$env | \
    skaffold render --loud -p $service -f - --output=$service.tmp && \
    cat $service.tmp | awk 'f;/# Source:/{f=1}' | \
    kubectl apply -n "$project-$env" -f - -l app.kubernetes.io/name=$service;
    rm -f $service.tmp
fi
