#!/usr/bin/perl
use strict 'vars';

my @PRUNE = ();
my $ROOT = '/';
my $DEF_OUTPUT = '/var/lib/slocate/FILES';
my $OUTPUT = $DEF_OUTPUT;

while ($ARGV[0] =~ /^-/) {
  if ($ARGV[0] =~ /^--([^=]*)=(.*)/) {
    if ($1 eq 'prunepaths') {
      push @PRUNE, split(/ /, $2);
    } elsif ($1 eq 'root') {
      $ROOT = $2;
    } elsif ($1 eq 'output') {
      $OUTPUT = $2;
    } else {
      warn "$0: Unknown long option --$1\n";
      usage();
    }
  } elsif ($ARGV[0] =~ /^-(.)/) {
    if ($1 eq 'p') {
      push @PRUNE, $ARGV[1];
      shift;
    } elsif ($1 eq 'r') {
      $ROOT = $ARGV[1];
      shift;
    } elsif ($1 eq 'o') {
      $OUTPUT = $ARGV[1];
      shift;
    } else {
      warn "$0: Unknown option -$1\n";
      usage();
    }
  } else {
    die "Can't happen! ($ARGV[0])\n";
  }
  shift;
}
usage() if @ARGV;

my @COMMAND =  ('find', $ROOT);
push @COMMAND, ('-path', $_, '-prune', '-o' ) for @PRUNE;
push @COMMAND, '-print';

open F, "> $OUTPUT" or die "$0: Couldn't open database file $OUTPUT: $!\n";
open STDOUT, ">&F" or die "$0: Couldn't dup to stdout: $!\n";
open SAVESTDERR, ">&STDERR" or die "$0: Couldn't dup to stderr: $!\n";
open STDERR, "> /dev/null" or die "$0: Couldn't discard stderr: $!\n";
close F;

exec @COMMAND;
print SAVESTDERR "$0: Couldn't run 'find' command:\n\t@COMMAND\n\t$!\n"; 
exit 1;

sub usage {
  print <<EOM;
$0 [-p path] [-r rootdir]
  -p   --prunepath   Ignore files on this path
  -r   --root        Start at this directory (default /)
  -o   --output      Deliver output to this file (default $DEF_OUTPUT)
EOM
    exit 1;
}
