#! /bin/bash -e
# mkls-lR version 1.12 1998/03/19
# A GNU/bash script for FTP servers.
# See also manpage and README.ls-lR.

# Copyright 1998 Ian Maclaine-cross (ian@ilm.mech.unsw.edu.au)
# You may use this only under the conditions of the General Public
# License in file GPL.

sn="mkls-lR";
usage="echo -e \
Makes ls-lR.gz, ls-lR.patch.gz and ls-lR.times files on FTP servers\n\
Usage:\n\
$sn [-a] -d dirpath [-n basename] \"[-I path ...] [path ...]\"\n\t\
-a = make ls-lR also\n\t\
dirpath = default subdirectory where ls-lR files made\n\t\
basename = name of ls-lR files (default ls-lR)\n\t\
path = ls -lR pathname argument (quotes protect wildcards)\n\t\
-I = ignore this path\n\
Simple example: $sn -d /home/ftp/pub/debian\n";

# $lslR.$old is previous $lslR's name in $lslR.patch.gz.
old="old";

# Get the options.
all=false;
args=`echo $@ | tr ' ' '\012' | sed -n "/^-a*[dnI]\$/N;/^-[^ ]/p"`;
while getopts ad:n:I: option $args; do
  case "$option" in
  a) all=:;;
  d) home=$OPTARG;;
  n) lslR=$OPTARG;;
  I) ;;
  ?|:) $usage; exit;;
  esac;
done;

# If no dirpath exit.
if [ -z $home ]; then
  $usage;
  exit;
elif [ ! -d $home ]; then
  echo $sn: Directory $home does not exist!;
  exit;
fi;
cd $home;
home=$PWD;

lslR=${lslR:=ls-lR};

if test -d $lslR; then
  echo $sn: Argument for -n $lslR is a directory!;
  exit;
fi;

# $work is for temporary file expansion.
work="/tmp/.mk$lslR.$$";
if ! mkdir $work; then
  echo $sn: Could not make working directory $work!;
  exit;
fi;

function end(){
  cd $home; rm -rf $work; exit;
}

# Make $lslR.new
if ls -lR\
  `echo " $@" | sed "s/ -a\+ / /g;s/ -a*[dn] *[^ ]\+/ /g;s/ -a*I */ -I/g"`\
  >$work/$lslR.new; 
then cd $work; 
else end; fi;

# If $lslR different make $lslR.patch.gz
if cp $home/$lslR.gz . &>/dev/null; then
  gunzip -fN $lslR.gz;
  mv -f $lslR $lslR.$old;
  mv -f $lslR.new $lslR;
  if diff -u $lslR.$old $lslR >$lslR.patch; then end; fi;
  gzip -9cf $lslR.patch >$home/$lslR.patch.gz;
else
  mv -f $lslR.new $lslR;
  rm -f $home/$lslR.times;
fi;

# Make new $lslR.times
if test -r $home/$lslR.times;
then tail -n1 $home/$lslR.times >$lslR.times;
else echo 0 >$lslR.times; fi;
# Timezone correction for UTC is 0.
date +%s -d"`find $lslR -printf %t` UTC" >> $lslR.times;
mv -f $lslR.times $home/$lslR.times;

# Make new $lslR.gz and $lslR.
gzip -9cfN $lslR >$home/$lslR.gz;
if $all; then mv -f $lslR $home/$lslR; fi;

end;





