#!/usr/bin/env bash

T="`mktemp`"
if [ "$1" = "-r" ]; then
  find .             -type f -regex ".*\/[0-9][0-9]\-.*\.\(yaml\|url\)$" > "$T"
  find .             -type d -regex ".*\/[0-9][0-9]\-ConfigMap\-.*$"     >> "$T"
else
  find . -maxdepth 1 -type f -regex ".*\/[0-9][0-9]\-.*\.\(yaml\|url\)$" > "$T"
  find . -maxdepth 1 -type d -regex ".*\/[0-9][0-9]\-ConfigMap\-.*$"     >> "$T"
fi
for f in $( sort -r "$T" ); do
  if [ -d "$f" ]; then
    if [[ "`basename $f`" =~ ^[0-9][0-9]-ConfigMap-.*$ ]]; then
      NAME=""
      NAMESPACE=""
      if [ ! -f "$f/config.json" ]; then
        echo "Warning: Missing $f/vars"
      else
        CFG="$f/config.json"
        NAME="`jq -r .name "$CFG"`"
        NAMESPACE="`jq -r .namespace "$CFG"`"
      fi
      FOUT="`mktemp`"
      cat <<EOF > $FOUT
apiVersion: v1
kind: ConfigMap
metadata:
  name: $NAME
  namespace: $NAMESPACE
EOF
      kubectl delete -f "$FOUT"
      rm "$FOUT"
    fi
  else
    EXT="`echo "$f" | tr '.' '\n' | tail -n 1`"
    if [ "$EXT" = "url" ]; then
      url=$(head -n 1 "$f" | tr -d '\n')
  echo "$url"
      kubectl delete -f "$url"
    else
      kubectl delete -f "$f"
    fi
  fi
done
rm "$T"

