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

if [ -z "$1" ]; then
    echo "Environment name required: dev, test, prod, etc."
    exit 1
fi

service=$(basename $PWD)
if [ $service == "kong" ]; then
  service="restapi"
fi
if [ -z "${2-}" ]; then
    version_pushed=$(git rev-parse --short HEAD)
else
    version_pushed=$2
fi
environ=$1

if [ $environ == "dev" ]; then
  profile='marvel-dev'
elif [ $environ == "test" ]; then
  profile='marvel-test'
fi


chartname=helm/$service
namespace=marvel2-$environ
release=$service
hostnames={$service-$environ-marvel2.zooxlabs.com}

env_values_file=$chartname/values-$environ.yaml
if [ -f $env_values_file ]; then
  env_values_file_option="-f $env_values_file"
else
  env_values_file_option=''
fi

# Use Helm to deploy the service to the given k8s namespace
# Get Helm 3+ from https://github.com/helm/helm/releases
helm upgrade --install --debug \
    --namespace $namespace \
    $release ./$chartname \
    $env_values_file_option \
    --set image.tag=$version_pushed \
    --set environ=$environ \
    --set profile=$profile \
    --set ingress.hosts=$hostnames
#--set ingress.tls.hosts[0]=$hostname

# notify slack channel
if [ $environ == "test" ]; then
    message="{\"text\": \"Service $service version $version_pushed was pushed to test\"}"
    curl -X POST -H 'Content-type: application/json' --data "$message" https://hooks.slack.com/services/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
fi
