#!/bin/bash
# EvoPPI - Database
#
# Copyright (C) 2017 - 2018 Jorge Vieira, Miguel Reboiro-Jato and Noé Vázquez González
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program.  If not, see
# <http://www.gnu.org/licenses/gpl-3.0.html>.

fileName="$(basename "$1")";
speciesName="${fileName/ [^ ]*/}";
speciesName="${speciesName/_/ }";
interactomeName="${fileName/[^ ]* /}";
interactomeName="${interactomeName/.tsv/}";
interactomeName="${interactomeName/_/ }";

echo "SELECT \`id\` FROM \`species\` WHERE \`name\` = '${speciesName}' INTO @speciesId;";
echo "INSERT INTO \`interactome\` (\`name\`, \`speciesId\`) VALUES ('${interactomeName}', @speciesId);";
echo "SET @interactomeId = LAST_INSERT_ID();";

awk -F'[ ,]' '
{
  if (int($0) < int($1)) {
    geneA = $0;
    geneB = $1;
  } else {
    geneA = $1;
    geneB = $0;
  }

  printf "INSERT IGNORE INTO `interaction` (`geneA`, `geneB`, `interactome`) VALUES (%d, %d, @interactomeId);\n", geneA, geneB;
}' "$1" | sort | uniq;
