#!/bin/bash

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

start_docker() {
  echo "$PROGNAME: Starting docker container \"$DOCKER_NAME\" ..."
  docker start "$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' c
do
  case $c in
    n) set_variable DOCKER_NAME "$OPTARG" ;;
    a) set_variable START_ALL YES ;;
    h|?) usage ;; esac
done

set_variable DOCKER_STATUS ""
set_variable PROGNAME "$(basename "$0")"
# set_variable CHECK_FILE "/tmp/DOCK_PREV_STATE"

# if [ -f "$CHECK_FILE" ] 
# then
#   read -r line<"$CHECK_FILE"
#   if [ "$line" != "running" ] 
#   then
#     rm "$CHECK_FILE" # The container was not runnin when stopped. Not starting it...
#   exit 0
#   fi
# fi

# rm "$CHECK_FILE"

  DOCKER_STATUS="$(/scripts/docker/docker_status.sh "$DOCKER_NAME")"
  case "$DOCKER_STATUS" in
    0)
    # "CRITICAL - $CONTAINER is already running."
    echo "$PROGNAME: Docker container \"$DOCKER_NAME\" already running"
    exit 0
    ;;
    1)
    # "WARNING - $CONTAINER state is restarting."
    echo "$PROGNAME: Docker container \"$DOCKER_NAME\" is restarting ..."
    exit 1
    ;;
    2)
    # "CRITICAL - $CONTAINER is not running."
    start_docker
    ;;
    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 "UNKNOWN - Container ID or Friendly Name Required"
    exit 1
    ;;
  esac      
# fi
