#!/bin/bash
# pdscp - Proxmox Dataset Copy Tool
# Using zynclib for ZFS replication
VERSION="0.2.0"
set -euo pipefail

TOOL_NAME="pdscp"
TOOL_LOGNAME="Transfer"

DAEMON_LIB="${DAEMON_LIB:-/usr/lib/pvmzync/daemon_lib}"
source "$DAEMON_LIB" || { echo "ERROR: daemon_lib not found" >&2; exit 1; }
source "$ZYNCLIB"     || { echo "ERROR: zynclib not found" >&2; exit 1; }

show_usage() {
  cat <<EOF
USAGE:
  pdscp <dataset> <REMOTE_HOST> [OPTIONS]
  pdscp              # monitor running transfer

DESCRIPTION:
  Copy an arbitrary ZFS dataset between Proxmox (or any ZFS) nodes.
  Uses ZFS send/recv via zynclib for efficient incremental transfers.
  Only one transfer can run at a time.

  For copying VMs/LXCs, use pvmcp(1).

  By default pushes from local to remote. Use --pull to reverse.

CONSTRAINTS:
  - One side must always be the local host.
  - Dataset path must contain a '/' (e.g., tank/backups).

  No arguments:
    If a transfer is running — monitor it (live log).
    If no transfer is running — show this help.

OPTIONS:
  --pull           Pull from remote instead of push (default: push).
  --savelogs       Save all logs to pdscp_logs_<timestamp>.tar.gz.
  -h, --help       Display this help message.

EXAMPLES:
  pdscp tank/backups pve-02          # Push dataset tank/backups to pve-02
  pdscp rpool/data pve-01 --pull     # Pull rpool/data from pve-01
  pdscp                               # Monitor running transfer

SEE ALSO:
  pvmcp(1) - Copy VMs/LXCs between nodes
  pvmig(1) - Migrate VMs within a cluster
EOF
}

# --- Argument parsing ---

parse_args() {
  declare -g dataset remote_host

  while [[ $# -gt 0 ]]; do
    case "$1" in
      -h|--help)
        show_usage
        exit 0
        ;;
      --pull)
        direction="pull"
        shift
        ;;
      --savelogs)
        SAVELOGS=true
        shift
        ;;
      -*)
        error "Unknown option: $1"
        ;;
      *)
        if [[ -z "${dataset:-}" ]]; then
          [[ "$1" == */* ]] || error "Dataset must contain '/' (e.g., tank/backups). For VMs, use pvmcp."
          dataset="$1"
        elif [[ -z "${remote_host:-}" ]]; then
          remote_host="$1"
        else
          error "Unknown argument: $1"
        fi
        shift
        ;;
    esac
  done

  [[ -z "${dataset:-}" ]]     && error "Dataset is required"
  [[ -z "${remote_host:-}" ]] && error "REMOTE_HOST is required"
  return 0
}

# --- Main tool logic ---

tool_main() {
  log "=== DATASET COPY MODE ==="
  log "Dataset: $dataset | Direction: $direction | Target: $remote_host"

  src_ds="$dataset"
  dst_ds="$dataset"

  ssh_src "zfs list -H $src_ds" >/dev/null 2>&1 || \
    error "Dataset '$src_ds' not found on $src_host"

  if ! zfs_sync_dataset; then
    error "Failed: $dataset; Log: $TRANSFERLOG"
  fi

  local summary=$(bash "$ZFS_ANALYZER" "$TRANSFERLOG" --summary 2>/dev/null)
  log "✓ dataset synced: $summary"
  log "=== COPY COMPLETE ==="
  log "Dataset $dataset successfully synced to $remote_host"
}

main "$@"
