#!/bin/bash

usage()
{
  echo "Usage: $0 [-n DOCKER_NAME] [ -a STOP_ALL ]"
  exit 2
}

stop_docker() {
  echo "$PROGNAME: Stopping docker container \"$DOCKER_NAME\" ..."
  docker stop "$DOCKER_NAME"
  exit 0
}

set_variable()
{
  local varname=$1
  shift
  if [ -z "${!varname}" ]; then
    eval "$varname=\"$@\""
  else
    echo "Error: $varname already set"
    usage
  fi
}

####################################################################
# Main script starts here

while getopts "n:a?h" option
do
  case "${option}" in
    n) set_variable DOCKER_NAME "${OPTARG}" ;;
    a) set_variable YES ;;
    h|?) usage ;;
    *) usage ;; esac
done

set_variable DOCKER_STATUS ""
set_variable DOCK_PREV_STATE ""
set_variable PROGNAME "$(basename "$0")"

# ---------------
# Error Handling
# ---------------
# set -e
# trap 'catch $? $LINENO' EXIT
# catch() {
#   echo "catching!"
#   if [ "$1" != "0" ]; then
#     # error handling goes here
#     echo "Error $1 occurred on $2 in $PROGNAME"
#   fi
# }
# ---------------
# Error Handling
# ---------------

if [ "$STOP_ALL" == "YES" ]
then  
  echo "stop all"
else
  DOCKER_STATUS="$(/scripts/docker/docker_status.sh "$DOCKER_NAME")"
  DOCK_PREV_STATE=$(curl --request GET --url http://127.0.0.1:8126/container/"$DOCKER_NAME" | jq '.state')
  echo "$DOCK_PREV_STATE" > /tmp/DOCK_PREV_STATE

  case "$DOCKER_STATUS" in
    0)
    # container running
    stop_docker
    ;;
    1)
    # container restarting
    echo "$PROGNAME: Docker container \"$DOCKER_NAME\" is restarting ..."
    exit 1
    ;;
    2)
    # container stopped
    echo "$PROGNAME: Docker container \"$DOCKER_NAME\" is already stopped ..."
    exit 0
    ;;
    3)
    # container unknown
    echo "$PROGNAME: UNKNOWN - Docker container \"$DOCKER_NAME\" is unknown"  
    exit 1
    ;;
    4)
    # "UNKNOWN - Unable to talk to the docker daemon"
    echo "$PROGNAME: UNKNOWN - Unable to talk to the docker daemon"    
    exit 1
    ;;
    5)
    # "UNKNOWN - Missing docker binary"
    echo "$PROGNAME: UNKNOWN - Missing docker binary"    
    exit 1
    ;;
    6)
    # "UNKNOWN - Container ID or Friendly Name Required"
    echo "$PROGNAME: UNKNOWN - Container ID or Friendly Name Required"
    exit 1
    ;;
  esac      
fi
