#!/usr/bin/make -Rrf
ifdef profile
SHELL=/usr/bin/time -f '=> jupiter: %e %C' /bin/bash -o pipefail
else
SHELL=/bin/bash -o pipefail
endif

ROOT_DIR:=$(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))

#------------------------------------------------------------
# params
#------------------------------------------------------------

ng=75
maxGap=100000
minBundleSize=10000
m=100000
i=0
t=8

#------------------------------------------------------------
# meta rules
#------------------------------------------------------------

.PRECIOUS: %-agp.sam %.agp
.DELETE_ON_ERROR:
.PHONY: check-params generateplot

default: generateplot

generateplot: check-params $(name).svg

check-name-param:
ifndef name
	$(error missing required param 'name' (output file prefix))
endif

check-params: check-name-param
ifndef ref
	$(error missing required param 'ref' (FASTA reference file))
endif
ifndef fa
	$(error missing required param 'fa' (FASTA contigs file))
endif

#optional command for sam files
ifdef sam
	$(attempting to skip alignments given $(sam))
endif

#------------------------------------------------------------
# pipeline rules
#------------------------------------------------------------

$(name)_reference.fa: $(ref)
	ln -s $< $@
	
$(name)_scaffolds.fa: $(fa)
	ln -s $< $@

# index FASTA file
%.fa.fai: %.fa
	samtools faidx $<
	
%.bwt: %.fa
	bwa index $*

%.agp %-agp.fa : %_scaffolds.fa
	perl $(ROOT_DIR)/bin/fatoagp.pl -f $*-agp.fa $< > $*.agp

ifdef sam
$(name)-agp.sam: $(sam)
	ln -s $< $@
else
%.fa.bwt %.fa.ann %.fa.pac %.fa.sa: %.fa
	bwa index $<
%-agp.sam: %_reference.fa %-agp.fa %_reference.fa.bwt %_reference.fa.pac %_reference.fa.sa %_reference.fa.ann
	bwa mem -t $(t) -x intractg $*_reference.fa $*-agp.fa > $@
endif

%.bed: %.sam
	grep -v XA $< | grep -v '^@' | awk '{if($$5 > 50 || $$5 == "" ) print}' | perl $(ROOT_DIR)/bin/samToBed.pl > $@

%.conf %.karyotype %.rv.links %.fw.links %.seqOrder.txt: %.agp %-agp.bed %_reference.karyotype %_scaffolds.fa.fai
	perl $(ROOT_DIR)/bin/generateConf.pl -n $(ng) -r $(ROOT_DIR)/config/rawConf.conf -p $* -s $*_scaffolds.fa.fai -b $*-agp.bed -a $*.agp -k $*_reference.karyotype

$(name)_reference.karyotype: $(name)_reference.fa
	perl $(ROOT_DIR)/bin/generateKaryotype.pl -i $(i) -m $(m) $(name)_reference.fa > $@

%.links.bundled: %.links
	cat $< | $(ROOT_DIR)/circos-tools-0.22/tools/bundlelinks/bin/bundlelinks -max_gap $(maxGap) -min_bundle_size $(minBundleSize) > $@

%.fw.links.bundled.flipped : %.fw.links.bundled
	awk ' { t = $$5; $$5 = $$6; $$6 = t; print; } ' $< > $@

%.links.final : %.rv.links.bundled %.fw.links.bundled.flipped
	cat $^ > $@

%.svg: %.conf %.karyotype %.links.final
	perl $(ROOT_DIR)/circos-0.69-3/bin/circos -noparanoid -conf $<
 
