#!/bin/bash

# USER=ubuntu register-dock 10.92.128.111 <moniker>
MONIKER=${1:-none}

if [ $MONIKER == "none" ]; then
  echo "This script will search for registered monikers and removes the entry for the passed in"
  echo "moniker"
  echo
  echo "NOTE: This script is potentially destructive:"
  echo "  - On the client it will overwrite certificates in ~/.docker/"
  echo
  echo "Usage:"
  echo "    $ unregister-dock <IP | moniker>"
  echo "        - 'IP' or 'moniker' is the registered details of the instance"
  echo
  echo "    Examples:"
  echo "    $ unregister-dock 10.93.133.6"
  echo "    $ unregister-dock project-dev"
  exit 1
fi

# Look up IP from moniker
FOUND_MONIKER=false
FOUND_PATH=
for f in $HOME/.docker/*; do
    if [ -d $f ] && [ -f $f/connection_config.txt ]; then
      while read -r line; do declare $line; done < "$f/connection_config.txt"
      if [ $DOCK_MONIKER = $MONIKER ] || [ $DOCK_IP = $MONIKER ]; then
        FOUND_MONIKER=true
        FOUND_PATH="${f}"
        break
      fi
    fi
done

if [ "$FOUND_MONIKER" = "false" ]; then
  echo "No moniker found"
  exit 0
fi

echo "Removing ${FOUND_PATH}"
rm -rf $FOUND_PATH
