#!/usr/bin/env bash

die() {
  echo "$*" >&2
  exit 1
}

sanitize_cluster_ids() {
  local raw="$1"
  local compact="${raw//[[:space:]]/}"
  if [[ ! "${compact}" =~ ^[0-9]+(,[0-9]+)*$ ]]; then
    die "invalid CLUSTER_IDS: must be comma-separated integers"
  fi
  printf '%s\n' "${compact}"
}

sanitize_import_id() {
  local raw="$1"
  local compact="${raw//[[:space:]]/}"
  if [[ ! "${compact}" =~ ^[0-9]+$ ]]; then
    die "invalid PROBE_IMPORT_ID: must be an integer"
  fi
  printf '%s\n' "${compact}"
}

build_cluster_filter() {
  local cluster_ids="${1:-}"
  local compact="${cluster_ids//[[:space:]]/}"
  if [[ -z "${compact}" ]]; then
    printf '1=1\n'
    return
  fi
  compact="$(sanitize_cluster_ids "${compact}")"
  printf 'cluster_id IN (%s)\n' "${compact}"
}

prepare_output_dir() {
  local base_dir="$1"
  local suffix="$2"
  local dir="${base_dir%/}/${suffix}"
  mkdir -p "${dir}"
  printf '%s\n' "${dir}"
}

render_sql_template() {
  local template_file="$1"
  local output_file="$2"
  local cluster_filter="$3"
  local probe_import_id="${4:-0}"

  if [[ ! -f "${template_file}" ]]; then
    die "template file not found: ${template_file}"
  fi

  sed \
    -e "s#__CLUSTER_FILTER__#${cluster_filter}#g" \
    -e "s#__PROBE_IMPORT_ID__#${probe_import_id}#g" \
    "${template_file}" > "${output_file}"
}

run_mysql_old() {
  MYSQL_PWD="${OLD_DB_PASSWORD}" mysql \
    --host="${OLD_DB_HOST}" \
    --port="${OLD_DB_PORT}" \
    --user="${OLD_DB_USER}" \
    --database="${OLD_DB_NAME}" \
    "$@"
}

run_mysql_new() {
  MYSQL_PWD="${NEW_DB_PASSWORD}" mysql \
    --host="${NEW_DB_HOST}" \
    --port="${NEW_DB_PORT}" \
    --user="${NEW_DB_USER}" \
    --database="${NEW_DB_NAME}" \
    "$@"
}

run_mysqldump_old() {
  MYSQL_PWD="${OLD_DB_PASSWORD}" mysqldump \
    --host="${OLD_DB_HOST}" \
    --port="${OLD_DB_PORT}" \
    --user="${OLD_DB_USER}" \
    "$@"
}
