#!/bin/bash

set -euo pipefail

threads=32
ref=/home/Resource/Genome/hg38/hg38.25_chromsome.fa

outdir=/BLUES/eric/ONT/5hmc_DMR
mkdir -p "${outdir}"

declare -A BAMS

BAMS[Naive]="/BLUES/eric/ONT/Naive/091724_Naive_W3MECPC2_aln.sorted.bam"
BAMS[Primed]="/BLUES/eric/ONT/Primed/Primed_W3MECP2_aln.sorted.bam"
BAMS[TSC]="/BLUES/eric/ONT/TSC/TSC_GFP_W3MECP2_merged_aln.sorted.bam"

cd "${outdir}"

for sample in Naive Primed TSC; do

    bam="${BAMS[$sample]}"
    pileup="${outdir}/${sample}_5hmC_pileup.bed"

    echo "======================================="
    echo "Running raw 5hmC pileup for ${sample}"
    echo "Input BAM: ${bam}"
    echo "Output: ${pileup}"
    echo "======================================="

    modkit pileup \
        "${bam}" \
        "${pileup}" \
        --cpg \
        --modified-bases 5hmC \
        --ref "${ref}" \
        --threads "${threads}"

    echo "Filtering ${sample} to 30x"
    awk '$5 >= 30' "${pileup}" > "${outdir}/${sample}_5hmC_pileup_30x.bed"

    bgzip -@ "${threads}" "${outdir}/${sample}_5hmC_pileup_30x.bed"
    tabix -p bed "${outdir}/${sample}_5hmC_pileup_30x.bed.gz"

done

echo
echo "[DONE] Raw 5hmC pileups and 30x files generated"
echo