#!/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"

apps_clone_cmd() {
  declare desc="clones an app"
  declare cmd="apps:clone" argv=("$@")
  [[ ${argv[0]} == "$cmd" ]] && shift 1
  declare OLD_APP="$1" NEW_APP="$2"
  local IGNORE_EXISTING=false
  local 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

  local NEW_CACHE_DIR="$DOKKU_ROOT/$NEW_APP/cache"
  local NEW_CACHE_HOST_DIR="$DOKKU_HOST_ROOT/$NEW_APP/cache"

  apps_create "$NEW_APP"
  pushd "$DOKKU_ROOT/$OLD_APP/." >/dev/null
  find ./* \( -name ".cache" -o -name "cache" \) -prune -o -print | cpio -pdmu --quiet "$DOKKU_ROOT/$NEW_APP"
  popd >/dev/null 2>&1 || pushd "/tmp" >/dev/null
  plugn trigger post-app-clone-setup "$OLD_APP" "$NEW_APP"

  if [[ -d "$NEW_CACHE_DIR" ]] && ! rmdir "$NEW_CACHE_DIR"; then
    docker run "$DOKKU_GLOBAL_RUN_ARGS" --rm -v "$NEW_CACHE_HOST_DIR:/cache" "dokku/$OLD_APP" chmod 777 -R /cache
  fi
  rm -rf "$NEW_CACHE_DIR"

  [[ -f "$DOKKU_ROOT/$NEW_APP/hooks/pre-receive" ]] && sed -i -e "s/git-hook $OLD_APP/git-hook $NEW_APP/g" "$DOKKU_ROOT/$NEW_APP/hooks/pre-receive"
  [[ "$SKIP_REBUILD" == "true" ]] || ps_rebuild "$NEW_APP"
  plugn trigger post-app-clone "$OLD_APP" "$NEW_APP"
  dokku_log_info1_quiet "Cloning $OLD_APP to $NEW_APP... done"
}

apps_clone_cmd "$@"
