#!/usr/bin/env bash
# A simple tool to subsample a big fasta file using mmseqs linclust.

calc(){ awk "BEGIN{ print $* }" ;}


NTHREADS=12
INPUTFASTA=""
TMPDIR=/data/nvme1/tegenfeldt/tmp/mmseqs_linclust/
OUTDIR=/data/nvme1/tegenfeldt/
MIN_SEQ_ID=0.8
MIN_COV=0.8
MAX_EVALUE=0.001

[[ $# -eq 1 ]] || { echo "usage: $0 <fasta file>"; exit 0; }
INPUTFASTA="$1"
[[ -f $INPUTFASTA ]] || { echo "error: missing input file $1"; exit 255; }
[[ -d $TMPDIR     ]] || { echo "error: missing tmp dir $TMPDIR"; exit 255; }
[[ -d $OUTDIR     ]] || { echo "error: missing output dir $OUTDIR"; exit 255; }


MSI_STR=$(calc "int(${MIN_SEQ_ID}*100)")
COV_STR=$(calc "int(${MIN_COV}*100)")

BNAME=$(basename $INPUTFASTA)
BNAME=${BNAME%%.*}
BFILE=${OUTDIR}/${BNAME}_S${MSI_STR}_C${COV_STR}
LOGFILE=${BFILE}.log
RESULT=${BFILE}_rep_seq.fasta
[[ -f $RESULT ]] && { echo "abort: output exists already at $RESULT"; exit 255; }

{
    echo "# workdir          $(pwd)"
    echo "# Input fasta      $INPUTFASTA"
    echo "# Tmp dir          $TMPDIR"
    echo "# Output dir       $OUTDIR"
    echo "# Command line     mmseqs easy-linclust --threads $NTHREADS $INPUTFASTA $BFILE $TMPDIR -e $MAX_EVALUE --min-seq-id $MIN_SEQ_ID -c $MIN_COV"
    mmseqs easy-linclust --threads $NTHREADS $INPUTFASTA $BFILE $TMPDIR -e $MAX_EVALUE --min-seq-id $MIN_SEQ_ID -c $MIN_COV
} >& $LOGFILE &
echo "started linclust on $INPUTFASTA"
echo "output: $BFILE"
