#!/bin/sh
# tmww plugin: versiontable
# whatis: try determine player's client version using online list and client versions summary table
# conflicts: log (versiontable logs also online/offline users)
# depends: -
# recommends: -

# this file is part of tmww - the mana world watcher
# willee, 2012-2014
# GPL v3

# check if not run as plugin
if [ "$TMWW_PLUGINS" != "yes" ] ; then
   echo >&2 "This script is tmww plugin and rely heavily on it's facilities."
   exit 1
fi

help_versiontable() {
   cat << EOF
versiontable -- try determine player's client version using online list and client
   versions summary table. versiontable generates extended version of "log" plugin
   so there's no reason to run both.

   IMPORTANT: run "versiontable" action only after you performed "fetch"

   Recommended execution interval equals to max between online list update time or
   versions summary table. Recommended way is something like:

   $ watch -pn 20 tmww versiontableconf

Command line options: -- (no commands)
EOF
}

[ "$TMWW_PLUGINHELP" = "yes" ] && help_versiontable && return 0
[ "$TMWW_PLUGINEXPORT" = "yes" ] && return 0

TMWW_LOGLOCK="${TMWW_LOCK}/tmww-log-${servername}"

set_log_lock() {
   check_lock "log" "${TMWW_LOGLOCK}" 35
}

unset_log_lock() {
   rmdir "${TMWW_LOGLOCK}" 2>/dev/null
}

parse_table () {
   awk -- '
   BEGIN { RS = "</tr>"; FS = "</td>"; OFS = "__" }
   /Total/ { exit }
   NR > 1 {
       for(i = 1; i <= NF; i++) {
           sub(/.*<td.*>/, "", $i)
           gsub(/\n/, "", $i)
       }
       print $1, $2
   } '
}

compare_lists () {
   awk -- '
   BEGIN { FS = "__"; s = 0 }
   NR == FNR { a[$1]=$2 ; next }
   { n = $2 - a[$1]; if (n > 0) { print n, $1 } ; }
   ' "${ver_old}" "${ver_work}"
}

# check if nothing to do
[ -s "${list_logon}" ] && processversions="yes"
[ "${processversions}" != "yes" ] && [ ! -s "${list_logoff}" ] && return 0

set_log_lock

# prepare report file
TMWW_VERSIONREPORT="${TMWW_VERSIONREPORT:-${HOME}/log/tmww}"
log_path="${TMWW_VERSIONREPORT}/${servername}/$(date -u +%Y-%m)"
check_dir "$log_path"
log_file="$log_path/$(date -u +%d).yml"

# prepare work files
TMWW_VERSIONCACHE="${TMWW_VERSIONCACHE:-${HOME}/log/versions}/${servername}"
check_dir "${TMWW_VERSIONCACHE}"
ver_raw="${TMWW_VERSIONCACHE}/active.html"
ver_work="${TMWW_VERSIONCACHE}/parsed.txt"
ver_old="${TMWW_VERSIONCACHE}/old.txt"
ver_summary="${TMWW_VERSIONCACHE}/$(date -u +%Y-%m-%d).summary.html"

# prepare versions url
LINK="${TMWW_VERSIONLINK:-http://updates.themanaworld.org/versions.php}"

# ----- this part will be skipped if noone to detect
if [ -s "$list_logon" ]; then

logon_clients=$( cat "$list_logon" )
logon_count=$( wc -l < "$list_logon" )

# versions

echo >&2 ${hlon}Fetching!${hloff}

$FETCH $LINK > "$ver_raw"
[ $? != 0 ] && { rm -f "$ver_raw" ;
   echo >&2 "Failed to retrieve versions file. Aborting." ; return 1 ; }

parse_table < "${ver_raw}" > "${ver_work}"

if [ ! -f "$ver_summary" ]; then
   mv "${ver_work}" "${ver_old}"
   echo >&2 "Aborting due to dry run."
   return 0
fi

new_clients=$( compare_lists | sed 's/\\/\\\\/g;s/"/\\"/g' )
new_count=$( printf "%s\n" "${new_clients}" | wc -l )

[ $logon_count -eq 1 ] && [ -n "$new_clients" ] && [ $new_count -eq 1 ] &&
   echo >&2 ${hlon}Player detected:${hloff} ${logon_clients}

fi
# ----- proceeding with log

exec 3>&1 1>>${log_file}

echo "- time: \"${servertime}\""
[ -s "$list_logon" ] && echo "  logon: [ $( make_qcsv < "$list_logon" ) ]"
[ -s "$list_logoff" ] && echo "  logoff: [ $( make_qcsv < "$list_logoff" ) ]"

if [ -n "$new_clients" ]; then
   if [ $logon_count -eq 1 ] && [ $new_count -eq 1 ]; then
       new_clients="${new_clients#* }"
       new_servertime=$( sed -n 's/.*Data\ retrieved:.*\(..:..\ .m\).*/\1/p' "${ver_raw}" )
       echo "  detected: [ \"$new_servertime\", \"${logon_clients}\", \"${new_clients}\" ]"
   else
       echo "  versions: "
       printf "%s" "$new_clients" | sort -rn | awk -- '
           { printf "      - [ \"%s\"",$1; sub(" *[^ ]* *",""); printf ", \"%s\" ]\n",$0 }'
   fi
fi

exec 1>&3 3>&-

# if we worked with versions file - move current to old
[ "$processversions" = "yes" ] && {
   cp "${ver_raw}" "${ver_summary}"
   mv -f "$ver_work" "$ver_old"
}

unset_log_lock

return 0