/*
Description

Adds the time left to the host name in h:m:s format.

CVAR

amx_hostname_update
  How often the hostname is updated, in seconds. (0 = disabled)

Credit

Original plugin by Cheap_Suit, see v1.3.4 in the history below.

History

1.0 First version by Deviance/Doombringer
1.1 Bug fix and h:m:s format
1.2 Hostname is restored at map end. Added CVAR amx_hostname_update.
1.2.1 Added delay before amx_hostname_update is read, so amxx.cfg is executed
      first.
1.2.3 Hostname cvar is read with delay now, too.
      Bug fix: Timer is halted before restoring the hostname.
1.3.1 Using m:s format if timeleft is less than one hour.
      Added leading zeros.
1.3.2 Bug fix: Hostname is only restored if a timer is running.
      Added several checks if hostname is empty.
      Made variables used in update_time global for performance.
1.3.4 From Cheap_Suit's original plugin:
      * "format" syntax for leading zeros, saving a few lines of code.
      * Added check if there is a time limit.
1.3.5 Bug fix: "no time limit" was shown during chat time.
1.3.6 Static variables for update_time()
*/

#include <amxmodx>
#include <amxmisc>

#define Plugin "Time left in hostname"
#define Version "1.3.6"
#define Author "Doombringer,pizzahut"
#define CVARNAME "amx_hostname_update"

new g_old_hostname[64]
new g_mp_timelimit

public plugin_init()
{
  register_plugin(Plugin,Version,Author)
  register_cvar(CVARNAME,"1.0")
  g_mp_timelimit = get_cvar_pointer("mp_timelimit")
  set_task(2.0,"check_time")
}

// Check cvar for valid values, correct if needed, update hostname now and set
// up a task.

public check_time()
{
  new Float:time = get_cvar_float(CVARNAME)
  if(time != 0.0)
  {
    time = floatabs(time)
    if(time < 1.0)
      time = 1.0
    get_cvar_string("hostname",g_old_hostname,63)
    if(strlen(g_old_hostname))
    {
      update_time()
      set_task(time,"update_time",1,"",0,"b")
    }
  }
}

// Update hostname.

public update_time()
{
  static new_hostname[64]
  static h,m,s

  if(strlen(g_old_hostname))
  {
    if(get_pcvar_float(g_mp_timelimit))
    {
      s = get_timeleft()
      m = s/60
      h = m/60
      s = s-m*60
      m = m-h*60
      if(h)
        format(new_hostname,63,"%s (Time left %d:%02d:%02d)",g_old_hostname,h,m,s)
      else
        format(new_hostname,63,"%s (Time left %d:%02d)", g_old_hostname,m,s)
    }
    else
      format(new_hostname,63,"%s (No time limit)",g_old_hostname)
    set_cvar_string("hostname",new_hostname)
  }
}

// Restoring hostname in case it's not reset in server.cfg.

public plugin_end()
{
  if(task_exists(1))
  {
    remove_task(1)
    if(strlen(g_old_hostname))
      set_cvar_string("hostname", g_old_hostname)
  }
}
