#!/bin/bash

# Use
# ./removeuserspace <ssh_address> <server_fqdn (for kubectl)> <user>

export SERVER=$1
export FQDN=$2
export USER=$3

export CERT_DIR=$HOME/.kube/$FQDN/users/$USER
export CA_CERT_DIR=$HOME/.kube/$FQDN

export SERVER_USER_DIR="~/.kube/users/$USER"
export SERVER_NAME=$(echo "$FQDN" | sed 's/\./-/g')
export SERVER_USER="$USER-$SERVER_NAME"

export KUBECONFIG="$HOME/.kube/$USER-config"

echo "Checking if project namespace exists"
exists=$(ssh $SERVER "kubectl get namespace --output=jsonpath=\"{.items[?(@.metadata.name=='$USER')].metadata.name}\"")
if [ -z $exists ]; then
    echo "Namespace not found, nothing to delete"
    exit 1
else
    echo "Namespace exists, deleting"
fi

echo "Deleting user namespace"
ssh $SERVER "kubectl delete -f $SERVER_USER_DIR/namespace.yaml"

echo "Deleting remote cert dir"
ssh $SERVER "rm -rf $SERVER_USER_DIR"

echo "Deleting local cert dir"
rm -rf $CERT_DIR

echo "Removing from kubeconfig"
rm $KUBECONFIG
