#!/bin/bash

export K8NAMESPACE="flights-ui"

echo "Create namespace [$K8NAMESPACE] if doesn't exist"
kubectl --kubeconfig $KUBECONFIG get namespace | grep -q "^$K8NAMESPACE " || kubectl --kubeconfig $KUBECONFIG create namespace $K8NAMESPACE

function deployImage {
  export AFL_PRJ_NAME=$1
  echo -e "\E[1;34mDeploy $AFL_PRJ_NAME\E[1;0m"

  if [ "$IMAGE_PULL_SECRET" != "" ]
  then
    export IMAGE_PULL_SECRETS=$'      imagePullSecrets:\n      - name: '$IMAGE_PULL_SECRET$'\n'
  else
    export IMAGE_PULL_SECRETS=""
  fi

  echo "Using k8s yml file as following:"
  envsubst < ./k8s/$AFL_PRJ_NAME.yaml

  echo "Start kubectl apply..."
  envsubst < ./k8s/$AFL_PRJ_NAME.yaml | kubectl --kubeconfig $KUBECONFIG apply -n $K8NAMESPACE -f -

  echo -e "\E[1;34m ...done\E[1;0m"
}

function serve {
  NAME=$1
  PORT=$2
  echo -e "\E[1;34mService $1 at port $2\E[1;0m"

  cat <<EOF | kubectl --kubeconfig $KUBECONFIG apply -n $K8NAMESPACE -f /dev/stdin
apiVersion: v1
kind: Service
metadata:
  name: $NAME
  namespace: $K8NAMESPACE
spec:
  ports:
  - port: 80
    protocol: TCP
    targetPort: 8080
  selector:
    name: $NAME
  type: ClusterIP
EOF
}

function serveLB {
  NAME=$1
  PORT=$2
  echo -e "\E[1;34mService $1 at port $2\E[1;0m"

  cat <<EOF | kubectl --kubeconfig $KUBECONFIG apply -n $K8NAMESPACE -f /dev/stdin
apiVersion: v1
kind: Service
metadata:
  name: $NAME
  namespace: $K8NAMESPACE
spec:
  ports:
  - port: 80
    protocol: TCP
    targetPort: 8080
  selector:
    name: $NAME
  type: LoadBalancer
EOF
}

deployImage flights-ui
serveLB flights-ui
