sort out DB new interface; search in parent dirs for .id3fs
[id3fs.git] / lib / ID3FS / DB.pm
index 5f08a04..f457905 100644 (file)
@@ -17,20 +17,17 @@ sub new
     bless($self,$class);
 
     $self->{me}=shift;
-    $self->{dbpath}=shift;
+    $self->{verbose}=shift;
+    my $init=shift;
+    my $dbpath=shift;
     $self->{base}=shift;
-    $self->{fallbackdir}=shift;
+    my $fallbackdir=shift;
 
-    if(!defined($self->{base}) &&
-       defined($self->{fallbackdir}) &&
-       -d $self->{fallbackdir})
-    {
-       $self->{base}=$self->{fallbackdir};
-    }
-    $self->{dbpath}="$self->{base}/$dbfile" unless(defined($self->{dbpath}));
+    $dbpath=$self->find_db($init, $dbpath, $fallbackdir);
+    return undef unless($dbpath);
     $self->{absbase}=Cwd::abs_path($self->{base});
 
-    my $connectstr="dbi:SQLite:dbname=$self->{dbpath}";
+    my $connectstr="dbi:SQLite:dbname=$dbpath";
     my ($user, $pass)=("", "");
     if($self->{postgres})
     {
@@ -38,7 +35,7 @@ sub new
        $user="ianb";
        $pass="foo";
     }
-    my $exists=-f $self->{dbpath};
+    my $exists=-f $dbpath;
     $self->{dbh}=DBI->connect($connectstr, $user, $pass,
                              { AutoCommit=>1 } );
     unless(defined($self->{dbh}))
@@ -58,6 +55,45 @@ sub new
     return $self;
 }
 
+sub find_db
+{
+    my($self, $init, $dbpath, $fallbackdir)=@_;
+    my $file=undef;
+    my $base=undef;
+    if(defined($dbpath))
+    {
+       $file=$dbpath;
+    }
+    if(defined ($self->{base}))
+    {
+       $file="$self->{base}/$dbfile" unless defined($file);
+       $base=$self->{base};
+    }
+    elsif(defined($fallbackdir) && -d $fallbackdir)
+    {
+       my $path=Cwd::abs_path($fallbackdir);
+       do
+       {
+           $file="$path/$dbfile";
+           $base=$path;
+           $path=~s/(.*)\/.*/$1/;
+       }
+       while(! -f $file && length($path) && -d $path);
+       if(! -f $file)
+       {
+           $file="$fallbackdir/$dbfile";
+           $base=$fallbackdir;
+       }
+    }
+    if(!-f $file && !$init)
+    {
+       print "$self->{me}: db not found at $file\n";
+       return undef;
+    }
+    $self->{base}=$base;
+    return $file;
+}
+
 sub create
 {
     my($self,$name)=@_;