#!/usr/bin/env bash
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"
source "$PLUGIN_AVAILABLE_PATH/apps/functions"
source "$PLUGIN_AVAILABLE_PATH/ps/functions"

cmd-apps-clone() {
  declare desc="clones an app"
  declare cmd="apps:clone"
  [[ "$1" == "$cmd" ]] && shift 1
  declare OLD_APP="$1" NEW_APP="$2"
  local IGNORE_EXISTING=false SKIP_REBUILD=false

  for arg in "$@"; do
    [[ "$arg" == "--skip-deploy" ]] && shift 1 && SKIP_REBUILD=true
    [[ "$arg" == "--ignore-existing" ]] && shift 1 && IGNORE_EXISTING=true
    [[ "$arg" =~ ^--.* ]] || break
  done

  OLD_APP="$1" NEW_APP="$2"
  [[ -z "$OLD_APP" ]] && dokku_log_fail "Please specify an app to run the command on"

  is_valid_app_name "$OLD_APP"
  is_valid_app_name "$NEW_APP"
  apps_exists "$OLD_APP" >/dev/null 2>&1 || dokku_log_fail "App does not exist"
  if apps_exists "$NEW_APP" >/dev/null 2>&1; then
    if [[ "$IGNORE_EXISTING" == true ]]; then
      dokku_log_warn "Name is already taken"
      return
    fi

    dokku_log_fail "Name is already taken"
  fi

  dokku_log_info1_quiet "Cloning $OLD_APP to $NEW_APP"
  apps_create "$NEW_APP"
  plugn trigger post-app-clone-setup "$OLD_APP" "$NEW_APP"
  SKIP_REBUILD=$SKIP_REBUILD plugn trigger post-app-clone "$OLD_APP" "$NEW_APP"
}

cmd-apps-clone "$@"
