#!/bin/bash

readonly progname="${0##*/}"

usage() {
    echo -e "\e[1;33m${progname} [-h] ['date'] \e[0m"
    echo -e "  -h : optional, displays this help"
    echo -e "  date : optional, lowest date we start recompiling the data from, format YYYY-MM-DD, default is '2018-01-01 00:00:00.000'"
    echo -e ""
    echo -e "\e[1;33mIt inserts missing un-offered data in xc_queue_call table from xivo_full_stats\e[0m"
    echo -e "\e[1;33mIt needs a valid .pgpass file to access db xivo_stats as asterisk user on port 5443\e[0m"
    echo -e "\e[1;33mIt also needs psql\e[0m"
    echo -e ""
}

exit_abnormally() {
    usage
    exit 1
}

cmn_assert_command_is_available() {
    local cmd=${1}
    # shellcheck disable=SC2086
    if ! type ${cmd} >/dev/null 2>&1; then
        echo ""
        echo "Cancelling because required command '${cmd}' is not available."
        exit_abnormally
    fi
}

psql_cmd() {
    local req="${1}"
    shift

    local psql_res=""

    if psql_res=$(psql -h localhost -p 5443 -U asterisk -w xivo_stats -qtc "${req}"); then
        echo "${psql_res}"
    fi
}

insert_missing_preoffered_events_to_xc_queue_call() {
    sql_query="insert into xc_queue_call (queue_ref, start_time, end_time, answer_time, ring_duration, termination, unique_id)
select cq.queue_ref, cq.queue_time , cq.hangup_time, cq.answer_time, cq.total_ring_seconds, CAST(CAST(cq.status AS varchar) AS queue_termination_type), cq.callid
from call_on_queue cq
where cq.callid not in (select unique_id from xc_queue_call where start_time >= '$date')
and cq.status in ('closed','divert_ca_ratio','divert_waittime','full','joinempty') and cq.queue_time >= '$date';"
    psql_cmd "${sql_query}"
}

count_xc_queue_call_rows() {
    sql_query="select count(*) from xc_queue_call where start_time >= '$date';"
    psql_cmd "${sql_query}"
}

main() {
    if [ "$1" = "-h" ]; then
        usage
        exit 0
    fi

    if [ ! -f "${HOME}/.pgpass" ]; then
        echo "ERROR: ${progname} needs a valid .pgpass file to access db xivo_stats as asterisk user on port 5443"
        exit_abnormally
    fi

    cmn_assert_command_is_available "psql"

    date="${1:-2018-01-01 00:00:00.000}"

    pre_xc_queue_call_rows=$(count_xc_queue_call_rows)
    insert_missing_preoffered_events_to_xc_queue_call
    insertion_result=$?
    if [[ insertion_result -ne 0 ]]; then
        echo "something went wrong during the insertion"
        exit_abnormally
    fi
    post_xc_queue_call_rows=$(count_xc_queue_call_rows)
    inserted_rows=$((post_xc_queue_call_rows - pre_xc_queue_call_rows))
    echo "Operation successful, ${inserted_rows} rows were inserted to xc_queue_call"

}

main "${@}"
