#!/bin/bash
ROOT=${ROOT:-.}
{%- set use_credentials = "" %}
{%- if k8s_deploy.tls_path %}
{%- for prxy in k8s_deploy.prxyGatewayServers %}
{%- if prxy.tls and prxy.tls.credentialName and k8s_deploy.prxy == "istio" %}
{%- set_global use_credentials = prxy.tls.credentialName %}
{% break %}
{%- endif %}
{%- endfor %}
if [ -r "$ROOT/{{k8s_deploy.tls_path}}/fullchain.pem" ] ; then
   {%- if use_credentials != "" and k8s_deploy.prxy == "istio" %}
   [ -x "$ROOT/make_istio-system_secret.sh" ] && $ROOT/make_istio-system_secret.sh $ROOT/{{k8s_deploy.tls_path}}
   {%- else %}
   kubectl delete secret {{k8s_deploy.name}}-certs -n {{k8s_deploy.namespace}} 2>/dev/null
   kubectl create secret tls {{k8s_deploy.name}}-certs --cert=$ROOT/{{k8s_deploy.tls_path}}/fullchain.pem --key=$ROOT/{{k8s_deploy.tls_path}}/privkey.pem -n {{k8s_deploy.namespace}}
   {%- endif %}
else
   echo "No SSL certificate"
   exit
fi
{%- endif %}
echo "checking configMaps ..."
if [ -r "$ROOT/configMap-etc.yaml" ] ;then
kubectl delete -f $ROOT/configMap-etc.yaml 2>/dev/null
kubectl apply -f $ROOT/configMap-etc.yaml
fi

kubectl delete -f $ROOT/{{k8s_deploy.name}}.yaml 2>/dev/null
kubectl delete -f $ROOT/srvc-{{k8s_deploy.name}}.yaml 2>/dev/null

if [ -r "$ROOT/prxy-virtual-srvc-{{k8s_deploy.name}}.yaml" ] ; then
kubectl delete -f $ROOT/prxy-virtual-srvc-{{k8s_deploy.name}}.yaml 2>/dev/null
kubectl delete -f $ROOT/prxy-gateway-{{k8s_deploy.name}}.yaml 2>/dev/null
fi

if [ -r "$ROOT/srvc-{{k8s_deploy.name}}.yaml" ] ; then
kubectl apply -f $ROOT/srvc-{{k8s_deploy.name}}.yaml
fi
if [ -r "$ROOT/prxy-virtual-srvc-{{k8s_deploy.name}}.yaml" ] ; then
kubectl apply -f $ROOT/prxy-virtual-srvc-{{k8s_deploy.name}}.yaml
kubectl apply -f $ROOT/prxy-gateway-{{k8s_deploy.name}}.yaml
fi
kubectl apply -f $ROOT/{{k8s_deploy.name}}.yaml

{%- if k8s_deploy.full_domain %}
echo "{{k8s_deploy.full_domain}} reload ..."
curl -s -o /dev/null -I -w "%{http_code}" https://{{k8s_deploy.full_domain}}
{%- endif %}
echo "__oOo__________oOo__________oOo__"
