#!/bin/bash
#	File:		/usr/local/sbin/sanedisk
#
#	Name:		Disk Sanity Maintenance
#
#	Author:		David Norris <dave@webaugur.com>
#
#	Purpose:	Keep the filesystem organized and easily recoverable 
#			with a goal of FHS Compliance
#
#	Usage:		Run this script daily with cron and/or manually as needed.
#
#	References:	Filesystem Hierarchy Standard <http://www.pathname.com/fhs/>
#			BASH Reference <http://www.gnu.org/manual/bash/html_node/bashref_toc.html>
#
# Overview: 
#	1. Backup critical files: /etc*
#	2. FHS compliant: /usr/tmp/ -> /var/tmp
#	3. Link optional executables to /opt/bin
#	4. Flush stale files from persistent cache: /var/tmp, /var/cache
#

 # Backup critical system files

    tar --create --ignore-failed-read --owner=root --group=root --gzip --file=/var/cache/backup/etc.tar.gz --backup=numbered /etc* &> /dev/null

    # Delete Backups older than 7 days
    find /var/cache/backup/etc.tar.gz* -type f -mtime +7 -exec rm -f -- {} \;  &> /dev/null


 # FHS compliant Temporary Space

    # /usr should be read-only; Link writable files to /var.
    if [ ! -h /usr/tmp ]; then
      echo "FHS Warning: /usr/tmp is not a symlink to /var/tmp and I am fixing it."

      # If /usr/tmp is a directory then move contents to /var/tmp.
      if [ -d /usr/tmp ]; then
        echo "FHS Warning: I found a /usr/tmp directory and I am fixing it."
        mv /usr/tmp/* /var/tmp/ &> /dev/null
      fi

      # Remove /usr/tmp and replace it with a symlink 
      rm -Rf /usr/tmp
      ln -s /var/tmp /usr/tmp;
    fi


 # Link optional executables into /opt/bin
   # Add /opt/bin to your PATH environment to take advantage
   # You may want to manually copy or link executables to /opt/bin
   # This intentionally DOES NOT overwrite existing executables 
   #   in case you have your own versions.

    # Find and Link Optional executables to a public place.
    for i in `find /opt/*/bin -type f -perm 0755` ; do

      # Link files and send errors to null device
      ln -s $i /opt/bin/`basename $i` &> /dev/null
    done


 # Clean persistent User space
   # Note: /tmp is NOT persistent 
   #   You should execute 'rm -Rf /tmp/*' at boot time

    # Clean User Temp of anything older than 1 Week
    find /var/tmp -mtime +7 -exec rm -Rf -- {} \;  &> /dev/null

    # Clean User Cache of anything older than 4 Weeks
    find /var/cache -mtime +28 -exec rm -Rf -- {} \;  &> /dev/null


# Obligatory New Line follows
