#!/usr/bin/env bash

[[ $# -eq 4 ]] || { echo "usage $0 <srcdir> <trgfile> <genes file> <taxid>"; exit 0; }

SRCDIR="$1"
TRGFILE="$2"
FGENES="$3"
TAXID="$4"
EXTENSION="fs"

[[ -d $SRCDIR  ]] || { echo "error: missing source dir at $SRCDIR"; exit 255; }
[[ -f $FGENES  ]] || { echo "error: missing genes file $FGENES";    exit 255; }
[[ -f $TRGFILE ]] && { echo "skip: target already exists $TRGFILE"; exit 255; }

create_from_taxid() {
    local taxid="$1"
    local fsrc=$SRCDIR/${taxid}.${EXTENSION}
    [[ -f $fsrc   ]] || { echo "error: missing source fasta file at $fsrc"; exit 255; }
    grep -f $FGENES --no-group-separator -A 1 $fsrc
}

create_from_file() {
    local txfile="$1"
    local t=""    
    for t in $(cat $txfile); do
        echo "searching taxid $t" 1>&2
        create_from_taxid $t
    done > $TRGFILE
}

echo "source        : $SRCDIR"
echo "genes         : $FGENES"
echo "taxid(s)      : $TAXID"
echo "src extension : $EXTENSION"
echo "output        : $TRGFILE"

if [[ -f $TAXID ]]; then
    echo "create using taxids from file $TAXID"
    create_from_file $TAXID
else
    echo "create using taxid $TAXID"
    create_from_taxid $TAXID > $TRGFILE
fi

