#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
set -e
. "$STREAMPIPES_WORKDIR/bin/common"

remove_container=false

cli_help_restart() {
  cat <<EOF
Restart running StreamPipes containers

Usage: streampipes restart [OPTIONS] [SERVICE...]

Options:
  -f, --force-create   Remove container before restarting
EOF

  exit 1
}

[ "$1" == '--help' ] || [ "$1" == '-h' ] && cli_help_restart

if [ -z "$1" ]; then
    fatal "Argument missing, see 'streampipes ${0##*/} --help'"
fi

while [[ "$#" -gt 0 ]]; do
    case $1 in
        -f|--force-create) 
          if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
            remove_container=true
            svc=$2
            shift 2
          else
            fatal "Argument for $1 is missing" >&2
          fi
          ;;
        -*|--*=) fatal "Unsupported flag $1, see 'streampipes ${0##*/} --help'" >&2 ;;
        *) svc+=("$1"); shift ;;
    esac
done

remove_and_restart() {
    info "Removing and restarting ${svc[*]}"
    concatenate_compose_files
    run "$docker_compose_files rm --stop -f ${svc[*]}"
    run "$docker_compose_files up -d ${svc[*]}"
}

restart() {
    info "Restarting ${svc[*]}"
    concatenate_compose_files
    run "$docker_compose_files restart ${svc[*]}"  
}

if is_streampipes_running; then
    if [ "$remove_container" = true ]; then
      remove_and_restart
    else
      restart
    fi
else
  info "No StreamPipes environment running"
fi
