/* getdate - Get the date and time in a variable */
/* Author: Cyrille Pontvieux <jrd@enialis.net>
 * Licence: GPL v3+ */

#include <grub/dl.h>
#include <grub/misc.h>
#include <grub/datetime.h>
#include <grub/env.h>
#include <grub/command.h>

GRUB_MOD_LICENSE ("GPLv3+");

static grub_err_t
grub_cmd_getdate (grub_command_t cmd __attribute__ ((unused)), int argc, char **args)
{
  struct grub_datetime datetime;
  char* value;

  if (argc < 2)
  {
    return grub_error (GRUB_ERR_BAD_ARGUMENT, "missing arguments");
  }
  if (grub_get_datetime (&datetime))
  {
    return grub_errno;
  }
  if (grub_strcmp(args[0], "date") == 0)
  {
    value = grub_xasprintf ("%d-%02d-%02d", datetime.year, datetime.month, datetime.day);
  }
  else if (grub_strcmp(args[0], "time") == 0)
  {
    value = grub_xasprintf ("%02d:%02d:%02d", datetime.hour, datetime.minute, datetime.second);
  }
  else if (grub_strcmp(args[0], "datetime") == 0)
  {
    value = grub_xasprintf ("%d-%02d-%02d %02d:%02d:%02d %s\n",
                 datetime.year, datetime.month, datetime.day,
                 datetime.hour, datetime.minute, datetime.second,
                 grub_get_weekday_name (&datetime));
  }
  else
  {
    return grub_error (GRUB_ERR_BAD_ARGUMENT, "first argument should either be 'date', 'time' or 'datetime'.");
  }
  grub_env_set (args[1], value);
  return grub_errno;
}

static grub_command_t cmd;

GRUB_MOD_INIT (getdate)
{
  cmd = grub_register_command ("getdate", grub_cmd_getdate,
            N_("date|time|datetime VARIABLE"),
            N_("Get the date or time or both into a variable."));
}

GRUB_MOD_FINI (getdate)
{
  grub_unregister_command (cmd);
}
