#!/bin/bash
#    Copyright 2015 Mirantis, Inc.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.


. "/usr/share/dockerctl/functions"
DEBUG=true

# Sets var nonopts
declare -a nonopts
parse_options "$@"
set -- "${nonopts[@]}"

# Parse config
confdir="/etc/dockerctl"
. "$confdir/config"

if [ -z "$1" ] || [ "$1" = "help" ]; then
  echo "Please specify a command."
  show_usage
  exit 1
fi

if [ -z "$2" ] || [ "$2" = "all" ]; then
  container="all"
else
  container=$2
fi

container_seq=$CONTAINER_SEQUENCE

case "$1" in
  build)
    if [[ "$container" == 'storage' ]]; then
      build_storage_containers
      run_storage_containers
    elif [[ "$container" == 'all' ]]; then
      # Step 1: prepare storage containers
      build_storage_containers
      run_storage_containers

      # Step 2: launch all in order, checking each one
      for service in $container_seq; do
        start_container $service
        check_ready $service
      done
    else
      start_container $container
    fi ;;
  check)
    if [[ "$container" == 'all' ]];then
      exit_code=0
      for service in $container_seq; do
        check_ready $service || exit_code=1
      done
      exit $exit_code
    else
      check_ready $container
    fi ;;
  create)
    create_container $container;;
  start)
    if [[ "$container" == 'all' ]]; then
      for service in $container_seq; do
        start_container $service
        check_ready $service
        sleep 4
      done
    else
      shift 2
      start_container $container $@
      if [[ ! "$@" =~ "--attach" ]]; then
        check_ready $container
      fi
    fi ;;
  post_start_hooks)
    shift 2
    post_start_hooks $container $@ ;;
  list)
    shift
    list_containers "$@" ;;
  shell)
    shift 2
    shell_container $container "$@" ;;
  copy)
    shift 1
    copy_files "$@" ;;
  restart|stop|revert|destroy)
    cmd=$1
    shift 2
    ${cmd}_container $container $@ ;;
  restore|backup)
    cmd=$1
    shift
    $cmd "$@" ;;
  logs|inspect)
    if [[ $2 == 'all' ]]; then
      echo "You need to specify valid container name."
      echo "Use 'dockerctl list' to see available containers."

      exit 1
    fi

    cmd=$1
    shift
    $cmd "$@" ;;
  *)
    echo 'Invalid selection.'
    show_usage
esac
