#!/bin/bash

pheno=$1
pop=$2
chr=$3

thr=8
mem=12000

covarFile=/mnt/project/import/ukbb_qced.covar.txt.gz
phenoFile=/mnt/project/import/ukbb_qced.${pheno}.txt.gz
popFile=/mnt/project/import/population/ukbb_qced.${pop}.txt.gz
locoFile=/mnt/project/association/step1/${pheno}.${pop}/ukb22418.${pheno}.${pop}_*.loco
listFile=/mnt/project/association/step1/${pheno}.${pop}/ukb22418.${pheno}.${pop}_pred.list
pfile=/mnt/project/sample_QCed/ukb23148.QCed.chr${chr}

mkdir -p /home/dnanexus/out/out/tmp && cd /home/dnanexus/out/out/

cp /mnt/project/tool/plink2 . && chmod 755 plink2
docker pull skoyamamd/regenie:v3.1.3.gz

cp ${covarFile} .
cp ${phenoFile} .
cp ${popFile} .
cp ${locoFile} .
cp ${listFile} .
cp ${pfile}.{pvar,pgen,psam} .

./plink2 \
  --pfile $(basename $pfile) \
  --keep $popFile \
  --make-pgen \
  --out $(basename $pfile).${pop}

docker run -v /home/dnanexus/:/home/dnanexus skoyamamd/regenie:v3.1.3.gz regenie \
   --step 2 \
   --pgen /home/dnanexus/out/out/$(basename $pfile).${pop} \
   --phenoFile /home/dnanexus/out/out/$(basename $phenoFile) \
   --covarFile /home/dnanexus/out/out/$(basename $covarFile) \
   --catCovarList SEX,ARRAY \
   --bsize 1000 \
   --qt \
   --apply-rint \
   --threads ${thr} \
   --pred /home/dnanexus/out/out/$(basename $listFile) \
   --out /home/dnanexus/out/out/tmp/ukb22418.${pheno}.${pop}.${chr}

rm *

ls tmp/*regenie | while read line; do
  cat $line | gzip -c > $(basename $line).gz
done

rm -r tmp

