#!/usr/bin/perl

# this script checks for all instances with a given prefix whether they
# actually exist and removes them from the database if they don't.
#
# this is mostly useful after part of a backup has been (intentionally
# or accidentally) deleted.

use warnings;
use strict;

use Simba::CA;

my $prefix_re = $ARGV[0];

unless ($prefix_re) {
    print STDERR "Usage: $0 prefix_re\n";
    exit(1);
}


my $ca = Simba::CA->new({
			    dbi_file => $ENV{SIMBA_DB_CONN} || "$ENV{HOME}/.dbi/simba",
			});

my $dbh = $ca->{dbh};

my $sessions
    = $dbh->selectall_arrayref(
        q{select * from sessions},
         { Slice => {} }
      );
$sessions = [ grep { $_->{prefix} =~ m/$prefix_re/ } @$sessions ];

for my $session (@$sessions) {
    my $instances
        = $dbh->selectall_arrayref(
            q{select i.id, f.path
              from instances i, files f
              where i.session=? and i.file=f.id
             },
             { Slice => {} },
             $session->{id}
          );

    for my $instance (@$instances) {
        my $backup_path = $session->{prefix} . '/' . $instance->{path};
        print "$backup_path\n";
        if (!lstat($backup_path)) {
            if ($!{ENOENT}) {
                # file doesn't exist, delete it
                $dbh->do(q{delete from instances where id=?}, {}, $instance->{id});
                print "\tdeleted\n";
            } else {
                die "unexpected error on $backup_path: $!";
            }
        }
    }
}

# remove orphaned records:
$sessions
    = $dbh->selectcol_arrayref(
        q{select s.id from instances i right outer join sessions s  on i.session=s.id where i.id is null}
      );

for my $session (@$sessions) {
    $dbh->do(q{delete from sessions where id=?}, {}, $session);
    print "session $session deleted\n";
}

my $files
    = $dbh->selectcol_arrayref(
        q{select f.id from instances i right outer join files f  on i.file=f.id where i.id is null}
      );

for my $file (@$files) {
    $dbh->do(q{delete from files where id=?}, {}, $file);
    print "file $file deleted\n";
}

my $versions
    = $dbh->selectcol_arrayref(
        q{select v.id from instances i right outer join versions2 v  on i.version=v.id where i.id is null}
      );

for my $version (@$versions) {
    $dbh->do(q{delete from versions2 where id=?}, {}, $version);
    print "version $version deleted\n";
}