#!/bin/sh

set -e

dir=$(dirname $0)

germline_id=$(cat $dir/germline_id)

cat <<EOF
By downloading the IMGT germline databases (IMGT/GENE-DB), you
accept the IMGT® license:  the IMGT® software and data are provided to the academic users and NPO's (Not for Profit Organization(s)) under the CC BY-NC-ND 4.0 license. Any other use of IMGT® material, from the private sector, needs a financial arrangement with CNRS. Citing IMGT-GENEDB: Giudicelli V., Chaume D. and Lefranc M.-P. IMGT/GENE-DB: a comprehensive database for human and mouse immunoglobulin and T cell receptor genes Nucl. Acids Res., 33(S1):D256-D261 (2005). PMID:15608191

Otherwise please remove the files from your system.
EOF

wget --no-check-certificate -N https://www.vidjil.org/germlines/germline-${germline_id}.tar.gz
tar xzmfv germline-${germline_id}.tar.gz --strip-components=1 germline/
if [ -d "$dir/../browser" ]; then
    tar xzmfv germline-${germline_id}.tar.gz --strip-components=1 -C $dir/../browser/ browser/
fi

tmpfile=$(mktemp)
awk '$0 ~ /^>/ { if ($0 ~ /\/DV/) {dv=1} else {dv=0}}  dv==1{print > "homo-sapiens/TRADV.fa"; next} {print}' homo-sapiens/TRAV.fa  > $tmpfile
mv $tmpfile homo-sapiens/TRAV.fa
awk '$0 ~ /^>/ { if ($0 ~ /\/DV/) {dv=1} else {dv=0}}  dv==1{print > "homo-sapiens/TRADV.fa"; next} {print}' homo-sapiens/TRDV.fa  > $tmpfile
mv $tmpfile homo-sapiens/TRDV.fa

for file in CD-sorting.fa CD.fa IGK-INTRON.fa IGK-KDE.fa; do
    sed -ri '/^[^>#]/ s/^(.*)$/\L\1/' homo-sapiens/$file
done
