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

trigger-builder-herokuish-post-app-clone-setup() {
  declare desc="builder-herokuish post-app-clone-setup plugin trigger"
  declare trigger="post-app-clone-setup"
  declare OLD_APP="$1" NEW_APP="$2"

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

  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 || pushd "/tmp" >/dev/null

  if [[ -d "$NEW_CACHE_DIR" ]] && ! rmdir "$NEW_CACHE_DIR"; then
    local DOCKER_RUN_LABEL_ARGS="--label=com.dokku.app-name=$NEW_APP"
    "$DOCKER_BIN" container run "${DOCKER_RUN_LABEL_ARGS[@]}" $DOKKU_GLOBAL_RUN_ARGS --rm --volume "$NEW_CACHE_HOST_DIR:/cache" "dokku/$OLD_APP" chmod 777 -R /cache
  fi
  rm -rf "$NEW_CACHE_DIR"
}

trigger-builder-herokuish-post-app-clone-setup "$@"
