#!/bin/bash

thr=30
mem=240000

mkdir tmp && cd tmp

cp /mnt/project/tool/plink . && chmod 755 plink
cp /mnt/project/tool/plink2 . && chmod 755 plink2

cp /mnt/project/import/ukbb_qced.knn.txt.gz .

cp /mnt/project/Bulk/Genotype\ Results/Genotype\ calls/ukb22418_c{1..22}_b0_v2.{bed,bim,fam} .
cp /mnt/project/Bulk/Genotype\ Results/Genotype\ calls/ukb22418_cX_b0_v2.{bed,bim,fam} .
wget https://storage.googleapis.com/genomics-public-data/references/hs37d5/hs37d5.fa.gz &>/dev/null

ls *.bed | sed 's/.bed//g' > merge.list

plink \
  --merge-list merge.list \
  --autosome-xy \
  --threads $thr \
  --memory $mem \
  --out ukb22418

plink2 \
  --bfile ukb22418 \
  --ref-from-fa hs37d5.fa.gz \
  --keep ukbb_qced.knn.txt.gz \
  --snps-only \
  --make-pgen \
  --threads $thr \
  --memory $mem \
  --out ukb22418.tmp

./plink2 \
  --pfile ukb22418.tmp \
  --missing variant-only \
  --threads $thr \
  --memory $mem \
  --out ukb22418.tmp

for pop in {AFR,AMR,EAS,EUR,SAS}; do

  ./plink2 \
     --pfile ukb22418.tmp \
     --keep <(zcat ukbb_qced.knn.txt.gz | grep -w ${pop} | cut -f 1,2) \
     --hardy \
     --threads $thr \
     --memory $mem \
     --out ukb22418.tmp.${pop} > /dev/null

done

cat ukb22418.tmp.{AFR,AMR,EUR,EAS,SAS}.hardy \
  | sed '1d' \
  | awk '0+$10<1e-15' \
  | cut -f 2 \
  | sort \
  | uniq > ukb22418.hardy.qcout

cat ukb22418.tmp.{AFR,AMR,EUR,EAS,SAS}.hardy.x \
  | sed '1d' \
  | awk '0+$14<1e-15' \
  | cut -f 2 \
  | sort \
  | uniq > ukb22418.hardy_x.qcout

cat ukb22418.tmp.vmiss \
  | sed '1d' \
  | awk '$5>0.02' \
  | cut -f 2 > ukb22418.missing.qcout

cat ukb22418.hardy.qcout ukb22418.hardy_x.qcout ukb22418.missing.qcout \
  | sort \
  | uniq > ukb22418.qcout

wc -l *out > ../ukb22418.qc_summary.txt

./plink2 \
  --pfile ukb22418.tmp \
  --exclude ukb22418.qcout \
  --ref-from-fa hs37d5.fa.gz \
  --make-pgen \
  --threads $thr \
  --memory $mem \
  --out ukb22418.qced

./plink2 \
  --pfile ukb22418.qced \
  --make-pgen \
  --set-all-var-ids '@:#:$r:$a' \
  --threads $thr \
  --memory $mem \
  --out ../ukb22418

cd ../ && rm -r tmp/

