#!/usr/bin/env bash
source "$(dirname "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)")/config"
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"
source "$(dirname "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)")/functions"

service-clone-cmd() {
  #E you can clone an existing service to a new one
  #E dokku $PLUGIN_COMMAND_PREFIX:clone lollipop lollipop-2
  #A service, service to run command against
  #A new-service, name of new service
  #F -c|--config-options "--args --go=here", extra arguments to pass to the container create command
  #F -C|--custom-env "USER=alpha;HOST=beta", semi-colon delimited environment variables to start the service with
  #F -i|--image IMAGE, the image name to start the service with
  #F -I|--image-version IMAGE_VERSION, the image version to start the service with
  #F -m|--memory MEMORY, container memory limit in megabytes (default: unlimited)
  #F -N|--initial-network INITIAL_NETWORK, the initial network to attach the service to
  #F -p|--password PASSWORD, override the user-level service password
  #F -P|--post-create-network NETWORKS, a comman-separated list of networks to attach the service container to after service creation
  #F -r|--root-password PASSWORD, override the root-level service password
  #F -S|--post-start-network NETWORKS, a comman-separated list of networks to attach the service container to after service start
  #F -s|--shm-size SHM_SIZE, override shared memory size for $PLUGIN_COMMAND_PREFIX docker container
  declare desc="create container <new-name> then copy data from <name> into <new-name>"
  local cmd="$PLUGIN_COMMAND_PREFIX:clone" argv=("$@")
  [[ ${argv[0]} == "$cmd" ]] && shift 1
  declare SERVICE="$1" NEW_SERVICE="$2" CLONE_FLAGS_LIST=("${@:3}")
  is_implemented_command "$cmd" || dokku_log_fail "Not yet implemented"

  [[ -z "$SERVICE" ]] && dokku_log_fail "Please specify a valid name for the service"
  [[ -z "$NEW_SERVICE" ]] && dokku_log_fail "Please specify a name for the new service"
  verify_service_name "$SERVICE"
  if service_exists "$NEW_SERVICE"; then
    dokku_log_fail "Invalid service name $NEW_SERVICE. Verify the service name is not already in use."
  fi

  local SERVICE_ROOT="$PLUGIN_DATA_ROOT/$SERVICE"
  local ID="$(cat "$SERVICE_ROOT/ID")"
  is_container_status "$ID" "Running" || dokku_log_fail "Service ${SERVICE} container is not running"

  PLUGIN_IMAGE=$(service_version "$SERVICE" | grep -o "^.*:" | sed -r "s/://g")
  PLUGIN_IMAGE_VERSION=$(service_version "$SERVICE" | grep -o ":.*$" | sed -r "s/://g")

  service_parse_args "${@:3}"

  dokku_log_info2 "Cloning $SERVICE to $NEW_SERVICE @ $PLUGIN_IMAGE:$PLUGIN_IMAGE_VERSION"
  service_create "$NEW_SERVICE" "${@:3}"
  dokku_log_info1 "Copying data from $SERVICE to $NEW_SERVICE"
  service_export "$SERVICE" | service_import "$NEW_SERVICE" >/dev/null 2>&1 || true
  dokku_log_info2 "Done"
}

service-clone-cmd "$@"
