#!/bin/bash

[ $# -lt 1 ] && { >&2 echo "Please give DB to read from as argument"; exit 1; }

source qa-common.sh

MYSQL_USER="${MYSQL_USER:-fic}"
MYSQL_PASSWORD="${MYSQL_PASSWORD:-fic}"
MYSQL_DATABASE="$1"

EXERCICES=$(curl -s -H "X-FIC-Team: ${QA_ADMIN}" http://${HOST_FICQA}/api/exercices/)
TEAMS=$(curl -s http://${HOST_FICADMIN}/api/teams/ | jq -r '.[].id' | while read IDTEAM; do curl -s http://${HOST_FICADMIN}/api/teams/$IDTEAM/associations | jq -r ".[] | {login: ., id_team: \"$IDTEAM\"}"; done)

echo "select Q.*, T.name, E.title from exercices_qa Q INNER JOIN exercices E ON E.id_exercice = Q.id_exercice INNER JOIN themes T ON T.id_theme = E.id_theme;" | mysql --skip-column-names -u "${MYSQL_USER}" --password="${MYSQL_PASSWORD}" "${MYSQL_DATABASE}" | tr '\t' '|' | while IFS='|' read IDQ IDEXERCICE IDTEAM REMOTE_USER SUBJECT CREATION STATE SOLVED CLOSED THEME EXERCICE_TITLE
do
	# Search exercice by title
	IDEXERCICE=$(echo "${EXERCICES}" | jq -r ".[] | select(.title == \"${EXERCICE_TITLE}\") | .id")
	[ -z "$IDEXERCICE" ] && { >&2 echo "QA query $IDQ: no exercice match"; continue; }

	# Search user in teams (if not found, set to null, this is allowed)
	IDTEAM=$(echo "${TEAMS}" | jq -r "select(.login == \"${REMOTE_USER}\") | .id_team")
	[ -z "$IDTEAM" ] && IDTEAM=null

	CREATION=$(echo ${CREATION}Z | sed 's/ /T/')
	[ "$SOLVED" == "NULL" ] && SOLVED=null || SOLVED="\"$(echo ${SOLVED}Z | sed 's/ /T/')\""
	[ "$CLOSED" == "NULL" ] && CLOSED=null || CLOSED="\"$(echo ${CLOSED}Z | sed 's/ /T/')\""

	SUBJECT=$(cat <<EOF | jq -R .
$SUBJECT
EOF
)

	QA=$(curl -s -f -X POST -d @- "http://${HOST_FICADMIN}/api/qa/" <<EOF
{
  "id_exercice": $IDEXERCICE,
  "id_team": $IDTEAM,
  "user": "$REMOTE_USER",
  "creation": "$CREATION",
  "state": "$STATE",
  "subject": $SUBJECT,
  "solved": $SOLVED,
  "closed": $CLOSED
}
EOF
)

	QAID=$(echo $QA | jq -r .id)

	echo "SELECT * FROM qa_comments WHERE id_qa = $IDQ ORDER BY date ASC;" | mysql --skip-column-names -u "${MYSQL_USER}" --password="${MYSQL_PASSWORD}" "${MYSQL_DATABASE}" | tr '\t' '|' | while IFS='|' read IDC IDQ IDT REMOTE_USER DATEC COMMENT
	do

		IDTEAM=$(echo "${TEAMS}" | jq -r "select(.login == \"${REMOTE_USER}\") | .id_team")
		[ -z "$IDTEAM" ] && IDTEAM=null

		DATEC=$(echo ${DATEC}Z | sed 's/ /T/')
		COMMENT=$(cat <<EOF | jq -R .
$COMMENT
EOF
)

		curl -s -f -X POST -d @- "http://${HOST_FICADMIN}/api/qa/$QAID/comments" <<EOF > /dev/null
{
  "id_team": $IDTEAM,
  "user": "$REMOTE_USER",
  "date": "$DATEC",
  "content": $COMMENT
}
EOF
	done
done
