#!/usr/bin/env bash
# Copyright 2014, 2015 Vladimir Ivanov <ivvl82@gmail.com>
# Distributed under the terms of the GNU General Public License v2

REPO_DIR=

# Specify the tournament here
TOURNAMENT=

function parse_setup {
    : ${REPO_DIR:=`dirname "$0"`}

    # If no tournament given, set it to the last one
    if [[ -z $TOURNAMENT ]]; then
        local year_dir=$(ls -1 -d ${REPO_DIR}/[0-9][0-9][0-9][0-9]/ | tail -1)
        TOURNAMENT=$(ls -1 -d ${year_dir}[0-9]-*/ | tail -1 \
                            | sed -E "s|${REPO_DIR}/(.*)/|\1|")
    fi
}

function parse_tour_info {
    # Add a newline at the end of 'tour_info' to parse the last line
    local tour_info=$(cat "${REPO_DIR}/${TOURNAMENT}/tours/${tour}/tour_info"; echo)

    local date_re="[0-9?]{2}\.[0-9?]{2}\.[0-9?]{4}"
    local res_re="(1|½|0|\+|−)"
    while read line; do
        if [[ $line =~ ^($date_re)\ +([^\ ]+)\ +-\ +([^\ ]+)(\ +$res_re-$res_re)? ]]; then
            local date=${BASH_REMATCH[1]}
            local white=${BASH_REMATCH[2]}
            local black=${BASH_REMATCH[3]}
            local result=${BASH_REMATCH[5]}-${BASH_REMATCH[6]}
            local round=$(echo "($tour - 1)/($ply_count - 1) + 1" | bc)
            parse_to_ini
            (( game_counter++ ))
        fi
    done <<< "$tour_info"
}

function parse_to_ini {
    echo "[game${game_counter}]"
    echo "round  = $round"
    [[ ! $date =~ \? ]] && echo "date   = $date"
    echo "white  = $white"
    echo "black  = $black"
    [[ $result == "-" ]] || echo "result = \"$result\""
    echo
}

parse_setup
# Configuration file for players
ply_ini=${REPO_DIR}/${TOURNAMENT}/players.ini

ply_count=$(grep "^\[player" "$ply_ini" | wc -l)
tour_seq=$(ls -1 -d ${REPO_DIR}/${TOURNAMENT}/tours/[0-9][0-9]/ \
                  | sed -E "s|${REPO_DIR}/${TOURNAMENT}/tours/([0-9]{2})/|\1|")

game_counter=1
for tour in $tour_seq; do
    parse_tour_info
done

exit 0