#!/usr/bin/env bash

[[ $# -ge 4 ]] || { echo "usage $0 <cluster file> <pipeline root> <trgfile> <clid1> [<clid2> ...]"; exit 0; }

FCLUSTER="$1"
SRCDIR="$2"
TRGFILE="$3"
shift
shift
shift
CLIDS=()
for clid in $@; do
    CLIDS+=($clid)
done

EXTENSION="fs"

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

GENES=()
extract_genes() {
    local c=
    local copts=
    [[ ${#CLIDS[@]} -gt 0 ]] || return 1
    for c in ${CLIDS[@]}; do
        copts="$copts -e '^$c '"
    done
    readarray GENES < <(eval "grep $copts $FCLUSTER" | cut -f 2 -d ' ' | sort)
    [[ ${#GENES[@]} -eq 0 ]] || {
        echo "found ${#GENES[@]} genes"
        return 0
    }
    echo "error: no genes found"
    return 2
}

TAXIDS=()
extract_taxids() {
    readarray TAXIDS < <(
        for g in ${GENES[@]}; do
            echo ${g%%:*}
        done | sort -u
    )
    [[ ${#TAXIDS[@]} -eq 0 ]] || {
        echo "found ${#TAXIDS[@]} taxids"
        return 0
    }
    echo "error: no taxids found"
    return 2
}

FGENES=""
extract_fasta() {
    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
}


echo "cluster       : $FCLUSTER"
echo "clid(s)       : ${CLIDS[@]}"
echo "source        : $SRCDIR"
echo "src extension : $EXTENSION"
echo "output        : $TRGFILE"

extract_genes  || exit 255
extract_taxids || exit 255
echo "N(genes)      : ${#FGENES[@]}"
echo "N(taxids)     : ${#TAXIDS[@]}"

FGENES=$(mktemp /tmp/fgenes_XXXX)
for x in ${GENES[@]}; do
    echo $x
done > $FGENES

for t in ${TAXIDS[@]}; do
    echo "taxid $t" 1>&2
    extract_fasta $t
done > $TRGFILE

rm -f $FGENES

