#!/bin/sh

my_own_short_hostname="$(hostname -s)"

reset_communications()
{
  com_in_progress=0
  remote_responded=0
}

reset_communications

while true
do
  echo "I AM:$my_own_short_hostname"
  read answer

  case "$answer" in
    YMC-CONFIG-PASSWORD-PROVIDER)
      echo "REMOTE STARTS TALKING TO US..." 1>&2
      com_in_progress=1
      continue
    ;;

    GOODBYE)
      echo "REMOTE HUNG UP" 1>&2
      com_in_progress=0
      break
    ;;

    WAIT|"")
      echo "REMOTE WANTS TO WAIT" 1>&2
      sleep 1
      continue
    ;;

    "ERROR:"*)
      echo "ERROR FROM REMOTE:${answer#ERROR:}" 1>&2
      continue
    ;;

    "YOU ARE:"*)
      remote_said_we_are="${answer#YOU ARE:}"
      if [ "$remote_said_we_are" != "$my_own_short_hostname" ]; then
        echo "REMOTE IDENTIFIED US INCORRECT AS '$remote_said_we_are' - RESETTING COMMUNICATION..." 1>&2
        reset_communications
        continue
      fi
      echo "REMOTE NOW KNOWS US..." 1>&2
      remote_responded=1
      continue
    ;;

    *)
      if [ $com_in_progress -ne 1 ]; then
        echo "COMMUNICATION NOT INITIALIZED - SKIPPING WITH DELAY..." 1>&2
        sleep 0.1
        continue
      elif [ $remote_responded -ne 1 ]; then
        echo "REMOTE DOES NOT KNOW US - SKIPPING WITH DELAY..." 1>&2
        sleep 0.1
        continue
      fi
    ;;
  esac

  case "$answer" in
    "YOUR NEW PASSWORD:"*)
      new_password="${answer#YOUR NEW PASSWORD:}"
      if [ -z "$new_password" ]; then
        echo "REMOTE DID NOT GAVE US A VALID PASSWORD - RESETTING COMMUNICATION..." 1>&2
        reset_communications
        continue
      fi
      echo $new_password > /boot/ymccluster/host.password
      if [ $? -eq 0 ]; then
        echo "SUCCESSFULLY UPDATED PASSWORD" 1>&2
      else
        echo "FAILED TO STORED RETRIEVED PASSWORD - RESETTING COMMUNICATION..." 1>&2
        reset_communications
        continue
      fi
    ;;

    *)
      echo "REMOTE TOLD SOMETHING WE DO NOT UNDERSTAND:'$answer'" 1>&2
    ;;
  esac
done

