#! /bin/bash

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"

if [ $1 = "switch" ]; then
    export PYTHONWARNINGS="ignore"
    echo "Using kubeconfig ${KUBECONFIG}"
    chmod 755 $KUBECONFIG
    clusters=$(gcloud container clusters list | grep ${2} | head -n 1)
    cluster_name=$(echo ${clusters} | awk '{print $1}' )
    zone=$(echo ${clusters} | awk '{print $2}' )
    echo "Switching to CLUSTER $cluster_name, ZONE $zone"
    gcloud container clusters get-credentials ${cluster_name} --zone ${zone} --project new-indico
    gcloud config set compute/zone ${zone}
fi

if [ $1 = "set-ns" ]; then
    namespace=$2
    if [ -z $namespace ]; then
        current_context=$(kubectl config current-context)
        kubectl config unset contexts.$current_context.namespace
    else
        kubectl config set-context --current --namespace $namespace
    fi
fi

if [ $1 = "get-ns" ]; then
    namespace=$(kubectl config view -o jsonpath='{.contexts[?(@.name=="'"$(kubectl config current-context)"'")].context.namespace}')
    if [[ $2 == "raw" ]]; then
        echo -e $namespace
    else
        echo -e "\\[\e[33m\\]${namespace}\\[\e[m\\]"
    fi
fi

if [ $1 = "exec" ]; then
    kubectl exec -it $(kubectl get pods | grep $2 | head -n 1 | awk '{print $1}') ${3:-bash}
fi

if [ $1 = "pods" ]; then
    indico pod ls
fi

if [ $1 = "update" ]; then
    indico svc restart ${@:2}
fi

if [ $1 = "apply" ]; then
    indico apply ${@:2}
fi

if [ $1 = "taints" ]; then
    kubectl get nodes -o json | jq '.items[].spec | .providerID, .taints'
fi

if [ $1 = "get-env" ]; then
    gcloud container clusters list --filter="resourceLabels.environment=${2}" | tail -n +2 | awk '{print $1}'
fi

if [ $1 = "scale" ]; then
    indico svc scale ${@:2}
fi

if [ $1 = "scale-cluster-nodes" ]; then
    # example: 'kube scale-cluster-nodes dev-mycluster down`
    cluster=$2
    action=$3
    limit=${4:-5}
    nodepools=$(gcloud container node-pools list --cluster $cluster | tail -n +2 | awk '{print $1}')
    ephemeral=$(gcloud container clusters list --filter="resourceLabels.ephemeral=true" | tail -n +2 | awk '{print $1}' | grep -w $cluster)
    if [ -z $ephemeral ]; then
        echo "Cluster $cluster is not labeled for scaling"
    else
        for pool in ${nodepools[@]}; do
            kube toggle-autoscale $cluster $pool $action $limit
        done
        echo "Done toggling autoscaling"
        for pool in ${nodepools[@]}; do
            kube scale-pool-$action $cluster $pool
        done
    fi
fi

if [ $1 = "scale-pool-down" ]; then
    cluster=$2
    pool=$3
    echo "Scaling down $pool pool in $cluster"
    gcloud container clusters resize $cluster --node-pool=$pool --num-nodes=0 --quiet
fi

if [ $1 = "scale-pool-up" ]; then
    cluster=$2
    pool=$3
    echo "Scaling up $pool pool in $cluster"
    gcloud container clusters resize $cluster --node-pool=$pool --num-nodes=1 --quiet
fi

if [ $1 = "toggle-autoscale" ]; then
    cluster=$2
    pool=$3
    action=$4
    limit=${5:-3}
    if [[ $action = "up" ]]; then
        echo "Enabling cluster auto-scaling in $pool pool in $cluster"
        gcloud container clusters update $cluster --node-pool $pool --min-nodes 0 --max-nodes $limit --enable-autoscaling --quiet
    elif [[ $action = "down" ]]; then
        echo "Disabling cluster auto-scaling in $pool pool in $cluster"
        gcloud container clusters update $cluster --node-pool $pool --min-nodes 0 --max-nodes $limit --no-enable-autoscaling --quiet
    fi
fi

if [ $1 = "get-cluster" ]; then
      cluster_name=$(kubectl config current-context | awk -F "_" '{print $NF}')
      if [[ $cluster_name == *"dev"* ]]; then
            color="92"
      fi

      if [[ $cluster_name == *"stage"* ]]; then
            color="34"
      fi

      if [[ $cluster_name == *"prod"* ]]; then
            color="91"
      fi

      if [[ $2 == "raw" ]]; then
          echo -e $cluster_name
      else
          echo -e "\\[\e[${color}m\\]${cluster_name}\\[\e[m\\]"
      fi
fi

if [ $1 = "gen" ]; then
    api=$2
    queue=$3
    tag=$4
    workers=${5:-1}
    scaling=${6:-1}

    helm template -f $DIR"/../values/api.yaml" $DIR"/../worker" --set api.name=$api,api.queue=$queue,api.workers=$workers,image.tag=$tag,scaling.default=$scaling> $DIR"/../kubernetes/build/${tag}/${api}${queue}.yaml"
fi

if [ $1 = "image" ]; then
    deployment=$2
    image=$3
    kubectl set image --record=true deployment/${deployment} ${deployment}=${image}
fi

if [ $1 = "drain" ]; then
    kubectl drain $2 --ignore-daemonsets --delete-local-data
fi

if [ $1 = "images" ]; then
    kubectl get pods -o custom-columns=NAME:.metadata.name,IMAGE:{.status.containerStatuses[0].image} | grep "$2"
fi

if [ $1 = "top" ]; then
    kubectl top pods | sort -nk 3 -
fi

if [ $1 = "rbac" ]; then
    kubectl create clusterrolebinding cluster-admin-binding-$(echo $2 | awk -F "@" '{print $1}') --clusterrole cluster-admin --user $2
fi

if [ $1 = "reset" ]; then
    instance=$2
    kubectl cordon ${instance}
    gcloud compute instances reset $instance
    sleep 10
    gcloud compute ssh $instance --command "sudo service kubelet restart"
fi

if [ $1 = "cluster" ]; then
    indico infra gke create ${@:2}
    kube switch $2
    email=$(cat /indico-deployment/.config/gcloud/configurations/config_default | grep account | awk -F "=" '{print $2}')

    kube rbac $email
fi

if [ $1 = "sync-images" ]; then
    indico sync images $2
fi

if [ $1 = "istio" ]; then
    kubectl create namespace istio-system
    helm template /istio-$ISTIO_VERSION/install/kubernetes/helm/istio-init --name istio-init --namespace istio-system | kubectl apply -f -
fi
