#!/bin/csh -f
#
#                   ************************************************************
#                   ****                                                    ****
#                   ****  Originally designed for the USACOM GCCS Network.  ****
#                   ****                                                    ****
#                   ************************************************************
#
# zlister           Author:   Joe Wulf - 960708@19:10 EDT.
#
#
# FUNCTION: Automates the generation of complete file system listings for
# --------  reference.  Should be run on production machines and monitored for
#           changes made on a daily basis (or more frequently, as needed).
#           'zlister' is supported by 'sagrep' (included) which provides for
#           easy searches (of the aquired data) for files.  This can save
#           significant time for user(s) instead of having to search the
#           actual, physical filesystem manually (a la: UNIX 'find' command).
#
#           Briefly, zlister will generate a filesystem listing of the desired
#           server.  This listing will be parsed such that the directory path
#           is prepended to the filename/directory lines generated.  This file
#           is then stripped of any records that identify records from a file-
#           system remotely mounted (even via automount).  The result is
#           logically diff'ed aginst the previously generated file for the
#           same server.  These two final output files are then compressed and
#           put away for later retrieval (by sagrep).
#
#           Generally, this process was written on/for a Solaris 2.3 plaform.
#           It has been tested/tweaked under Solaris 2.5 as well.  Some
#           improvements have also been incorporated to support execution on
#           HP-UX and Linux (1.1.59+) platforms.  Minor modifications are
#           required to support any other platform.  This is the master script
#           and will contain the greatest volume of documentation/explaination.
#           Design intent was to be straight forward and simple to execute on a
#           wide/diverse group of platforms via standard csh and awk processes.
#
#           When executed on a frequent basis (i.e. daily), the resulting .diff
#           output can provide invaluable clues to system/security administrative
#           personnel as to EVERY file which changes on the system listed.  In
#           conjunction with frequent (daily) system backups, the potential for
#           any form of data loss can be significantly reduced.  Please review
#           all the data produced by these scripts for accuracy within your
#           environment.  It may not produce the results you think it would;
#           though I have tried to produce the best possible product I can.  :)
#
#           This is an ideal product to execute on newly built/rebuilt
#           production servers to get/establish/document the baseline of the
#           complete filesystem.  Subsequent runs will highlight differences.
#           Especially benificial to be ran after a filesystem check has been
#           run and significant errors were reported/corrected.
#
#           Originally designed to support the U.S. Atlantic Command Global
#           Command and Control System (USACOM GCCS).  zlister is now freely
#           available, via general distribution, to all.  Your comments and
#           suggestions are very welcome, as this project is still subject to
#           many improvement(s).  Please write me with your suggestions, at my
#           shipboard address (good until Aug '98).  I will gladly credit
#           those who contribute suggestions.  When writing via snailmail,
#           please send your snailmail address, as I WILL return to you an
#           updated version on floppy.  If you send your update(s) via floppy
#           please indicate what format it is in (tar, dos, etc...).  I'm
#           stationed onboard ship, and do not have internet access between
#           July 1996 and August 1998.  (After that it is ISDN for me)
#                       DP1 Joe Wulf
#                       USNS Spica, (T-AFS 9)
#                       FPO AP 96678-4066
#                       United States of America
#
#            -or at:    Commander in Chief                 (My previous Command
#                       U.S. Atlantic Command (USACOM)      if you want to help
#                       ATTN: J632B                         them out too :)    )
#                       1562 Mitscher Ave, STE 200
#                       Norfolk, Va. 23551-2551
#
#           At USACOM I worked with Jim Hunt (among many others).  He has
#           graciously volunteered to serve as an alternate point of contact
#           for zlister, while I am serving two years of sea duty.  He has
#           agreed to forward your suggestions and comments to me.  Please
#           don't pester him too much... he has not worked with me while I've
#           developed zlister - he has simply agreed to be an alternate POC.
#           You comments will reach Jim at "huntj@wangfed.com".  Please use
#           "zlister" in your subject line to help him out.  Thanks.  :)
#
#           sunsite.unc.edu has graciously allowed this product to be made
#           available on their host.  You should be able to find it on their
#           filesystem at: "/pub/Linux/system/Admin/zlister.taz".
#
#           I have liberally placed comments throughout these scripts 1) in
#           an attempt to "document" what is being done and why.  2) to help
#           me remember what I was doing.  Questions asked in here are to me,
#           not you (a reminder of just one more thing I intend to investigate).
#
#           To send me a report on an execution problem, please include a
#           complete copy of the current version of the scripts you are using
#           in compressed tar format, a complete copy of the window performing
#           the execution (or you can do zlister > zl.out and send me zl.out).
#           If possible include what ever output that has already accumulated
#           in the /tmp/zlister... dir; again in compressed tar format.
#           These are the reference(s) that I will need to help debug your
#           problem.  Independent of the problem report, please execute
#           zlister.stats and send me the output from that process as well.
#           Usually, all this output will fit on one, sometimes two, standard
#           1.44 foppies in compressed tar format.  Thanks.
#
#
# STANDARD SCRIPT LOCATION(S) (and purpose):
# -----------------------------------------
# /sysadmin/zlister.bin/zlister:
#           Production executible csh script.  It collects the file system
#           listing, processes it for data storage and retrieval.  By default it
#           will produce a report of changes to the filesystem since the last
#           time zlister was run.  Will duplicate itself to 'zlister.orig', for
#           protection, if it doesn't already exist.
#           This script is divided into sections, which are:
#           1.0)  Establishment of the standard production environment.
#           1.9)  Settings used to assist in testing and during development.
#           2.0)  Gathering of data.
#           3.0)  Format the output into desireable form.
#           4.0)  Elimination of records subordinate to NFS mount points.
#           5.0)  Highlight differences between this listing and the one before it.
#           6.0)  Perform data compression and move final files into production.
#           7.0)  Ensure file/directory permissions are correct.
#           Normal permissions are 755 root {default_group_for_root}
# /sysadmin/zlister.bin/zlister.Version-1.4b
#           Empty file describing the current version number of this release;
#           usually the same version number of the zlister script itself.
# /sysadmin/zlister.bin/zlister.preproc:
#           PreProcessor for zlister when Automountd is unavailable and/or
#           not being used and there is a desire to keep active NFS mounts
#           to a minimum.  Will 'auto-mount/unmount' the /sysadmin partition
#           in conjunction with the execution of zlister (as long as it has
#           been shared from the parent server).
#           Normal permissions are 755 root {default_group_for_root}
# /sysadmin/zlister.bin/zlister.awk.diff.PostProc:
#           awk script that arranges the parsed output, placing the
#           path of each entity at the beginning of each line.  This makes
#           it easier to sort the file of yesterdays versus today's
#           changes.
#           Normal permissions are 644 root {default_group_for_root}
# /sysadmin/zlister.bin/zlister.awk.ls-laR:
#           awk script that parses the path of each directory and places it
#           before the filename/sub-directory entries.  Does additional spiffy
#           formatting to cleanly align all fields, including the comma'tization
#           of the filesize field.
#           Normal permissions are 644 root {default_group_for_root}
# /sysadmin/zlister.bin/zlister.awk.noNFS:
#           awk script which reads the initial filesystem listing created
#           by zlister and parsed by zlister.awk.ls-laR; identifies
#           filesystems mounted from remote systems and systematically
#           removes those references.  The resulting production output only
#           contains references to directories and files on the local server
#           or workstation.
#           Haven't tried pushing the limits of awk on the various platforms
#           that I've been able to execute this on.  One of the many things
#           to do when time permits.  Desire to test various lengths for the
#           field which will be passing the mount points to remove.  Would like
#           feedback (with copious details) on its success in your environment.
#           Normal permissions are 644 root {default_group_for_root}
# /sysadmin/zlister.bin/zlister.awk.sort.PostProc:
#           awk script serving as a post processor of the sorted output as part
#           of diffing.  Checks ajacent records for differences and properly
#           reformats the output into the standard format.
#           Normal permissions are 644 root {default_group_for_root}
# /sysadmin/zlister.bin/zlister.lsm:
#           Simple document with brief description and scope of applicability.
#           Built per sunsite.unc.edu's .lsm version 3 format.
# /sysadmin/zlister.bin/zlister.stats:
#           This process is not required, at all, for zlister to properly
#           function.  It is an additional product that was convient for me.
#           Support csh script to collect network, system, user home and file
#           system status.  Takes a "picture" of the current system state.
#           Will later be divided into two pieces:
#           zlister.stats.daily:  Generally to be ran once a day.
#           zlister.stats.hourly: Generally to be run hourly.  It will have
#                                 the intelligence to perpetuate itself, via
#                                 'at' along with doc's on how to kill it off.
#           General execution of zlister will execute both, when complete.
#           Will duplicate itself, to zlister.stats.orig, for protection, if
#           it doesn't already exist.
#           Normal permissions are 755 root {default_group_for_root}
# /sysadmin/zlister.bin/zlister.stats.preproc:
#           Preprocessing scheduler (but it isn't written yet).  Requires
#           two arguments: 1) Numerical
#           range of hours to process for (Zulu time);  2) How many minutes
#           after the start of the hour to execute (allows for balancing).
#           Supplants crontab scheduling of independent frequency execution
#           of the data collection.
#           Normal permissions are 755 root {default_group_for_root}
# /sysadmin/zlister.bin/sagrep:
#           Post-zlister-execution script to support retrieval of data.
#           Name means Super-ACOM-grep or System-Administrator grep.
#           Tool used to query compressed output of zlister for desired
#           pattern.  Will make a sagrep.orig, for protection, if it
#           doesn't already exist.
#           Need standalone code to diff desired dates, same code that
#           zlister has; but will have to be either run as root or stored
#           in /tmp for general user access.
#           Normally a link is established from /usr/local/bin to sagrep, but
#           that must be manually done by root.
#           Normal permissions are 755 root {default_group_for_root}
# /sysadmin/zlister.bin/zl:
#           Development/test copy of zlister script.  Not normally
#           included in the production zlister distribution.
#           Normal permissions are 755 root {default_group_for_root}
#
#
#    Yes.   Much of this might be improved by using perl 5.001+, However,
#           1) I don't know perl (haven't had the time free to learn it).
#           2) Perl might not be available, much less already available on,
#              any particular platform that zlister might be installed upon.
#              I shouldn't (and won't) be including Perl in this package.
#           3) Any takers on re-engineering this as a distinct version in perl?
#
#
# PRODUCTION DATA FILES/DIRECTORIES USED:
# --------------------------------------
# Note: {server_name} is a reference to the hostname on which this script is
#           being executed.
# /sysadmin:
#           Should be an NFS/Automountd exported filesystem on the primary
#           production server (which will be exporting it).  Ensure when
#           that root server is exporting the filesystem, it is giving
#           read/write priv's (anon=0).  Clients will mount this to access
#           the scripts and data storage locations.
#           Normal permissions are 755 root {default_group_for_root}
# /sysadmin/zhostlists/{server_name}/Current:
#           Input parameter file which is referenced by this script at the
#           beginning for comparision purposes and by sagrep to identify the
#           current server(s) and filesystem listing(s) available to search.
#           Data format is as follows:
#           Line 1:      Date and time of most current file (yymmdd.hhmm).
#                2-EOF:  List of dates for this server for which data is
#                        available.  Data is useful to speed sagrep processing.
# /sysadmin/zhostlists/{server_name}/{server_name}.{yymmdd.hhmm}.Z
#           Compressed filesystem listing, minus NFS filesystems.
#           Be extremely careful if you choose to manually remove any of
#           these files.  Especially dangerous is the removal of the most
#           current file.  If you choose to remove the last file (and diff)
#           then you must update "/sysadmin/zhostlists/{server_name}/Current"
#           to reflect whichever file is the most current.
# /sysadmin/zhostlists/{server_name}/{server_name}.{yymmdd.hhmm}.diff.Z
#           File containing the differences between the previous zlister
#           execution for this server and the most current execution.
# /sysadmin/zhostlists/{server_name}/{server_name}.{yymmdd.hhmm}.errors
#           File containing output to standard error when executing the
#           "/bin/ls -laR /" commmand.  It will only exist when the
#           execution on the specific date/time encountered errors.
# /sysadmin/zhostlists/{server_name}/misc-data:
#           Directory holding compressed files on system statistics and
#           performance data.  Directory and data generated by the
#           zlister companion script "zlister.stats".
# /tmp/zlister.{yymmdd.hhmm}
#           Directory where temporary files used to build the final
#           product(s) are created/manipulated.  These files will be
#           retained when the $test environment variable is set to "YES".
#
#
# TEMPORARY INSTALLATION FILES/DIRECTORIES:
# ----------------------------------------
# {More to appear here, eventually...}
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
# TEMPORARY FILES/DIRECTORIES (located under /tmp/zlister.{yymmdd.hhmm}:
# ---------------------------------------------------------------------
# {More to appear here, eventually...}
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
# HISTORY:
# -------
# 1.0  Provided basic capability to list a complete filesystem on
#      the targeted server, parsing the path of each directory, 
#      pre-pending that path before each directory/file entry and
#      then storing the resulting file in compressed form.  Provided
#      for multiple listings per day.  zlister originally was known as
#      'fs' and actually fit on one normally printed page of paper.
#      Added logic to allow proper execution via cron.
#
# 1.1  Improved detection of where the storage directory is located
#      (and that it has the proper permissions).  Added enhanced code
#      via awk script to identify filesystems mounted from remote
#      machines and eliminiate such directories and files from the
#      collected listing.  Enhanced fixes supporting 'sagrep'.
#      Standardized names of awk scripts.
#
# 1.2  Added support to properly diff the previous file with the newly
#      generated file.  Added protections when file systems are accessed
#      via the Automount daemon.
#
# 1.3  Tweaked zlister a little by removing -v option from the compress
#  &   program.  For some strange reason (at least under Solaris), compress
# 1.3a sends its compression ratio message(s) to stderr(?).  Discovered the
#      exact same type of problem (under Solaris) with automountd.  Revised
#      the zlister.awk.sort.PostProc script so that records identifying
#      directories AND that have identical permissions, owner and group
#      information are not written to the output file.  This will save
#      dramatically on output space.  1.3a was the last version
#      implemented at USACOM prior to my xfer.
#
# 1.4  Enhanced processing when executed on a new platform for the first
#      time; when executing under /tmp/sysadmin/zlister.bin vice the
#      normal/default/standard location of /sysadmin/zlister.bin.
#      Tweaked awk's, especically to handle "unique" /dev dir's on HP-UX.
#
# 1.4a 960521@1326 Minor tweaks.  General distribution began.
#
# 1.4b 960624@2145 Minor tweaks.  Rebuilt documentation portion dealing with
#      installation of zlister.  Enhanced diff process to eliminate records
#      that would otherwise have appeared simply because six months had
#      passed.  Improved management of temp space.  When not testing,
#      intermediary files will be purged, thus reducing space consumed
#      during execution.
#
# 1.5  Revised the zlister script to support the enhanced call to the
#      newly revised zlister.awk.noNFS (V:1.2) script which eliminates, in
#      the accumulated data, paths to files/dirs subordinate to
#      NFS/Automountd mount points.  Newer version is not executed
#      iteratively, but singularly.  All available mount points are passed
#      to it and in one execution, properly eliminates records identified
#      in remotely mounted filesystems.  This is the newest piece and I didn't
#      have a machine to test it on; I simulated the situation and then tested.
#      You should really check out the data to ensure you are getting the
#      results you think you should be getting.
#
# Still to be implemented:
# 1.x  Streamlined and optimized functionality, reduced execution output verbosity
#      and eliminated some data protection(s) used during earlier stages of
#      development.  Implemented standard logging to a file of script
#      execution; and rounded out documentation in all files, enhanced
#      installation instructions.  Implemented better check(s) for available
#      space early on in the script, and made the later portions smarter on
#      removing intermediary files when space is especially tight.
#
# 1.x  Incorporate the "Planned Enhancement"'s section.
#
# 2.0  Rethought direction taken to do all of this.  Might try something like
#      manually figuring out the mount points, using that as input to the
#      find command.  Further have the find execute an ls -lad on each item.
#      Will need an additional awk script to place blank lines after each
#      directory entry (looks nicer that way).  Still don't believe this is
#      a good workable way to do things.  But what the heck.
#      This version number with this specific fix may never occur.
#
#
#
#
#
#
#
#
#
#
#
#
#
# PRODUCTION INSTALLATION INSTRUCTIONS:
# ------------------------------------
# 1)  Pick a server in your domain that will have the greatest success as the Master
#     Server for storing the zlister data.  The bulk of the instructions below will
#     occur/pertain to this Master Server.  Another concern should be to place zlister
#     on one of your faster drives, not one of the slower ones.  This will speed
#     production of the data as well as facilitate its future retrieval.
#
# 2)  I recommend staying with the default/standard location for storage of these
#     scripts and data areas.  Should you decide otherwise, then assume YOUR OWN
#     location in place of "/sysadmin" when referenced here.  But you are then forced
#     to make script changes.  Alternatively you could store the data where-ever you
#     choose and link /sysadmin to that path (ln -s /sysadmin /your/path).
#     Give consideration to where the data will be stored.  Specifically, which server
#     will have available the storage space for holding the data and will not be "too"
#     busy to be the NFS Server (communications wise).  That repository will
#     be known as the server.  All others using/storing data there will be clients
#     of the server, using that area.  So to use the default, perform:
#          mkdir /sysadmin
#          chmod 755 /sysadmin
#          cd /sysadmin
#          mv /{your path to the directory containing}/zlister.taz to /sysadmin/zlister.tar.Z
#
# 3)  The distributed file is a compressed tar archive.  To extract the files, do the following:
#          uncompress zlister.tar.Z
#          tar xvf zlister.tar
#     This will create the /sysadmin/zlister.bin directory and install the production scripts
#     in there with their appropriate permissions intact.
#
# 4)  Manual execution of zlister at this time is a good idea to build your initial
#     filesystem listing.  To do so, execute the following:
#          /sysadmin/zlister.bin/zlister
#     Watch all the on-screen progress activity for information on what is occuring.
#     Review the output files generated look under /sysadmin/zhostlist/{your server name}
#     as a starting point.  The files ending with ".Z" are unix compressed.  "zcat" can be
#     used to view them (remember to pipe to more).
#     Allow some time to pass (a day), and then manually re-execute zlister.  Again, review
#     the output files generated.  One specific file of interest should be the ...diff.Z output.
#     It shows what changes have occured to what files since the last time zlister was ran.
#
# 5)  The zlister csh script will execute to completion, without modification.  By default
#     it searches for a standard location to execute (and utilize the necessary awk scripts)
#     from and a standard location to store the finished data.  These directories are
#     referenced by the $ProdS and $PTWD variables respectively.  If the default parent
#     directory (/sysadmin) doesn't exist, then all data collected will remain under the
#     /tmp/zhostlists/zlister.{yymmdd.hhmm} directory.  The intemediary
#     /tmp/zhostlists will automatically be created either under /tmp or under
#     /sysadmin (but only if it didn't already exist there).  To allow retention
#     and query of data files, either this zlister script and the accompanying
#     sagrep script must both be modified; -or- create the '/sysadmin' directory
#     on a the "host" server and all clients.  Then, through either NFS or
#     Automountd, mount the /sysadmin partition on all other clients/workstations
#     that you desire to run this process on.  Read below for an explaination
#     of what to change and how.
#
# 6)  To completely remove a server and its accumulated data from being available from being
#     reviewed by sagrep, do the following command:
#     "rm -rf /sysadmin/zhostlists/{server_name}" where {server_name} is
#     the hostname you wish to remove.  To remove all stored data: rm -rf /sysadmin/zhostlists
#
# 7)  Ensure the Master Server (the repository) is SHARE'ing the data/program area.
#     Ensure all clients are properly mounting the SHARE'd area and server and clients
#     are consistent in their implementation.
#     (If the repository is small on available disk space, consider way(s) to keep "old"
#      data constantly migrated offline or removed.  Provide suggestions on possible
#      methodoligies.)
#
# 8)  Consider how frequently zlister should be ran and whether you desire that to be
#     always be manually or via a cron job.  If via cron, must be setup only for a uid(0)
#     account.  That is, it must be executed as root; or root-equivilant.
# 
# 9)  If sysadmin is created under /tmp, then the "zhostlists" dir will be there as well.
#     To place them in their natural homes, do the following:
#          mkdir /sysadmin
#          chmod 755 /sysadmin
#          mv /tmp/sysadmin /
#          mv /tmp/zhostlists /sysadmin
#
#10)  If upgrading from a previous version, recommend keeping the old zlister.bin dir
#     by: "mv /sysadmin/zlister.bin /sysadmin/zlister.bin.prev".  Then un-tar this
#     group of scripts into a brand new /sysadmin/zlister.bin directory.  Start fresh.
#
#
# FREQUENCY OF EXECUTION:
# ----------------------
# Exact start time should be sometime after normal working hours and staggered
#   across servers (to reduce device/server contention).
# Should run zlister with enough lead time for completion before the daily save is scheduled.
# Running time for a SUN 1000 with expansion Pedestals AND 30GB SparcStorage
#   Arrays is ~85 Minutes.  (~210,385 lines in the acom1000 host output file).
#
# Examples are below of (ZULU time) root crontab entries and their timing.
#    The entries are staggered across servers to avoid NFS/Automountd clashes.
#     Optional redirection can include something like "> /tmp/zlister.today".
#
# [acom1000]  05 02 * * * /sysadmin/zlister.bin/zlister
# [usacom  ]  05 03 * * * /sysadmin/zlister.bin/zlister
# [acomjmcs]  05 04 * * * /sysadmin/zlister.bin/zlister
# [acomgsrt]  05 05 * * * /sysadmin/zlister.bin/zlister
#
#
#
#
# PLANNED ENHANCEMENTS:
# --------------------
# Implement $LOG for output.  Keep data under /tmp/zlister.{yymmdd.hhmm}.
#   Then move it with live data files (based on $test).  Also could setup
#   for a standard 7-day (mon, tue...) file/day rotation.
#
# {Implement daily (server-by-server) log files to be used as standard
#  output for zlister execution and for diff output to be reviewed.
#  There should be a directory to contain seven files (Mon, Tue, etc...)
#  These will be the log of zlister execution activity.  Accompanying them
#  will be another 7 files: Mon.diff, Tue.diff, etc...  These will contain
#  the daily diff output.  The standard files will still be collected in
#  the normal place(s) but these are in addition to - and will simply be
#  overwritten when next cycled back thru.}
#
# Trap interupts (like <Ctrl>c) to at least perform the 'unsetenv' stuff as
#   this job abnormally dies.  In zlister.stats and sagrep as well.
#
# Fix up to support a passed-argument to only list (pre-ufsdump lvl-0 save)
#   and then check for it later and finish the script up.  Will also help
#   when this is run in single-user mode and later that same data is
#   desired to be kept.
#   -S servername #server listing came from
#   -f filename   #filename (including path if necessary) of file to process.
# Allow an argument "-P /path/to/file" where file is an 'ls -lR' file.  Typically
#   this will be downloaded from a site on the internet (i.e. sunsite.unc.edu).
#   Based on the input file, determine if it is still compressed (or gzipped) and
#   handle appropriately.  Process it through the zlister.awk.ls-laR, then check
#   for a previous file, diff if possible, then compress it all and put it away.
# Accept an argument and identify specially (somehow) that the listing was
#   generated incidental to a save.  Add logic so that we keep back a
#   specified number of pre-save zlister files for this server.
#
# Implement check for number of files to keep historically; and if set,
#   automatically remove those older than that number.  But should be off
#   by default.
#
# Consider possibility putting some of the grep's and line count stuff in
#   the background.
#
# Should we enhance code to protect for a 4 digit year (yyyy) field (the
#   year 2000 is coming up fast)?  Maybe make it an option early on in the
#   script.
#
# Create a generic installation script that will setup the default directory
#   structure and proper permissions.  Or - that could be an accepted
#   argument/option that this script detects.
#
# Further explore space saving conservation efforts that can be performed if
#   / and/or /tmp space is EXTREMELY limited.  For instance removing
#   intermediary products from awk's, diff and sort.  And provide for suicide
#   when / and/or /tmp filesystem is WAY TOO small (like 100+ percent full).
#
# When out of test mode, test for the existance of $tmp.  This would mean that
#   the administrator kicked off zlister twice in the same minute.  If $tmp
#   already exists, then the current execution is the second one and MUST
#   commit suicide.  Executing a minute apart is the answer if they REALLY
#   NEED to be performed that closely together.  Test this.
#
# Test when /sysadmin is a link to someother point in the filsystem both
#   locally and remotely.  Do all the changes to owner/group/perms remain ok?
#   Does the logic to set them recursively continue to function properly?
#
# Is there any way out of all this processing that the TimeZone is indicated
#   in the saved output?
#
# Add intelligence to support zlister.V:#.#.orig naming/testing, vice what is
#   begin done now.
#
# Add a --help option to explain some things to the user.
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
# SCRIPT EXECUTION BEGINS:
# -----------------------
# set echo
# ******************************************************************************
# * 1.0  Establishment of the production environment (housekeeping).           *
# ******************************************************************************
set zlister_version = "1.5"

set bad = 999   # Used as an exit code.

# Must be root, else not guarenteed to list the entire filesystem.
if ( `whoami` != "root" ) then
     echo " "
     echo "     Error: $0"
     echo "            MUST be run as root, not as: `whoami`."
     echo "            Otherwise the entire filesystem may not"
     echo "            be properly documented."
     echo " "
     echo "     Exiting...."
     exit $bad
endif

if ( -e /tmp/zlister.no ) then
     # The presence of this file means that we do not want zlister to execute at this time.
     #   Handy when, in a pinch, you don't want it to execute.... but you know cron is going
     #   to kick it off soon.  You should manually kick this off afterwards, so as not to
     #   loose continuity.  :)
     echo " "
     echo "     *****************************************************************************"
     echo "     *** zlister is prevented from executing because /tmp/zlister.no exists.   ***"
     echo "     *** Remove the file to continue.  Execute zlister when ready to continue. ***"
     echo "     *****************************************************************************"
     echo " "
     echo "     Exiting...."
     exit $bad
endif

#   Protecting for the possibility of manual/automatic execution.  We need to know where
#   the supporting awk scripts can be found at.  If we can't find, exit.
set orig     = "`dirname $0`"
set origtest = "`dirname $0`/zlister.orig"
set origpwd  = "`pwd`"
if ( -e $origpwd/zlister.awk.ls-laR ) then
     # Found it in the current working directory.
     set ProdS = $origpwd
else
     if ( -e $origtest/zlister.awk.ls-laR ) then
          # Found it in the explictly stated path (on the command line $0).
          set ProdS = $origtest
     else
          if ( -e /sysadmin/zlister.bin/zlister.awk.ls-laR ) then
               # Found it on the path in the standard location.
               set ProdS = /sysadmin/zlister.bin
          else
               if ( -e /tmp/sysadmin/zlister.bin/zlister.awk.ls-laR ) then
                    # Found it on the path in the standard temporary installation/execution location.
                    set ProdS = /tmp/sysadmin/zlister.bin
               else
                    echo "zlister cannot find the required awk support scripts."
                    echo "origpwd($origpwd), origtest($origtest)."
                    echo " "
                    echo "Exiting..."
                    echo " "
                    exit $bad
               endif
          endif
     endif
endif

# Protecting the original script (nice thing to do).
#   This needs a little more work.
if ( ! -e $origtest ) then
     cp -p $orig/zlister $origtest
endif
#echo "ProdS($ProdS)."

# Modify $path to support implementation on other than Solaris servers; original path is protected in support of manual execution.
set prot_path = "$path"
# echo "Path var was already set with: ($path)."
# echo " "

# Improve the following with aliases for non-Solaris commands.

# For systems running under automount, check out man `ps -aef` outputs ensuring before and after
#   reports are looked at for the "-t" argument.  Over time, do future ones show "-t" output?
#   What about after boot's and subsequent executions of zlister...What happens? And then more
#   boot's/reboot's?  And then execution of zlister again?

# Need to implement a better way to check the default time for automount.  And does it have to be platform specific?

set IAM=`uname`
switch ( $IAM )
       # Add sections here for your host, utilizing the basic format seen below.
       case "SunOS":
            #Solaris 2.3 (GCCS Standard), though this has also worked under 2.4 and 2.5.
              echo "SunOS"
            set path=( /bin /usr/bin /etc /sbin /usr/bin/X11 /usr/sbin /usr/etc /usr/local/bin )
            set path=($path /usr/ucb /usr/ccs/bin /usr/lib /usr/lib/nis )
            alias df-k '/bin/df -k'
            alias automount  '/usr/sbin/automount'
            alias automountl '/usr/sbin/automount -t 7000'
            alias automounts '/usr/sbin/automount -t 300'
            breaksw
       case "HP":
            # Not tested (guessed).    {Need specific Version #'s}
              echo "HP"
            set path=( /bin /usr/bin /etc /sbin /usr/bin/X11 /usr/sbin /usr/etc /usr/local/bin )
            set path=($path /usr/lib /usr contrib/bin )
            alias df-k '/bin/bdf -L'
            alias automount  '/usr/sbin/automount'
            alias automountl '/usr/sbin/automount -tl 7000'
            alias automounts '/usr/sbin/automount -tl 300'
            breaksw
       case "HP-UX":
            # (Tac-3) "HP-UX starbase A.09.01 E 9000/750"
            # (Tac-4) "HP-UX hpinst1  A.09.07 E 9000/712"
            # (Tac-4) "HP-UX orbiter  B.10.00 A 9000/712"
              echo "HP-UX"
            set path=( /bin /usr/bin /etc /sbin /usr/bin/X11 /usr/sbin /usr/etc /usr/contrib/bin )
            set path=($path /usr/local/bin /usr/lib /usr/tran/sparc/bin /utils )
            set ver = `uname -a | cut -d' ' -f3`
            if ( $ver == "B.10.00" ) then
                 alias df-k '/bin/bdf -L'
                 # Automount on HP-UX might pose problem(s) as the manpage says "mount and bdf won't show 
                 #   currently mounted filesystems mounted via the automounter".  This will cause problems in
                 #   the resulting compressed output as structure will remain in the file that really doesn't
                 #   reside on the platform listed.  Must find some way around this.
                 # Maybe add code to check automount files, parse, and then eliminate?
                 alias automount  '/usr/sbin/automount'
                 alias automountl '/usr/sbin/automount -tl 7000'
                 alias automounts '/usr/sbin/automount -tl 300'
            else
                 if ( $ver == "A.09.01" || $ver == "A.09.07" ) then
                      # This platform may cause a problem. The following appears in the hp automount manpage:
                      # Automatically-mounted file systems are mounted with type ignore; they
                      #   do not appear in the output of either mount(1M), or bdf(1M).
                      # Might have to program a workaround (grrrr).
                      alias df-k '/usr/bin/bdf -L'
                      alias automount  '/usr/etc/automount'
                      alias automountl '/usr/etc/automount -tl 7000'
                      alias automounts '/usr/etc/automount -tl 300'
                 else
                      echo "Your specific version of HP-UX is unknown to this environment."
                      echo "Locate your 'bdf' and 'automount' executables, then"
                      echo "update this script (zlister and zlister.stats) with"
                      echo "the locations for those binarys."
                      echo " "
                      exit $bad
                 endif
            endif
            breaksw
       case "Linux":
              echo "Linux"
            set path=( /etc /bin /usr/bin /usr/sbin /usr/ucb /sbin /usr/X11R6/bin /usr/X11/bin )
            set path=($path /usr/openwin/bin /usr/local/bin )
            alias df-k '/bin/df -k'
            # Need a 'ps' check as well as a '-e automount' existance check
            if ( -e /usr/etc/automount ) then
                 alias automountl '/usr/etc/automount -v -tl 7000'
                 alias automounts '/usr/etc/automount -v -tl 300'
            else
                 alias automountl 'echo " "'
                 alias automounts 'echo " "'
            endif
            breaksw
       default:
            echo "Your operating system ($IAM) is unknown to this environment."
            echo "You will have to include additional code to figure out where"
            echo "certain basic unix commands are.  Please read the beginning"
            echo "comments of the zlister script and up to the section that"
            echo "establishes the system path and the alias's."
            echo " "
            echo "Please send me the code changes you made so I can include"
            echo "your environment in future versions.  Thank you (Joe Wulf)."
            echo " "
            echo "Exiting..."
            exit $bad
            breaksw
endsw
if ( -e /sysadmin ) then
   set path=( $path /sysadmin /sysadmin/zlister.bin )
else
   if ( -e /tmp/sysadmin ) then
        set path=( $path /tmp/sysadmin /tmp/sysadmin/zlister.bin )
   endif
   # Update this piece with the current location of the executable scripts, else exit.
endif
# echo "Path var now set with: ($path)."
# echo " "

# Fixup this display so that the size of the host name is taken into consideration plus two spaces.
# Presumes a "x.x" format for the version number.
set    x      = `hostname | awk '{print length($0)}'`;@ x++ 
setenv Space    "`echo '          |' | cut -c $x-11`";unset x
echo "*--------------------------------------------------------------------------------------*"
echo "|  zlister (Version $zlister_version)             Started   `date`, `hostname`$Space"
echo "*--------------------------------------------------------------------------------------*"
set date1="Started at:   `date`."

# Set the date/time to a usable, sortable construct.
set IT   = `date +%y%m%d.%H%M`

# Set the owner and group access per site needs.  Owner is recommended to be whatever root's group is, to keep write priv's to a very limited few.
  set owner="root"
  set group = `grep root /etc/passwd | head -1 | cut -d: -f4`
      # $perms is wide open (at 755) for all users to read the files.
      #   If you choose, you can make this more restricitive (i.e. 740).  But this would provide error messages to users attempting access.
  set perms='755'

# By default perform all work under /tmp.
# You'll find everything that will be run under '/tmp/sysadmin' and '/tmp/zlister.$IT' in the virgin, production scripts.
# '/sysadmin' is the default parent directory for System Administration work/files.....
# Typically it is an NFS/automountd directory living on a single host and shared amongst the remaining servers (clients).
# To support this, '/sysadmin' must be explicitly shared from the home/parent server, and mounted by either
#    NFS or the Automountd daemon.

      # Might test to see if /sysadmin is a link to another point in the filesystem.  Generally this isn't a problem
      #   except when performing the recursive changes to permissions, owner and group fields.
      # Permissions on /sysadmin should be 755.
      # Not ready to force permissions at this level yet, especially if it is a link (then should be 777), or "/tmp".

# Lets begin figuring out where we are and where we are going to.
set PTWD='/sysadmin'
if ( ! -e $PTWD ) then
     echo "The standard starting location: PTWD($PTWD), doesn't exist."
     # For now check /tmp/sysadmin, if it exists then use it (/tmp/sysadmin/zhostlists)
     #                                           else use    (/tmp/zhostlists)
     # Tell the user what is going on.
     echo " "
     echo "This is a problem.  I'll continue to build/store  everything as you would expect;"
     echo "however, all files will remain under /tmp/zhostlists and /tmp/zlister.{DATE}.{TIME}."
     echo " "
     echo "When ready to store data in the standard, production location - either change"
     echo "the value of the PTWD variable, near the top of this script; or create the"
     echo "standard location ('/sysadmin') via:  mkdir /sysadmin."
     echo "Now might be a good time to also fix the sagrep script and put it in a good home"
     echo "(like /usr/local/bin).  :)"
     echo " "
     echo "Most likely this is being run for the first time, unmodified, from a new server,"
     echo "or you are continuing to execute it from /tmp (ok for testing)."
     echo "Now might be a good time to also fix the sagrep script and put it in a good home."
     echo " "
     echo "You can break (<CTRL>-C) now, or allow this test run to continue... (Sleeping 15)."
     sleep 15
     set PTWD='/tmp'
else
     echo "PTWD($PTWD) exists; excellent."
     # Safe to run these now and in the background, all other work is done under /tmp.
     if ( $PTWD == '/sysadmin' ) then
          # Force the proper permissions now, but only if /sysadmin is the right dir.
          #   Otherwise, we will be changing /tmp; and that ISN'T good.
          chmod 755 $PTWD
     endif
endif
echo " "

# "zhostlists" is the standard location used for this effort; but you certainly can define your own.
# This will be the working directory to contain each server name.  These server-name-sub-directories
#   will contain server-specific filesystem listings (and stats from zlister.stats eventually).
set PTWD2='zhostlists'
if ( ! -e $PTWD/$PTWD2 ) then
     echo "PTWD/PTWD2($PTWD/$PTWD2) doesn't exist.  This isn't a problem."
     #                                              (Famous last words.)
     echo "Creating $PTWD/$PTWD2 for you now."
     set echo;mkdir $PTWD/$PTWD2
     if ( ! $status == 0 ) then
          unset echo
          echo "Encountered error creating the $PTWD/$PTWD2 directory."
          echo "You'll need to investigate....."
          exit $bad
     else
          unset echo
     endif
     echo "Guess we're OK.  But, there are no previous files."
     echo " "
     set diff = "NO"
     echo "diff ($diff), PTWD/PTWD2($PTWD/$PTWD2)."
     echo " "
     # Rearrange the sleep command to be before we actually make the change.
     echo "You can break (<CTRL>-C) now, or allow this test run to continue... (Sleeping 15)."
     sleep 15
else
     echo "PTWD/PTWD2($PTWD/$PTWD2) exists; excellent."
endif
# Force the proper permissions now.
chmod 755 $PTWD/$PTWD2
echo " "

# For consistancy in this script, as well as in 'sagrep', $Srvr must equal the `hostname` of this box.
# This will be for the actual server this filesystem listing is being prepared for.
set Srvr = `hostname`
if ( ! -e $PTWD/$PTWD2/$Srvr ) then
     echo "PTWD/PTWD2/Srvr($PTWD/$PTWD2/$Srvr) doesn't exist.  This isn't a problem."
     echo "Making sub-dir $PTWD/$PTWD2/$Srvr for you now."
     set echo;mkdir $PTWD/$PTWD2/$Srvr
     if ( ! $status == 0 ) then
          unset echo
          echo "Encountered error creating the $PTWD/$PTWD2/$Srvr directory."
          echo "You'll need to investigate....."
          exit $bad
     endif
     unset echo
     # Rearrange the sleep command to be before we actually make the change.
     echo "You can break (<CTRL>-C) now, or allow this test run to continue... (Sleeping 15)."
     sleep 15
     # Onetime setting to protect us.
     echo "Never" > $PTWD/$PTWD2/$Srvr/Current
     echo "Guess we're OK.  There are no previous files."
     echo " "
     set diff = "NO"
     echo "diff ($diff), PTWD/PTWD2/Srvr($PTWD/$PTWD2/$Srvr)."
     echo " "
else
     echo "PTWD/PTWD2/Srvr($PTWD/$PTWD2/$Srvr) exists; excellent."
endif
# Force the proper permissions now.
chmod 755 $PTWD/$PTWD2/$Srvr
echo " "

# Now we know where we are working out of (in support of awk script execution).
set PROD = $PTWD/$PTWD2
# echo "PROD($PROD), ProdS($ProdS)."
echo " "

set Dvdr = "--------------------------- [$Srvr / Divider] ----------------------------"

# Check for existance and then set; else first time ran for this server?
#   And, sanity-check: is the home server where the data resides alive?
#   Cause we will most likely be NFS mounting that home.
#
# There should always be a current file, if we get this far into the script.
# Either it contains a valid date.time (from a previous run) -or- 
#        it contains the word "Never" (indicating never having been run before).
     set Crnt = `cat $PROD/$Srvr/Current | head -1`

if ( ! -e $PROD/$Srvr/Current ) then
     echo "This is the first run for this server; no previous file exists."
     set diff="NO"
else
     set Crnt = `cat $PROD/$Srvr/Current | head -1`
     if ( ! -e $PROD/$Srvr/$Srvr.$Crnt.Z ) then
          set ITDOES="IT does NOT exist."
          set diff="NO"
          # Add logic to "figure out" which file is the last production output.
          #   So that we can verify $Crnt.Z against what the real last file is
          #   Then what do we do?
     else
          set ITDOES="It does exist."
          set diff="YES"
     endif
     echo "Previous production file was: $PROD/$Srvr/$Srvr.$Crnt.Z; and $ITDOES"
endif
echo "New file production will be:  $PROD/$Srvr/$Srvr.$IT.Z"
echo "diff ($diff)."


# Implement a temp sub-directory to drop all data into so as not to utilize production nor NFS filespace, until we're ready to.
# Make it on the fly and IF everything is ok at eoj, then forcefully remove it; but after the data is properly moved.
if ( ! -e /tmp/zlister.$IT ) then
     mkdir /tmp/zlister.$IT
     set Stat = $status
     if ( $Stat != 0 ) then
        echo "There was an error in creating the temp directory"
        echo "where the data will be massaged.  This is a problem"
        echo "that you must investigate.  status($Status)."
        echo " "
        echo "Exiting..."
        exit $bad
     endif
endif
set tmp="/tmp/zlister.$IT"
echo " "



##[Test area]############################***********************************----------------------------------------------------
# ******************************************************************************
# * 1.9  Test settings used to assist development.                             *
# *      This will eventually be removed.                                      *
# ******************************************************************************
# Used while this script is still being developed.
# Placed here to allow normal processing above, and for troubleshooting.  This way the above
#   can set things as appropriate; then force a test condition anyway.  Will delete when really ready for production.
  set test = "NO" 
# set test = "YES"

# Delete /tmp/zlister... when execution is complete?
  set deltmp = "YES"
# set deltmp = "NO"

# Fake mount points to remove?  Newly added to test improved awk script.
# set fakerm = "YES"
  set fakerm = "NO"

#Define the nice value...
# set nice="-3"    # Seems FASTER during execution...  Check csh manpage.
  set nice="-12"   # Moderate timeframe to work with (good for generic production runs).

# Allows a work-around to the actual gathering of the file system listing.
  set byp = "NO"
# set byp = "YES"

echo "test($test), deltmp($deltmp), nice($nice), byp($byp), Really diff($diff)."
echo " "

##[Additional Test Area]#################***********************************----------------------------------------------------
# Take advantage of this when utilizing a set of files already generated.
# But, must run zlister fully one time, then change below as appropriate.
if ( $byp == "YES" ) then
     #   But set the date to the most current test/temp run.
     set nice = "-3"
     set Crnt = "960518.1040"
     set IT   = "960707.1857"
     set tmp  = "/tmp/zlister.$IT"
     set PNW = `cat $tmp/paths.not.wanted | tr '\012' ' '`
     echo "IT($IT), tmp($tmp), PNW($PNW), and we bypassed."
     echo " "

     # goto bypass
     # goto bypassNFS
       goto DoREALD
     # goto bypassDIFF
endif
##[End of Test Areas]##[Going back into production]*************************----------------------------------------------------



# ******************************************************************************
# * 2.0  Gathering of data.                                                    *
# ******************************************************************************
# And away we go (production run)...
echo "Pre job-run sync(s)."
echo "bing";sync
echo "bang";sync
echo "bong";sync

# For Automountd process - determine/protect current (default?) time-to-live and reset to two hours.
# "mount -a", "mountall -l" don't work the way I'd like them too.
# Somehow...
automountl
set Stat = $status
if ( $Stat != 0 ) then
     alias autommountl
     echo "automount command returned the following status($Stat)."
endif

# SHOULDN'T be aliased, but lets be positive.
unalias ls

           # Temporary, while checking automount capability.
           df-k
           echo " "

echo " ls -laR /         (Nice'd $nice)     Point(2.0)  `date`, $Srvr."
# Implemented $nice value to free system resources; enhanced redirection to pickup errors.
# Check remainder of this script to ensure the *.errors file is compress/moved into production. No errors, no move of file.
# (Sometimes still doesn't catch all the errors.  For instance:  "NFS server dbserver not responding, giving up".
# Collection of the complete filesystem will utilize NFS/Automountd for all filesystems that are mounted from other server/workstations.

      # Investigate other attributes to 'ls' that will provide other dates/times.
      #    ls -l provides 'modification' time
      #    ls -u          'last access'  time
      #    ls -n          'UID/GID' numbers, vice owner and group names.
      # Combine all output onto ONE line.  Build special fix.ls-laR process to handle.
      #    Final output should contain a single line of column headers at top of file.
      # However, to incorporate any of the above, would require a re-write of "zlister.awk.ls-laR".
      #
      # I'll go through all this, but want feedback from those desiring it.

# Current reasons for using ls -laR vice find:
#   1) Varied platforms (OS's) with varied find options for eliminating filesystems including some for remote(s) only.
#   2) Not sure how to code logic to walk through all the output for the local filesystems, but not the remotely mounted ones.
#   3) This process has worked and I'd welcome other suggestions/input.
#

#            =========
( nice $nice ls -laR / > $tmp/$Srvr.$IT.ls-laR ) >& $tmp/$Srvr.$IT.ls-laR.errors
set Stat=$status

set LsErr=`ls -l $tmp/$Srvr.$IT.ls-laR.errors | awk '{ print $5 }'`
if ( $LsErr == 0 ) then
     echo "No errors accumulated during generation of the filesystem listing."
else
     # What is done with this file?----------------------------------------------------- *********************
     echo "The following system errors occured during filesystem listing generation:"  > $tmp/$Srvr.$IT.errors
     echo " "                                                                         >> $tmp/$Srvr.$IT.errors
     cat $tmp/$Srvr.$IT.ls-laR.errors                                                 >> $tmp/$Srvr.$IT.errors
     echo "Status($Stat).  Some errors accumulated during the ls of the filesystem listing generation."
     /bin/ls $tmp/$Srvr.$IT.errors
     echo "-*-*-*------[Begin display of errors]--------------------*-*-*"
     cat $tmp/$Srvr.$IT.ls-laR.errors
     echo "-*-*-*------[End display of errors]----------------------*-*-*"

     # Is this right?
     # rm $tmp/$Srvr.$IT.ls-laR.errors
endif
echo " ---- ls -laR is complete,    status($Stat) ----  `date`."             | tee -a $tmp/$Srvr.$IT
echo " "


# Identifies NFS mounted filesystems and their mount points.
# Using those records, delete those pieces from a fixed ls -laR listing.
# For each path, eliminate those records from the fixed listing
# *** Eventually, once perfected, place the next two lines at top of script; instead of here.
# Sort them in reverse order to prevent problems.  <<<--- Test this thought with the new version of awk.NoNFS.
# Combine all entries in 'paths.not.wanted' as a space delimited single line...
# These entries will be used later, during the elimination of NFS mount data.  But their data is gathered now.
echo "   ID paths not wanted                Point(2.1)  `date`, $Srvr."
mount | grep ":/" | sort -r | cut -d" " -f1 > $tmp/paths.not.wanted
          # Test and setup for fake mount points to remove.
          if ( $fakerm == "YES" ) then
               echo "*****************************************"
               echo "** Using fake mount points for testing **  Setup complete."
               echo "*****************************************"
               echo "/etc"        >$tmp/paths.not.wanted
               echo "/usr/man"   >>$tmp/paths.not.wanted
          endif
set NUM = `cat $tmp/paths.not.wanted | wc -l | tr -d ' '`

echo "Basic sysinfo collection."
echo " "                                                                               > $tmp/$Srvr.$IT
echo "   $Srvr  $IT."                                                                 >> $tmp/$Srvr.$IT
echo "   Built with zlister V: ($zlister_version)."                                   >> $tmp/$Srvr.$IT
echo "                         `date`"                                                >> $tmp/$Srvr.$IT
echo " "                                                                              >> $tmp/$Srvr.$IT
echo " "                                                                              >> $tmp/$Srvr.$IT

# What about NIS+ passwd/group tables; should they be added here for completeness???
# If we do want them, must test for execution of NIS+ processes; and access to NIS+ server.
# Maybe better way would be to check for 'rpc.nisd' in execution.  If yes, then get tables for here.
echo "cat /etc/passwd | sort -t: -n +2 -4"                                            >> $tmp/$Srvr.$IT
cat /etc/passwd | sort -t: -n +2 -4                                                   >> $tmp/$Srvr.$IT
echo " "                                                                              >> $tmp/$Srvr.$IT
echo " "                                                                              >> $tmp/$Srvr.$IT

if ( -e /.secure/etc/passwd ) then
     # Found on SNAP III HP-UX 09.01
     echo "cat /.secure/etc/passwd | sort -nt: +2 -4"                                 >> $tmp/$Srvr.$IT
     cat /.secure/etc/passwd | sort -nt: +2 -4                                        >> $tmp/$Srvr.$IT
     echo " "                                                                         >> $tmp/$Srvr.$IT
     echo " "                                                                         >> $tmp/$Srvr.$IT
endif

echo "cat /etc/group | sort -nt: +2 -4"                                               >> $tmp/$Srvr.$IT
cat /etc/group | sort -nt: +2 -4                                                      >> $tmp/$Srvr.$IT
echo " "                                                                              >> $tmp/$Srvr.$IT
echo " "                                                                              >> $tmp/$Srvr.$IT

if ( -e /etc/shadow ) then
     echo "cat /etc/shadow | sort -nt: +2 -4"                                         >> $tmp/$Srvr.$IT
     cat /etc/shadow | sort -nt: +2 -4                                                >> $tmp/$Srvr.$IT
     echo " "                                                                         >> $tmp/$Srvr.$IT
     echo " "                                                                         >> $tmp/$Srvr.$IT
endif

# Generate an awk process to pretty up the df output.
# awk -f $PROD/x1/zlister.awk.df-k.
df-k
echo "df-k"                                                                           >> $tmp/$Srvr.$IT
df-k                                                                                  >> $tmp/$Srvr.$IT
echo " "                                                                              >> $tmp/$Srvr.$IT
echo " "                                                                              >> $tmp/$Srvr.$IT

# Generate an awk process to pretty up the mount output (What about automount?).
# awk -f $PROD/x1/zlister.awk.mount-v.
echo "mount"                                                                          >> $tmp/$Srvr.$IT
mount                                                                                 >> $tmp/$Srvr.$IT
echo " "                                                                              >> $tmp/$Srvr.$IT
echo " "                                                                              >> $tmp/$Srvr.$IT

# Restore shortened Automountd protected time-to-live.
automounts
if ( $Stat != 0 ) then
     alias automounts
     echo "automount command returned the following status($Stat)."
endif


# ******************************************************************************
# * 3.0  Format the output into desireable form.                               *
# ******************************************************************************
echo "  zlister.awk.ls-laR                  Point(3.0)  `date`, $Srvr."
rm -rf $tmp/$Srvr.awk.out.$IT >& /dev/null   # Shouldn't exist
#
# HP-UX 9.0.01 entry.
# crw-rw-rw-   1 root     root       3 0x000002 May  6 10:57 /dev/null
#
# Solaris entries.
# lrwxrwxrwx   1 root     root          27 Mar  6  1995 /dev/null -> ../devices/pseudo/mm@0:null
# crw-rw-rw-   1 root     sys       13,  2 Mar 12 13:16 /devices/pseudo/mm@0:null
#
# Use the next line when testing the rewrite of this awk script:
# date;rm zz.dev.out;awk -f zlister.awk.ls-laR.test  OutFile=zz.dev.out  zz.dev;date
#
nice $nice awk -f $ProdS/zlister.awk.ls-laR  OutFile=$tmp/$Srvr.awk.out.$IT  $tmp/$Srvr.$IT.ls-laR
set Stat=$status

echo " ---- fix.ls-laR is complete, status($Stat) ----  `date`."             | tee -a $tmp/$Srvr.$IT
echo " "                                                                     | tee -a $tmp/$Srvr.$IT

# Checking that we have good data out of awk process.  If not, prevent execution of remaining script.
set LsErr=`ls -l $tmp/$Srvr.awk.out.$IT | awk '{ print $5 }'`
if ( $LsErr != 0 ) then
     echo "Looks like the zlister.awk.ls-laR script completed successfully."
else
     echo "Status($Stat).  The zlister.awk.ls-laR script didn't successfully complete."
     echo "This requires investigation under /tmp/zlister..."
     echo "Exiting....  $tmp still exists."
     echo " "
     ls -la $tmp
     echo " "
     exit $bad
endif

echo "`tail -1 $tmp/$Srvr.awk.out.$IT`"                                            | tee -a $tmp/$Srvr.$IT
echo "       {Total # Lines:  `cat $tmp/$Srvr.awk.out.$IT | wc -l | tr -d ' '`}."  | tee -a $tmp/$Srvr.$IT
echo " "                                                                           | tee -a $tmp/$Srvr.$IT


# ******************************************************************************
# * 4.0  Elimination of records subordinate to NFS mount points.               *
# ******************************************************************************
echo "   New RmNFS procedure(s)             Point(4.0)  `date`, $Srvr."
# Utilizes already identified NFS/automountd mounted filesystems and their mount points.
# set echo
switch ( $NUM )
       case 0:
            set PNW = "No"
            echo "NUM($NUM), no mounted filesystems ($PNW); continuing."
            breaksw;
       case 1:
            set PNW = `cat $tmp/paths.not.wanted`
            echo "NUM($NUM), one mounted filesystem ($PNW)."
            breaksw;
       default:
            # For instance (/h/JMTK) and (/h/JMTKP1) now won't get in each others way.  Then put them all on one line.
            # Old version
            # set PNW = `cat $tmp/paths.not.wanted | tr '\012' ' '`

            # New version to support a comma-delimited path supporting one iteration of zlister.awk.noNFS (trailing comma removed).
              set PNW = `cat $tmp/paths.not.wanted | tr '\012' ',' | sed 's/,$//'`
            echo "NUM($NUM), many mounted filesystems: ($PNW)."
            breaksw
endsw

bypassNFS:
if ( ! -e $tmp/$Srvr.awk.out.$IT.preserve ) then
     if ( $test == "YES" ) then
          # Should only need to protect this when testing.
          nice $nice cp $tmp/$Srvr.awk.out.$IT $tmp/$Srvr.awk.out.$IT.preserve
     endif
endif
ls -la $tmp
echo " "


# goto REALD
DoREALD:
echo " "
# Here is the new procedure:
# Compute length of accumulated mountpoints.  If too long (how long is too long?) then
#   break it up into several pieces and iteratively remove them.
#
# Eventually FIX this so that the old process is totally removed.

     # Temp variables for development/testing.
     # setenv nice   "-3"
     # setenv Srvr   `hostname`
     # setenv ProdS  "/sysadmin/zlister.bin"
     # setenv ProdS  "/tmp/sysadmin/zlister.bin"
     # setenv PROD   "/sysadmin/zhostlists"
     # setenv Crnt   "960518.1040"
     # setenv IT     "960707.1857"
     # setenv tmp    "/tmp/zlister.$IT"
     # setenv NFSMNT "`cat /tmp/zlister.$IT/paths.not.wanted | tr '\012' ','`"
     # setenv NNM "`cat $tmp/paths.not.wanted | wc -l | tr -d ' '`"
     # setenv NFSMNT "/etc,/usr"
     # setenv NNM    "2"
     # setenv NFSMNT $PNW
     # rm ztest*;awk -f $ProdS/zlister.awk.noNFS.test NNM=$NNM UWMP=$NFSMNT OutFile=$tmp/ztest.CleanerFSList NW=$tmp/ztest.NotWanted.List $tmp/$Srvr.awk.out.$IT

echo "   New RmNFS procedure(s)             Point(4.1)  `date`, $Srvr."
if ( "$PNW" != "No" ) then
     # Here we are...
     setenv NNM "`cat $tmp/paths.not.wanted | wc -l | tr -d ' '`"
     setenv NFSMNT $PNW

     echo "Removing records for mount points subordinate to:"
     cat $tmp/paths.not.wanted
     echo " "

     echo "awk -f ($ProdS/zlister.awk.noNFS.test"
     echo "       UWMP    = ($NFSMNT)"
     echo "       NNM     = ($NNM)"
     echo "       OutFile = ($tmp/CleanerFSList)"
     echo "       NW      = ($tmp/NotWanted.List)"
     echo "                 ($tmp/$Srvr.awk.out.$IT)"

     # check limit here inside awk w/ 250, 500 1000, 1000+ chars lengths for mount points.
     #                 Script to execute        Unwanted mount points  # of      Output file                 Deleted records         Input file
     nice $nice awk -f $ProdS/zlister.awk.noNFS UWMP=$NFSMNT           NNM=$NNM  OutFile=$tmp/CleanerFSList  NW=$tmp/NotWanted.List  $tmp/$Srvr.awk.out.$IT

     # Rename smaller file to reflect 'Today', vice generic filename.
     cp -p $tmp/CleanerFSList      $tmp/Today.awk.out.$IT
else
     if ( $test == "YES" ) then
          cp -p $tmp/$Srvr.awk.out.$IT $tmp/Today.awk.out.$IT
     else
          mv    $tmp/$Srvr.awk.out.$IT $tmp/Today.awk.out.$IT
     endif
     echo " "
     echo "No mounted filesystems to deal with, continuing..."
endif
echo " "

echo "      Post.RmNFS                      Point(4.2)  `date`, $Srvr."
ls -la $tmp
echo " "

 
# ******************************************************************************
# * 5.0  Highlight differences between this listing and the one before it.     *
# ******************************************************************************
# Developed post-processor to be more specific and provide nicer to look at output than diff by itself.
#    Keeps all like lines together as pairs (based on $9/$10 (first piece of path)).
#    (Don't compare the data we put before the actual file system listing) header lines.
#    Remove the . and .. entries from the diffs' output (but not the src).
#      Ensure duplicate blank lines are removed.
#    Protect for files/dirs with date change (six months have passed without change); where time changes to year.
#    Must protect for any other possible filenames that may be listed above . and .. (for example %filename).
#    Produce report specifically for printing with page headers (*** Still to be done ***).
#
# Begin by comparing fields, in yesterday's file against today's, that begin with a slash "/" in
#   either field 9 or 10 (based on /dev).
# Ignore source/dest lines having less than 9 fields.
# Ignore source/dest lines which are just . and .. (except the very first ones in the filesystem (root).
# Compare all fields.  Protect/check for links to different file than yesterday.
#    Records that are completely the same, ignore.
#    Records that are completely the same, except for the date/time/year field, ignore.
#    Print all other records in the format of: "< Yesterday's record"
#                                              "> Today's record"
#                                               {blank line}
# Ensure pagesize, format (including headers) is defined and maintained.
# Identify records that occur in one file but not the other: "D Yesterday's record"  -or-  "A Today's record"
#                                                             {blank line}
#
# Suggestion used from Bill Smith, INRI: diff yesterdays file against todays, pipe the output thru sort (960222).
# More (960227) from Doug Safley (SAIC) and Gerard Donlon (BBN).  Suggested using awk to rearrange the fields
#   in the diff'd output, then sort, then put the fields back.  Great ideas - worked out very nicely.
#
# Another thought to keep in mind:  The diff output will not (yet?) look as desired when a "directory" name
#   changes.  For instance, when the example dir "/proj-work" (with substructure) is renamed to "/proj-work.old"
#   the diff process will show "D" deleted records for the original directory and substructure along with
#   subsequent "A" added records for the area that was moved to.  Even though the structure of files and dir's
#   below the renamed point actually didn't change (or maybe slightly).  Makes it difficult to compare changes.
#   But this is the correct (default) processing.

     # More test variables...
     #   setenv nice  "-3"
     #   setenv Srvr  `hostname` 
     #   setenv ProdS "/sysadmin/zlister.bin"
     #   setenv PROD  "/sysadmin/zhostlists"
     #   setenv Crnt  "960518.1040"
     #   setenv IT    "960707.1857"
     #   setenv tmp   "/tmp/zlister.$IT"

echo " "
echo " diff($diff) Pre.diff                 Point(5.0)  `date`, $Srvr."
if ( $diff == "YES" ) then
     # Must take into consideration the HP side (possibly linux as well) when sorting (may have to use alias?).
     echo "Comparing previous output file (Yesterdays) with Todays via awk process."
     # Uncompress yesterdays production file for comparision.  Protect for possible BSD 12-filename problem/limit.
     if ( -e $tmp/Yesterday.File.$Srvr.$Crnt.preserve ) then
          echo "Utilizing preserve copy."
          /bin/cp -p $tmp/Yesterday.File.$Srvr.$Crnt.preserve $tmp/Yesterday.File.$Srvr.$Crnt
     else
          echo "cp -p $PROD/$Srvr/$Srvr.$Crnt.Z"
          echo "  to: $tmp/Yesterday.File.$Srvr.$Crnt.Z"
                cp -p $PROD/$Srvr/$Srvr.$Crnt.Z          $tmp/YDL.Z
          # Seems that utilizing the -v option causes output to standard error(?).  So, removed the argument.
          nice $nice uncompress $tmp/YDL.Z
          set Stat = $status
          if ( $Stat == 0 ) then
               mv    $tmp/YDL                                $tmp/Yesterday.File.$Srvr.$Crnt
          else
               echo "Mission Control, we have a problem...."
               echo "Uncompressing yesterdays file was NOT successful."
               echo "diff processing bypassed.  Moving on."
               set diff = "NO"
               goto AfterDF
          endif
          if ( $test == "YES" ) then
               cp -p $tmp/Yesterday.File.$Srvr.$Crnt    $tmp/Yesterday.File.$Srvr.$Crnt.preserve
          endif
     endif

     #***********************************************
     # Check awk limitations pg 263 SED & AWK book. * Still to be done.
     #***********************************************
     echo " "
     ls -la $tmp
     echo " "

     # Strip off all junk above the "---[Begin Server File System Listing]---" line from yesterdays file
     #  and the blank line after this text.
     echo " "

     echo "                                      Point(5.1)  `date`, $Srvr."
     echo "Stripping off extra, unnecessary info from previous file"

     # Compute this based on the # of lines in the current execution's header file + (maybe) 30 lines for fudging...?
     # set i = 250
     set z = `cat $tmp/$Srvr.$IT | wc -l | tr -d ' '`
     @ i = $z + 30
     echo "z($z), i($i)";echo " ";unset z

     #####################
     ####  TEST THIS  ####
     #####################
     # DUH... Can greatly simplify this by using "grep -n pattern filename | head -1" to get the desired line number.

     DfLbl1:
     # Seems that simply tail'ing a large # of lines backward from the end of a file doesn't work correctly under Solaris 2.3.
     # Send output to dev/null cause we don't want to see it; just get the status of searching for the pattern.
     head -$i $tmp/Yesterday.File.$Srvr.$Crnt | tail -1 | grep 'Begin Server File System Listing' > /dev/null
     set Stat = $status
     if ( $Stat == 1 ) then
          # echo "i($i)."
          @ i--
          if ( $i == 0 ) then
               # Could set up nested if's checking for first 250 then add 25 then add 25.....
               echo "Exiting, didn't find desired header pattern in source"
               echo "file (Yesterday.File.$Srvr.$Crnt)."
               echo "Need to increase 'i' just above the (DfLbl1) label."
               exit 999
          else
               # echo "i($i).";echo " "
               goto DfLbl1
          endif
     else
          # Found match
          # set echo
          # echo "Found match: i($i)."
          # Add two to start on the proper line.
          @ i++; @ i++
          tail +$i $tmp/Yesterday.File.$Srvr.$Crnt > $tmp/Yesterday.File.$Srvr.$Crnt.1
          set c1 = `cat $tmp/Yesterday.File.$Srvr.$Crnt.1 | wc -l | tr -d ' '`
          echo "Removed ($i)-1 header lines, leaving        $c1"
     endif

     # Remove the last two lines from the file as well.  If the zlister.awk.ls-laR script changes, so may ($i).
     set i = 2
     @ i = $c1 - $i
     head -$i $tmp/Yesterday.File.$Srvr.$Crnt.1    >  $tmp/Yesterday.File.$Srvr.$Crnt.2
     if ( $test == "YES" ) then
          # Keep the input files
          echo "Keeping the  $tmp/Yesterday.File.$Srvr.$Crnt.1  file."
     else
          rm $tmp/Yesterday.File.$Srvr.$Crnt.1
          echo "Removed the $tmp/Yesterday.File.$Srvr.$Crnt.1  file."
     endif
     echo " "

     echo " diff'ing                             Point(5.2)  `date`, $Srvr."
     #                 Yesterdays file,                    Todays file,              diff output/awk input
     nice $nice diff   $tmp/Yesterday.File.$Srvr.$Crnt.2   $tmp/Today.awk.out.$IT  > $tmp/$Srvr.$IT.diff1
     if ( $test == "YES" ) then
          # Keep the input file
          echo "Keeping the  $tmp/Yesterday.File.$Srvr.$Crnt.2  file."
     else
          rm $tmp/Yesterday.File.$Srvr.$Crnt.2
          echo "Removed the  $tmp/Yesterday.File.$Srvr.$Crnt.2  file."
     endif
     echo " "

     echo " remove /proc & our temp files.       Point(5.3)  `date`, $Srvr."
     # Chose to do this here after the diff, instead of performing this two times on subsequent input files.
     # Added "| grep -v $IT" to eliminate references to this execution run.
     echo "Removing entries for /proc (kmem)."
     cat  $tmp/$Srvr.$IT.diff1 | grep -v " \/proc\/" | grep -v $IT >  $tmp/$Srvr.$IT.diff2
     # Elimination of /proc was desirable on Solaris and Linux because it is a representation of the system memory.
     #   This might not be desirable on your host if "/proc" has nothing to do with system memory.

     if ( $test == "YES" ) then
          # Keep the input file
          echo "Keeping the  $tmp/$Srvr.$IT.diff1  file."
     else
          rm $tmp/$Srvr.$IT.diff1
          echo "Removed the  $tmp/$Srvr.$IT.diff1  file."
     endif

     # This would be the place to implement custom removal's of records you are absolutely positive you don't want
     #   to see in the resulting diff output.  Be damn sure you are aware of what you are getting rid of.
     #   KNOW YOUR DATA!
     # Suggest reading "$tmp/$Srvr.$IT.diff2 as your input and write to "$tmp/$Srvr.$IT.diff2a",
     # then to "$tmp/$Srvr.$IT.diff2b", etc.  Ensure the next two occurances of "$tmp/$Srvr.$IT.diff2"
     # are changed to "$tmp/$Srvr.$IT.diff2" AND whatever is the last letter you used.
     echo " "

     echo " zlister.awk.diff.PostProc            Point(5.4)  `date`, $Srvr."
     echo " Pre-sort awk"
     #                       awk script to execute              diff output                    awk output/sort input
     echo "nice $nice awk -f $ProdS/zlister.awk.diff.PostProc   OutFile=$tmp/$Srvr.$IT.diff3   $tmp/$Srvr.$IT.diff2"
           # This rm is purposeful and helpful when manually executing (especially under test mode).
           rm -rf $tmp/$Srvr.$IT.diff3 >& /dev/null
           nice $nice awk -f $ProdS/zlister.awk.diff.PostProc   OutFile=$tmp/$Srvr.$IT.diff3   $tmp/$Srvr.$IT.diff2
     if ( $test == "YES" ) then
          # Keep the input file
          echo "Keeping the  $tmp/$Srvr.$IT.diff2  file."
     else
          rm $tmp/$Srvr.$IT.diff2
          echo "Removed the  $tmp/$Srvr.$IT.diff2  file."
     endif
     echo " "

     echo " sort'ing                             Point(5.5)  `date`, $Srvr."
     # sort the file on fields zero, one and two, then use awk script to generate report.
     #                           awk input               sort output (input to next awk script)
     echo "nice $nice sort +0 -3 $tmp/$Srvr.$IT.diff3  > $tmp/$Srvr.$IT.diff4"
           nice $nice sort +0 -3 $tmp/$Srvr.$IT.diff3  > $tmp/$Srvr.$IT.diff4
     if ( $test == "YES" ) then
          # Keep the input file
          echo "Keeping the  $tmp/$Srvr.$IT.diff3  file."
     else
          rm $tmp/$Srvr.$IT.diff3
          echo "Removed the  $tmp/$Srvr.$IT.diff3  file."
     endif
     echo " "


     #*************************************************[label]*********************************************************
                                                      bypassDIFF:
     #*****************************************************************************************************************

     echo " zlister.awk.sort.PostProc            Point(5.6)  `date`, $Srvr."
     # echo " Using 1.1 version that eliminates /. and /.. records (when nothing else is different about the record)."
     echo " Using new 1.2 version that eliminates records where time changed to year (as only change on the record)."
     echo " Post-sort awk"
     echo " "
     rm -f $tmp/$Srvr.$IT.diff5
     #   Reorder fields into proper display order and then write output.
     #     rm diff5; awk -f /sysadmin/zlister.bin/zlister.awk.sort.PostProc           OutFile=diff5   diff4

     #                       Script to execute                 Formatted diff output          Input from sort
     echo "nice $nice awk -f $ProdS/zlister.awk.sort.PostProc  OutFile=$tmp/$Srvr.$IT.diff5   $tmp/$Srvr.$IT.diff4"
           nice $nice awk -f $ProdS/zlister.awk.sort.PostProc  OutFile=$tmp/$Srvr.$IT.diff5   $tmp/$Srvr.$IT.diff4
     set Stat = $status
     if ( $Stat != 0 ) then
          echo "*************************************************************"
          echo "**  zlister.awk.sort.PostProc did not gracefully complete  **"
          echo "**  its processing.  Exiting...                            **"
          echo "*************************************************************"
          echo " "
          exit $bad
     endif
     if ( $test == "YES" ) then
          # Keep the input file(s)
          echo "Keeping the  $tmp/$Srvr.$IT.diff4  and $tmp/$Srvr.$IT.diff5  files."
          cp -p $tmp/$Srvr.$IT.diff5 $tmp/$Srvr.$IT.diff
     else
          rm $tmp/$Srvr.$IT.diff4
          mv $tmp/$Srvr.$IT.diff5 $tmp/$Srvr.$IT.diff
          echo "Removed the  $tmp/$Srvr.$IT.diff4  and $tmp/$Srvr.$IT.diff5  files."
     endif
     echo " "

     echo " "
     ls -la $tmp
     echo " --- diff process output is $tmp/$Srvr.$IT.diff  --- `date`."
     # echo "Since we still haven't completed all the diff stuff, EXIT."
     # exit 999
else
     echo "No diff processing today."
endif
echo " "

AfterDF:
echo "   test($test) Post.diff              Point(5.7)  `date`, $Srvr."
echo "---[Begin Server File System Listing]---"  | tee -a $tmp/$Srvr.$IT
     cat $tmp/Today.awk.out.$IT                  >>       $tmp/$Srvr.$IT
echo " "


# ******************************************************************************
# * 6.0  Perform data compression and move final files into production.        *
# ******************************************************************************
echo "                                      Point(6.0)  `date`, $Srvr."

# Preserve an uncompressed version temporarily.
# Funky compress process required on non-BSD systems to get around 12-char filename limit.
cp -p $tmp/$Srvr.$IT $tmp/zl
ls -la $tmp/zl
nice $nice compress $tmp/zl
echo " "

if ( ! -e $tmp/zl.Z ) then
     echo "Mission Control:  We have a problem."
     echo "For whatever reason (you need to investigate) the"
     echo "$tmp/$Srvr.$IT was not compressed."
     echo "Exiting, to alloy you to investigate..."
     echo " "
     /bin/ls -la $tmp
     echo " "
     exit $bad
else
     # We don't have to move (should only copy) the following file as
     #   it will be naturally purged with its parent directory.
     # Check on/for compression will be removed when process is perfected.
     echo "Compression status looks good."
     ls -la $tmp/zl.Z
     cp -p $tmp/zl.Z $tmp/$Srvr.$IT.Z
     echo "Final production file is: $tmp/$Srvr.$IT.Z"
endif

if ( $diff == "YES" ) then
     /bin/ls -la $tmp/$Srvr.$IT.diff
     /bin/cp -p  $tmp/$Srvr.$IT.diff $tmp/zld
     nice $nice compress             $tmp/zld
     # Add logic to check for proper compression here as well.
     /bin/ls -la                     $tmp/zld.Z
     /bin/cp -p $tmp/zld.Z $tmp/$Srvr.$IT.diff.Z
endif
echo " --- compression is complete --- `date`."
echo " "

echo "                                      Point(6.1)  `date`, $Srvr."
echo "Now we begin moving the files to their live home"
echo "    -- (If remote, this piece will involve NFS/automountd) --"
if ( $test == "YES" ) then
     # if we are testing don't add file to live area.
     echo "............  except we can't; it's a test."
     echo "So, we are just moving on.  $tmp is still avail for reference."
     echo "Production file is currently at:  $tmp/$Srvr.$IT.Z"
else
     echo "Not testing, moving: $tmp/$Srvr.$IT.Z"
     echo "                 to: $PROD/$Srvr/$Srvr.$IT.Z"
     echo " "
     mv $tmp/$Srvr.$IT.Z       $PROD/$Srvr
     if ( -e $tmp/$Srvr.$IT.errors ) then
          echo "Moving the listing of filesystem listing generation errors, as well."
          echo "Production error file is: $PROD/$Srvr/$Srvr.$IT.errors"
          # Look into compressing the error file first (remember to support BSD).
          /bin/cp -p $tmp/$Srvr.$IT.errors  $PROD/$Srvr
     endif

     # Check for moving the diff'd file will be still take place since the flag will be set properly
     #   based on the existance of previous data.
     if ( $diff == "YES" && -e $tmp/$Srvr.$IT.diff.Z ) then
          echo "Moving diff'd output to production directory as well."
          echo "Production diff file is: $PROD/$Srvr/$Srvr.$IT.diff.Z"
          # Add logic here to mv/cp the file based on $TEST
          /bin/cp -p $tmp/$Srvr.$IT.diff.Z  $PROD/$Srvr
     endif
endif
echo " "

# Ensure Current file gets updated.
echo "                                      Point(6.2)  `date`, $Srvr."
if ( $test == "YES" ) then
     # If we are testing, we don't want to update it.
     echo "Testing; won't update Current."
else
     echo "Since we moved the data already, and we're NOT testing, Current will be updated with '$IT'."
     echo $IT > $PROD/$Srvr/Current

     # Apply post-production logic to assist in 'sagrep' processing.
     # Follow conventions outlined near top of this script for 'Current' file structure and build that output here.
     # Layout spacing so that each server name is spaced out for 8 characters and a blank.
     # Line#2: named list (VH) of all servers data is avail for (Auto update this for all other servers).
     # [*** FIX ***] to add proper number of spaces after each one (for sagrep) processing; allow for "yymmdd.hhmm  " size.
     # Line2 - EOF:  list of files available for selection, via sagrep.
     # This list is only accurate as long as no one deletes a file identified by the list since it was generated.
     echo "And a list of available files.  Line2 - EOF: will contain..."
     ls -1 $PROD/$Srvr | grep -v error | grep $Srvr | sed 's/$Srvr//' | sed 's/.Z$//' | tee -a $PROD/$Srvr/Current
     echo " "                                                                         | tee -a $PROD/$Srvr/Current
endif

# Removing $tmp (/tmp/zlister.$IT)
if ( $deltmp == "YES" ) then
     echo "This is a production run, NOT a test; therefore REMOVING ($tmp)."
     rm -rf $tmp
else
     echo "deltmp is not set; therefore NOT removing ($tmp)."
endif
echo " "

echo "                                      Point(6.3)  `date`, $Srvr."
if ( $test != "YES" ) then
     if ( -e $ProdS/zlister.stats ) then
          echo "Performing secondary data collection."
            $ProdS/zlister.stats
          # else $ProdS/zlister.stats.daily
          #      $ProdS/zlister.stats.hourly
     endif
else
     echo "Testing; secondary data collection bypassed."
endif
echo " "

echo "                                      Point(6.4)  `date`, $Srvr."
echo " "

#
# Logic may need to be modified to support Automountd.
#


# ******************************************************************************
# * 7.0  Ensure file/directory permissions are correct.                        *
# ******************************************************************************
# If /sysadmin ($PTWD) is mounted (from NFS/automountd), then don't change permissions/owner/group.
#   Is this supportive of a directory name of the owners choice being mounted in a different place?
#   What if /sysadmin is a link to another part of the file system.  Will the recursive changes take effect?

# Only reason to do the next line is IF the Automountd is being used.
echo "                                      Point(7.0)  `date`, $Srvr."
ls -la $PTWD/$PTWD2 >& /tmp/zlister.junk.junk;rm /tmp/zlister.junk.junk

set MNT_CHK=`mount | grep ":/" | grep $PTWD`
# 0=mounted/executing remotely
# 1=mounted/executing locally
set Stat=$status
# echo "MNT_CHK($MNT_CHK)."
if ( $Stat == 1 ) then
     if ( $test == "NO" ) then
          # We are executing on the source server; enforce correct permissions.
          echo "Chog; local to server with the data."
          echo "(30), owner($owner), group($group), perms($perms), PTWD/PTWD2($PTWD/$PTWD2)."
                    nice $nice chown -R $owner $PTWD/$PTWD2  &
          (sleep 30;nice $nice chgrp -R $group $PTWD/$PTWD2) &
          (sleep 31;nice $nice chmod -R $perms $PTWD/$PTWD2) &
          if ( $PTWD == "/sysadmin" ) then
               # Production environment
               set Start='/sysadmin'
          else
               # Continuing to provide support if testing/installing for the first time.
               set Start='/tmp/sysadmin'
          endif
          chown $owner $Start/zlister.bin/*
          chgrp $group $Start/zlister.bin/*
          chmod 755    $Start/zlister.bin/zl*
          chmod 644    $Start/zlister.bin/*awk*  $Start/zlister.bin/*lsm
          (sleep 60;find $Start -type d -exec chmod 755 {} \; ) &
     else
          echo "Testing; NO chog performed."
     endif
else
     echo "We are on server where $PTWD is remotely mounted, so no change of permissions/owner/group."
     echo "Enforcement of correct permissions only takes place there."
endif
echo " "

echo "                                      Point(7.1)  `date`, $Srvr."
echo "Post run sync(s)."
echo "bong";sync
echo "bang";sync
echo "bing";sync

# Insert logic to tar to tape & allow for removal of files for this server older than xx days.
#   By default, this will be off.

echo " "
echo " **************************************************************************************"
echo " **************************************************************************************"
echo " *****  Please send me any enhancements you have made to this package.  Not only  *****"
echo " *****  will I credit you with the changes, and mail to you the improved version  *****"
echo " *****  but your efforts will improve this zlister project for everyone else.     *****"
echo " *****                 Thank you for your time (Joe Wulf).                        *****"
echo " *****                          DP1 Joe Wulf                                      *****"
echo " *****                          USNS Spica, (T-AFS 9)                             *****"
echo " *****                          FPO AP 96678-4066                                 *****"
echo " *****                          United States of America                          *****"
echo " **************************************************************************************"
echo " **************************************************************************************"
sync;sync;sync
echo " "
echo " "
echo "                    $date1"
echo "                    Completed at: `date`, $Srvr."
echo "*--------------------------------------------------------------------------------------*"
echo "|  zlister (Version $zlister_version)            Completed  `date`, `hostname`$Space"
echo "*--------------------------------------------------------------------------------------*"
echo " "

set path = "$prot_path"
if ( $test == "NO" ) then
     echo "."
     unsetenv date1 PROD ProdS Crnt Srvr IT tmp PNW NUM UWMP test bad NFSMNT NFSMNTP PTWD PTWD2 IAM orig origtest
     unsetenv nice owner group perms diff prot_path Space
else
     echo "Variables are still set for current shell testing."
endif
exit 0
