#!/usr/bin/env bash

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"

usage() {
  cat <<'EOF' >&2
usage: publish <owner> <dataset-uuid> [options]

Copies a staged shareable dataset bundle from:
  ./users/<owner>/datasets/share/<uuid>

to:
  ./shared/datasets/<uuid>

options:
  --force               Replace an existing target bundle
  --source-root <path>  Override the default source root (default: ./users)
  --target-root <path>  Override the default target root (default: ./shared/datasets)
EOF
  exit 1
}

OWNER="${1:-}"
DATASET_UUID="${2:-}"
shift $(( $# > 0 ? 1 : 0 ))
shift $(( $# > 0 ? 1 : 0 ))

[[ -n "$OWNER" && -n "$DATASET_UUID" ]] || usage

FORCE=0
SOURCE_ROOT="$ROOT_DIR/users"
TARGET_ROOT="$ROOT_DIR/shared/datasets"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --force)
      FORCE=1
      shift
      ;;
    --source-root)
      [[ $# -ge 2 ]] || usage
      SOURCE_ROOT="$2"
      shift 2
      ;;
    --target-root)
      [[ $# -ge 2 ]] || usage
      TARGET_ROOT="$2"
      shift 2
      ;;
    *)
      usage
      ;;
  esac
done

SOURCE_DIR="$SOURCE_ROOT/$OWNER/datasets/share/$DATASET_UUID"
TARGET_DIR="$TARGET_ROOT/$DATASET_UUID"

[[ -d "$SOURCE_DIR" ]] || {
  echo "share bundle not found: $SOURCE_DIR" >&2
  exit 1
}

mkdir -p "$TARGET_ROOT"

if [[ -e "$TARGET_DIR" ]]; then
  if (( FORCE )); then
    rm -rf "$TARGET_DIR"
  else
    echo "target already exists: $TARGET_DIR" >&2
    echo "rerun with --force to replace it" >&2
    exit 1
  fi
fi

cp -R "$SOURCE_DIR" "$TARGET_DIR"

echo "published dataset"
echo "owner: $OWNER"
echo "uuid: $DATASET_UUID"
echo "source: $SOURCE_DIR"
echo "target: $TARGET_DIR"
