#!/usr/bin/env bash
set -euo pipefail

REMOTE_DIR="/sf/storage/gmo/hic/out/_RawReads/2025-12-15_BGI/"
DEST_ROOT="/data/ddpanchenko/main_dom/ChiPseq_25122025/data"


# MAP=(CTCF1 CTCF2 H3K27Ac1 H3K27Ac2 CTCF1_input CTCF2_input H3K27Ac1_input H3K27Ac2_input)
MAP=(H3K27Ac2)

mkdir -p "$DEST_ROOT"

for src_prefix in "${MAP[@]}"; do

  dest_dir="${DEST_ROOT}/${src_prefix}_2BGI"
  mkdir -p "$dest_dir"


  patterns=(
      "${src_prefix}_*_1.fq.gz"
      "${src_prefix}_*_2.fq.gz"
      "${src_prefix}_*R1*.*q.gz"
      "${src_prefix}_*R2*.f*q.gz"
  )

  # Собираем паттерны в строку для find
  find_expr=$(printf -- '-name "%s" -o ' "${patterns[@]}" | sed 's/ -o $//')

  mapfile -d '' remote_files < <(
    ssh gdev bash -c "'
      shopt -s nullglob
      find \"${REMOTE_DIR}${src_prefix}\" -maxdepth 1 -type f \( ${find_expr} \) -print0
    '" || true
  )

  for remote_path in "${remote_files[@]}"; do
    remote_path="${remote_path//$'\r'/}"
    [[ -z "$remote_path" ]] && continue

    base="$(basename "$remote_path")"
    suffix="${base#${src_prefix}}"
    new_name="${src_prefix}_2BGI${suffix}"

    echo "Downloading ${src_prefix}"
    scp -T "gdev:'${remote_path}'" "${dest_dir}/${new_name}"
  done
done
