/*
 * == This file has been MODIFIED by jhlowe@acm.org without the copyrighter's
 * == consent (2004-02-14).
 *
 * Copyright (c) 2001 Thorsten Kukuk.
 *
 * Copyright (c) 1992 Keith Muller.
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Keith Muller of the University of California, San Diego.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "swuser_config.h"
#include <sys/types.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <stdio.h>
#include <time.h>
#include <utmp.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <tar.h>
#ifdef HAVE_SYSMACROS_H
#include <sys/sysmacros.h>
#endif
#include "ls_list.h"
#include "vis.h"

/*
 * a collection of general purpose subroutines used by pax
 */

/*
 * constants used by ls_list() when printing out archive members
 */
#define MODELEN 20
#define DATELEN 64
#define DAYSPERNYEAR    365
#define SECSPERDAY      (60 * 60 * 24)
#define SIXMONTHS	((DAYSPERNYEAR / 2) * SECSPERDAY)
#define CURFRMT		"%b %e %H:%M"
#define OLDFRMT		"%b %e  %Y"
#define NAME_WIDTH	8

/*
#define PAX_DIR         1                * directory *
#define PAX_CHR         2                * character device *
#define PAX_BLK         3                * block device *
#define PAX_REG         4                * regular file *
#define PAX_SLK         5                * symbolic link *
#define PAX_SCK         6                * socket *
#define PAX_FIF         7                * fifo *
#define PAX_HLK         8                * hard link *
#define PAX_HRG         9                * hard link to a regular file *
#define PAX_CTG         10               * high performance file *
*/

#define PAX_DIR        DIRTYPE
#define PAX_CHR        CHRTYPE
#define PAX_BLK        BLKTYPE     
#define PAX_REG        REGTYPE    
#define PAX_SLK        SYMTYPE   
#define PAX_SCK        REGTYPE  /* Not used */
#define PAX_FIF        FIFOTYPE  
#define PAX_HLK        LNKTYPE 
#define PAX_HRG        LNKTYPE 
#define PAX_CTG        REGTYPE   /* Not used */

#define MAJOR(x)        major(x)
#define MINOR(x)        minor(x)
#define TODEV(x, y)     makedev((x), (y))

#define UGSWIDTH 18
static int ugswidth = UGSWIDTH;


static
char *
tartime(time_t t)
{
  static char buffer[100];
  char *p;

  /* Use ISO 8610 format.  See:
     http://www.cl.cam.ac.uk/~mgk25/iso-time.html  */
  struct tm *tm = localtime (&t);
  if (tm)
    {
      sprintf (buffer, "%04d-%02d-%02d %02d:%02d:%02d",
               tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
               tm->tm_hour, tm->tm_min, tm->tm_sec);
    }
  else
   {
      sprintf (buffer, "%lu", (unsigned long)t);
   }
  return buffer;
}

static
void
safe_print (char *str, FILE * fp)
{
  char visbuf[5];
  char *cp;

  /*
   * if printing to a tty, use vis(3) to print special characters.
   */
  if (isatty (fileno (fp)))
    {
      for (cp = str; *cp; cp++)
	{
	  (void) vis (visbuf, cp[0], VIS_CSTYLE, cp[1]);
	  (void) fputs (visbuf, fp);
	}
    }
  else
    {
      (void) fputs (str, fp);
    }
}

static
void
safe_print_to_strob(char *str, STROB * fp)
{
  char visbuf[5];
  char *cp;

  if (1 || /* isatty (fileno (fp))*/ 0 )
    {
      for (cp = str; *cp; cp++)
	{
	  (void) vis (visbuf, cp[0], VIS_CSTYLE, cp[1]);
	  strob_strcat(fp, visbuf);
	}
    }
  else
    {
      strob_strcat(fp, str);
    }
}

void
ls_list (char * name, char * ln_name, struct stat * sbp,
	time_t now, FILE * fp, char * uname, char * gname, int type, int vflag)
{
	STROB * buf = strob_open(160);
        ls_list_to_string(name, ln_name, sbp, now, buf, uname, gname, type, vflag);
	fprintf(fp, "%s", strob_str(buf));
        (void) fflush (fp);
	strob_close(buf);
}

void
ls_list_to_string(char * name, char * ln_name, struct stat * sbp,
	time_t now, STROB * fp, char * uname, char * gname, int type, int vflag)
{
  char f_mode[MODELEN];
  char f_date[DATELEN];
  char *timefrmt;
  char * ltmfrmt = NULL;
  char numid[64];
  int pad;
  unsigned long int sizeme;

  numid[sizeof(numid) - 1] = '\0';

  /*
   * if not verbose, just print the file name
   */
  if (!vflag)
    {
      strob_sprintf(fp, 0, "%s\n", name);
      return;
    }
    strob_strcpy(fp, "");

  /*
   * user wants long mode
   */
  swbis_strmode (sbp->st_mode, f_mode);

  if (ltmfrmt == NULL)
    {
      /*
       * no locale specified format. time format based on age
       * compared to the time pax was started.
       */
      if (((sbp->st_mtime + SIXMONTHS) <= now) && now != 0)
	timefrmt = OLDFRMT;
      else
	timefrmt = CURFRMT;
    }
  else
    timefrmt = ltmfrmt;

  /*
   * print file mode, link count, uid, gid and time
   */
  if (strftime (f_date, DATELEN, timefrmt, localtime (&(sbp->st_mtime))) == 0)
    f_date[0] = '\0';

  if (vflag > 1) {
          pad = strlen(uname) + 2  +  /* e.g  ``(root)'' */
		strlen(gname) + 2  +  /* e.g. ``(root)'' */
		9 /*strlen(size)*/ +
		1 +
		1 +
		11 + 11 +
		0;
          if (pad > ugswidth)
       		 ugswidth = pad;
	  strob_sprintf(fp, 1, "%s[%d](%s)/[%d](%s) %*s",
            f_mode,
		(int)(sbp->st_uid), uname,
		(int)(sbp->st_gid), gname,
		ugswidth - pad, "");
  } else {
     if (strlen(uname) && strlen(gname)) {
          pad = strlen(uname) + strlen(gname) + 9 /*strlen(size)*/ + 1;
          if (pad > ugswidth)
       		 ugswidth = pad;
	  strob_sprintf(fp, 1, "%s%s/%s %*s",
            f_mode, uname, gname, ugswidth - pad, "");
     } else {
	  snprintf(numid, sizeof(numid)-1, "%d/%d", (int)(sbp->st_uid), (int)(sbp->st_gid));
          pad = strlen(numid) + 8 /*strlen(size)*/ + 1;
          if (pad > ugswidth)
       		 ugswidth = pad;
	  strob_sprintf(fp, 1, "%s%s %*s",
            f_mode, numid, ugswidth - pad, "");
     }
  }
  
  /*
   * print device id's for devices, or sizes for other nodes
   */
  if ((type == PAX_CHR) || (type == PAX_BLK))
#		ifdef LONG_OFF_T
    strob_sprintf(fp, 1, "%4u,%4u ", MAJOR (sbp->st_rdev),
		    MINOR (sbp->st_rdev));
#		else
    strob_sprintf(fp, 1, "%4lu,%4lu ", (unsigned long) MAJOR (sbp->st_rdev),
		    (unsigned long) MINOR (sbp->st_rdev));
#endif
  else
    {
     if ((type == PAX_SLK) || (type == PAX_HLK)) {
	sizeme = 0;
     } else {
        sizeme = (unsigned long int)(sbp->st_size);
     }
#		ifdef LONG_OFF_T
     strob_sprintf(fp, 1, "%9lu ", (unsigned long int)(sizeme));
#		else
     strob_sprintf(fp, 1, "%9lu ", (unsigned long int)(sizeme));
#		endif
    }

  /*
   * print name and link info for hard and soft links
   */
  /* (void) fputs (f_date, fp); */
  strob_sprintf(fp, 1, "%s ", tartime(sbp->st_mtime));
  safe_print_to_strob(name, fp);
  if ((type == PAX_HLK) || (type == PAX_HRG))
    {
      /* strob_strcat(fp, " == "); */
      strob_strcat(fp, " link to ");
      safe_print_to_strob(ln_name, fp);
    }
  else if (type == PAX_SLK)
    {
      strob_strcat(fp, " -> ");
      safe_print_to_strob(ln_name, fp);
    }
  strob_strcat(fp, "\n");
  return;
}

/*
 * ls_list()
 *	list the members of an archive in ls format
 */
void
OLDls_list (char * name, char * ln_name, struct stat * sbp,
	time_t now, FILE *fp, char * uname, char * gname, int type, int vflag)
{
  char f_mode[MODELEN];
  char f_date[DATELEN];
  char *timefrmt;
  char * ltmfrmt = NULL;
  char numid[64];
  int pad;

  numid[sizeof(numid) - 1] = '\0';

  /*
   * if not verbose, just print the file name
   */
  if (!vflag)
    {
      safe_print (name, fp);
      (void) putc ('\n', fp);
      (void) fflush (fp);
      return;
    }

  /*
   * user wants long mode
   */
  swbis_strmode (sbp->st_mode, f_mode);

  if (ltmfrmt == NULL)
    {
      /*
       * no locale specified format. time format based on age
       * compared to the time pax was started.
       */
      if (((sbp->st_mtime + SIXMONTHS) <= now) && now != 0)
	timefrmt = OLDFRMT;
      else
	timefrmt = CURFRMT;
    }
  else
    timefrmt = ltmfrmt;

  /*
   * print file mode, link count, uid, gid and time
   */
  if (strftime (f_date, DATELEN, timefrmt, localtime (&(sbp->st_mtime))) == 0)
    f_date[0] = '\0';
/*
  (void) fprintf (fp, "%s%2u %-*.*s %-*.*s ", f_mode, sbp->st_nlink,
		  NAME_WIDTH, UT_NAMESIZE, uname,
		  NAME_WIDTH, UT_NAMESIZE, gname);
*/

  if (strlen(uname) && strlen(gname)) {
          pad = strlen(uname) + strlen(gname) + 9 /*strlen(size)*/ + 1;
          if (pad > ugswidth)
       		 ugswidth = pad;
	  fprintf (fp, "%s%s/%s %*s",
            f_mode, uname, gname, ugswidth - pad, "");
	  /*
	  (void) fprintf (fp, "%s%-*.*s/%-*.*s ", f_mode,
		  0/ *NAME_WIDTH* /, UT_NAMESIZE, uname,
		  NAME_WIDTH, UT_NAMESIZE, gname);
	  */
  } else {
          /*
	  (void) fprintf (fp, "%s %-*.*s ", f_mode, NAME_WIDTH+5, UT_NAMESIZE+5, numid);
	  */
	  snprintf(numid, sizeof(numid)-1, "%d/%d", (int)(sbp->st_uid), (int)(sbp->st_gid));
          pad = strlen(numid) + 8 /*strlen(size)*/ + 1;
          if (pad > ugswidth)
       		 ugswidth = pad;
	  fprintf (fp, "%s%s %*s",
            f_mode, numid, ugswidth - pad, "");
  }

  /*
   * print device id's for devices, or sizes for other nodes
   */
  if ((type == PAX_CHR) || (type == PAX_BLK))
#		ifdef LONG_OFF_T
    (void) fprintf (fp, "%4u,%4u ", MAJOR (sbp->st_rdev),
		    MINOR (sbp->st_rdev));
#		else
    (void) fprintf (fp, "%4lu,%4lu ", (unsigned long) MAJOR (sbp->st_rdev),
		    (unsigned long) MINOR (sbp->st_rdev));
#endif
  else
    {
#		ifdef LONG_OFF_T
      (void) fprintf (fp, "%9lu ", (unsigned long int)(sbp->st_size));
#		else
      (void) fprintf (fp, "%9lu ", (unsigned long int)(sbp->st_size));
#		endif
    }

  /*
   * print name and link info for hard and soft links
   */
  /* (void) fputs (f_date, fp); */
  fprintf(fp, "%s", tartime(sbp->st_mtime));
  (void) putc (' ', fp);
  safe_print (name, fp);
  if ((type == PAX_HLK) || (type == PAX_HRG))
    {
      fputs (" == ", fp);
      safe_print (ln_name, fp);
    }
  else if (type == PAX_SLK)
    {
      fputs (" => ", fp);
      safe_print (ln_name, fp);
    }
  (void) putc ('\n', fp);
  (void) fflush (fp);
  return;
}
