#!/bin/bash
#SBATCH --ntasks=1
#SBATCH --time=96:00:00
#SBATCH --partition=queue_name
#SBATCH --job-name=assembly.juicer

raw=/path/to/raw/reads
hic=/path/to/hic/output/directory
ref=/path/to/reference/assembly
bwa_db=/path/to/bwa_db

juicer=/path/to/local/opt/juicer

module load java

cd $hic

#
# Index the reference genome.
#
bwa index -p $bwa_db/assembly.db $ref/assembly.fasta
samtools faidx -o $ref/assembly.fasta.fai $ref/assembly.fasta

#
# Generate a file with restriction site positions, libraries constructed with DpnII ('GATC')
#
python $juicer/misc/generate_site_positions.py DpnII assembly $ref/assembly.fasta
mv $hic/assembly_DpnII.txt $hic/juicer/restriction_sites/

#
# Generate a file containing the sizes of chromosomes in the assembly.
#
awk 'BEGIN{OFS="\t"}{print $1, $NF}' $hic/juicer/restriction_sites/assembly_DpnII.txt > $hic/juicer/restriction_sites/assembly.chrom.sizes

#
# Link the files, they must have "*R1.fastq.gz" suffix or alignment won't run properly
#
ln -s $raw/hic_reads_R1.fastq.gz  $hic/juicer/fastq/.
ln -s $raw/hic_reads_R2.fastq.gz  $hic/juicer/fastq/.

#
# Identify Hi-C junctions.
#
$juicer/SLURM/scripts/juicer.sh -t 24 -d $hic/juicer -D $juicer/SLURM -s DpnII -g assembly \
                                -q aces -Q 5760 -l aces -L 23040 \
                                -p $hic/juicer/restriction_sites/assembly.chrom.sizes \
                                -z $ref/bwa_db/assembly.db \
                                -y $hic/juicer/restriction_sites/assembly_DpnII.txt

#
# Prepare files from Juicer for use in 3d-dna.
#
ln -s $hic/juicer/aligned/merged_nodups.txt $hic/3d-dna/.
ln -s $ref/assembly.fasta $hic/3d-dna/.

cd $hic/3d-dna

bash /path/to/local/opt/3d-dna/run-asm-pipeline.sh -r 0 $hic/3d-dna/assembly.fasta $hic/3d-dna/merged_nodups.txt

#
# Cleanup juicer files (taken from $juicer/SLURM/scripts/cleanup.sh) 
#
rm $hic/juicer/aligned/merged_sort.txt 
rm -r $hic/juicer/splits 
gzip $hic/juicer/aligned/dups.txt
gzip $hic/juicer/aligned/opt_dups.txt
gzip $hic/juicer/aligned/abnormal.sam
gzip $hic/juicer/aligned/collisions.txt
gzip $hic/juicer/aligned/unmapped.sam
