#!/usr/bin/perl

use strict;
use warnings;
use DBI;

# $Id: fat.pl 134 2008-05-01 22:23:36Z ed $
# $URL: svn+ssh://fw/repos/code/perl/fat/fat.pl $
#
# I wrote this while waiting for someone to come online
#
# CREATE TABLE file( file_id integer not null primary key autoincrement, file_name varchar(9000) not null, file_path varchar(9000) not null, file_size integer not null default 0, file_type integer not null default 0, file_parent integer not null default 0 );
# CREATE INDEX file_name_idx on file ( file_name );
# CREATE INDEX file_parent_idx on file( file_parent );
# CREATE INDEX file_path_idx on file ( file_path );
# CREATE INDEX file_type_idx on file( file_type );


my %config;

sub set_config {
	my $name = `hostname`;
	chomp( $name );
	open( F, $name ) or die( "could not open $name: $!" );
	while( my $l = <F> ) {
		chomp( $l );
		next if $l =~ /^#/;
		$l =~ s/#.*//g;
		if( $l =~ /^(.*?)\s*=\s*(.*?)$/ ) {
			$config{$1} = $2;
		}
	}
	close(F);

	$config{'dbh'} = DBI->connect("dbi:SQLite:dbname=fat.sqlite", "", "", { AutoCommit => 0 } )
		or die( "Could not connect to db: $!" );

	$config{'sth'} = $config{'dbh'}->prepare( "INSERT into file ( file_name, file_path, file_size, file_type, file_parent ) values ( ?, ?, ?, ?, ? );" );
	
}

sub insert {
	my $file = shift;
	my $parent = shift;
	my $type = shift;

	my $full = $file;

	my @s = stat( $full ) or
		die( "cannot stat: $!" );

	if( $file =~ m#^(.*)\/(.*)# ) {
		$full = $file;
		$file = $2;
	}
	
	$config{'sth'}->execute( $file, $full, $s[7], $type, $parent );

	return( $config{'dbh'}->last_insert_id( undef, undef, "file", undef ) );
}

sub process_dir {
	my $d = shift;
	my $pid = shift;

	my (@arr, @dirs );

	opendir( D, $d )
		or return;

	foreach( readdir( D ) ) {
		next if( $_ eq "." || $_ eq ".." );
		push( @arr, $d . "/" . $_ ) if( -f "$d/$_" );
		push( @dirs, $d . "/" . $_ ) if( -d "$d/$_" );
	}
	closedir( D );

	foreach( @arr ) {
		#my @s = lstat( $_ );
		#print( sprintf( "File mode: %0o\n", $s[2] >> 8 ) );
		insert( $_, $pid, "0" );
	}

	foreach( @dirs ) {
		print( "Doing $_\n" );

		my @s = lstat( $_ );
		next if( $s[2] >> 8 == 0241 );
		#print( sprintf( "File mode: %od\n", $s[2] ) );

		my $dir_id = insert( $_, $pid, "1" );
		process_dir( $_, $dir_id );
	}
	$config{'dbh'}->commit;
}

sub main {
	my $start = "/home/ed";

	my $dir = insert( $start, "0", "1" );
	process_dir( $start, $dir  );
}

set_config();
main();

