#!/bin/bash

SLEEP=$1

if [[ "$SLEEP" == "" ]]; then
    echo "sm-wait: ERROR: missing argument"
    exit 1
fi

if [[ "$SLEEP" == "stop" ]]; then
    echo "sm-wait: Stopping all waiting processes." \
      | tee /proc/1/fd/1
    touch /tmp/sm-wait-stopped
    sleep 5  # wait for new processes to respawn
    pkill sm-wait
    exit
fi


if [[ "$SLEEP" == 0 ]]; then
    exit
fi

if [[ -f /tmp/sm-wait-stopped ]]; then
  echo "sm-wait: Exiting, because sm-wait was already stopped."
  exit
fi


terminate() {
    echo "sm-wait: Gracefully terminated." 
    exit
}

trap terminate SIGTERM
trap terminate SIGINT

echo "sm-wait: Waiting for $SLEEP seconds to let you prepare you connection. "\
  "Once you're ready, run 'sm-wait stop' inside the container or 'sm-local-ssh-* stop-waiting' "\
  "from your local machine."

for loop in $(seq 1 1 "$SLEEP") 
do
    sleep 1
    SSM_PID=$(pgrep -f amazon-ssm-agent)
    if [[ "$SSM_PID" == "" ]]; then
      AGENT_INFO="SSM Agent has NOT been started yet."
    else
      AGENT_INFO="SSM Agent has been already started."
    fi

    if [[ "$((loop % 10))" == "0" ]]; then
      echo "sm-wait: Still waiting ($loop)... $AGENT_INFO"
    fi
done

echo "sm-wait: Waiting complete. No 'stop' command received. Had SSM initialization failed? Do you need to increase timeout?"
