#! /usr/bin/env slsh
% Generate a listing of an RPM file

private define pgm_usage ()
{
   vmessage ("Usage: lsrpm FILENAME");
   exit (1);
}

private variable RPM_Command = "rpm -q -l --dump -p ";

private define exit_error (msg)
{
   () = fprintf (stderr, "%s\n", msg);
   exit (1);
}

private define run_rpm (file)
{
   variable fp;
   variable lines;
   variable months =
     ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
      "Oct", "Nov", "Dec"];
   variable s;

   fp = popen (RPM_Command + file, "r");
   if (fp == NULL)
     exit_error ("Failed to open RPM process");

   % each line contains:
   % path size mtime md5sum mode owner group isconfig isdoc rdev symlink

   variable six_months_ago = _time () - 3600*24*30*6;

   foreach (fp)
     {
	variable path, size, mode, owner, group, symlink, mtime;
	variable mstring;
	variable tm;

	s = ();
	s = strchop (strtrim_end (s, "\n"), ' ', 0);

	path = s[0];
	size = s[1];
	mtime = integer (s[2]);
	mode = integer (s[4]);
	owner = s[5];
	group = s[6];

	tm = localtime (mtime);
	if (mtime < six_months_ago)
	  mtime = sprintf ("%s %2d %4d",
			   months[tm.tm_mon],
			   tm.tm_mday,
			   1900 + tm.tm_year);
	else
	  mtime = sprintf ("%s %2d % 2d:%02d",
			   months[tm.tm_mon],
			   tm.tm_mday,
			   tm.tm_hour,
			   tm.tm_min);

	symlink = "";
	if (stat_is ("lnk", mode))
	  symlink = " -> " + s[10];

	mstring = stat_mode_to_string (mode);

	if (-1 == fprintf (stdout,
			   "%8s %8s %8s %10s %s %s%s\n",
			   mstring, owner, group, size, mtime, path, symlink))
	  exit_error (sprintf ("Write failed: %s", errno_string (errno)));
     }
   () = pclose (fp);
}

if (__argc != 2)
  pgm_usage ();

run_rpm (__argv[1]);
exit (0);
