#!/bin/bash

cd /home/dnanexus

cp /mnt/project/genotypes/ukb22418.pvar .
cp /mnt/project/genotypes/ukb22418.psam .
cp /mnt/project/genotypes/ukb22418.pgen .

cat ukb22418.pvar | grep "##" | sed '1s/^/##fileformat=VCFv4.2\n/' > ukb22418.vcf
cat ukb22418.pvar | grep "#" | grep -v "##" | awk '{print $0"\tQUAL\tFILTER\tINFO"}' >> ukb22418.vcf
cat ukb22418.pvar | grep -v "#" | awk '{print "chr"$0"\t.\t.\t."}' >> ukb22418.vcf
gzip -f ukb22418.vcf

wget http://hgdownload.cse.ucsc.edu/goldenPath/hg19/liftOver/hg19ToHg38.over.chain.gz &>/dev/null
wget https://storage.googleapis.com/genomics-public-data/resources/broad/hg38/v0/Homo_sapiens_assembly38.fasta &>/dev/null
wget https://storage.googleapis.com/genomics-public-data/resources/broad/hg38/v0/Homo_sapiens_assembly38.dict &>/dev/null

docker pull broadinstitute/gatk:4.2.6.0

docker run -v /home/dnanexus/:/home/dnanexus/ broadinstitute/gatk:4.2.6.0 \
  gatk LiftoverVcf \
  -I /home/dnanexus/ukb22418.vcf.gz \
  -O /home/dnanexus/ukb22418.hg38.vcf.gz \
  -C /home/dnanexus/hg19ToHg38.over.chain.gz \
  -R /home/dnanexus/Homo_sapiens_assembly38.fasta \
  --REJECT /home/dnanexus/ukb22418.hg38.rejected.vcf.gz

zcat ukb22418.hg38.vcf.gz \
  | grep -v "#" \
  | awk '{split($3,arr,":"); if($1=="chr"arr[1] && arr[3]==$4 && arr[4]==$5){print $0}}' \
  | awk '$7=="PASS" && $8=="."' \
  | awk '{print $3"\t"$2}' > ukb22418.hg38.linker

wget https://s3.amazonaws.com/plink2-assets/alpha3/plink2_linux_avx2_20220801.zip
unzip plink2_linux_avx2_20220801.zip
chmod 755 plink2

./plink2 \
  --pfile ukb22418 \
  --update-map ukb22418.hg38.linker \
  --extract ukb22418.hg38.linker \
  --make-pgen \
  --sort-vars \
  --out ukb22418.hg38.tmp

./plink2 \
  --pfile ukb22418.hg38.tmp \
  --ref-from-fa Homo_sapiens_assembly38.fasta \
  --set-all-var-ids 'chr@:#:$r:$a' \
  --make-pgen \
  --out /home/dnanexus/out/out/ukb22418.hg38

cp ukb22418.hg38.vcf.gz /home/dnanexus/out/out/

