#!/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 "$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
data:
EOF
      FILES="`mktemp`"
      find "$f" -type f > "$FILES"
      for FILE in $(cat "$FILES"); do
        BASENAME="`basename "$FILE"`"
        if [ "$BASENAME" != "config.json" ]; then
          jq -e ".base64[] | select(. == \"$BASENAME\")" "$CFG" > /dev/null
          if [ $? -eq 0 ]; then
            echo "  $BASENAME.base64: |" >> "$FOUT"
            base64 "$FILE" | tr -d '\n' | sed "s/^/    /" >> "$FOUT"
            echo "" >> "$FOUT"
          else
            echo "  $BASENAME: |" >> "$FOUT"
            sed "s/^/    /" "$FILE" >> "$FOUT"
          fi
        fi
      done
      rm "$FILES"
      kubectl apply -f "$FOUT"
      rm "$FOUT"
    else
      echo "Dunno: $f"
    fi
  else
    D="`dirname "$f"`"
    if [ -f "$D/env" ]; then
      source "$D/env"
    fi
    EXT="`echo "$f" | tr '.' '\n' | tail -n 1`"
    if [ "$EXT" = "url" ]; then
      url=$(head -n 1 "$f" | tr -d '\n')
      kubectl apply -f "$url"
    else
      envsubst < "$f" | kubectl apply -f -
      if [ $? -ne 0 ]; then
        echo "🔴 $f"
      fi
    fi
  fi
done
rm "$T"
