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

tar_build() {
  declare desc="builds apps from tarball via command line"
  local APP="$1"; verify_app_name "$APP"
  shift 1

  # clean up after ourselves
  local TAR_BUILD_TMP_WORK_DIR=$(mktemp -d "/tmp/dokku_tar.XXXX")
  trap 'rm -rf "$TAR_BUILD_TMP_WORK_DIR" > /dev/null' RETURN INT TERM EXIT

  # extract tar file
  chmod 755 "$TAR_BUILD_TMP_WORK_DIR"
  pushd "$TAR_BUILD_TMP_WORK_DIR" > /dev/null

  # Detect a common prefix that all files in the tar have, and strip off each directory found in it
  local COMMON_PREFIX=$(tar -tf "$DOKKU_ROOT/$APP/src.tar" | sed -e 'N;s/^\(.*\).*\n\1.*$/\1\n\1/;D')
  local BOGUS_PARTS=$(echo "$COMMON_PREFIX " | awk 'BEGIN{FS="/"} {print NF-1}')

  dokku_log_info1_quiet "Striping $BOGUS_PARTS worth of directories from tarball"

  tar -x -C "$TAR_BUILD_TMP_WORK_DIR" -f "$DOKKU_ROOT/$APP/src.tar" --strip-components="$BOGUS_PARTS"
  chmod -R u+r "$TAR_BUILD_TMP_WORK_DIR"

  if [[ -f Dockerfile ]] && [[ "$([[ -f .env ]] && grep -q BUILDPACK_URL .env; echo $?)" != "0" ]] && [[ ! -f ".buildpacks" ]]; then
    plugn trigger pre-receive-app "$APP" "dockerfile" "$TAR_BUILD_TMP_WORK_DIR"
    dokku_receive "$APP" "dockerfile" "$TAR_BUILD_TMP_WORK_DIR" | sed -u "s/^/"$'\e[1G'"/"
  else
    plugn trigger pre-receive-app "$APP" "herokuish" "$TAR_BUILD_TMP_WORK_DIR"
    dokku_receive "$APP" "herokuish" "$TAR_BUILD_TMP_WORK_DIR" | sed -u "s/^/"$'\e[1G'"/"
  fi
}

tar_in_cmd() {
  declare desc="deploys app from tarball on STDIN via command line"
  local cmd="tar:in"
  local APP="$2"

  verify_app_name "$2"
  tee "$DOKKU_ROOT/$APP/src.tar" | wc -c
  plugn trigger receive-app "$APP"
}

tar_from_cmd() {
  declare desc="deploys app from tarball at URL via command line"
  local cmd="tar:from"
  verify_app_name "$2"
  local APP=$2
  local URL=$3
  shift 3
  curl -# --insecure -L "$URL" | tar_in_cmd "tar:in" "$APP" "$@"
}
