package SI::grub;

use if $ENV{DEBUG} ~~ /grub|all/ => "Smart::Comments";
use strict;
use warnings;
use File::Temp qw(tempdir);
use IO::File;

use SI::tools;

sub restore(\%) {
    my $devs = shift;

    # assume the first ext is the boot device (should have
    # been labeled

    my ($boot, undef) = grep { $devs->{volume}{$_}{type} =~ /^ext/ }
    grep { $devs->{volume}{$_}{origin} eq "ptable" }
    grep { defined $devs->{volume}{$_}{type} } 
    sort keys %{$devs->{volume}};

    # now find the partition containing the fstab, it should
    # be the root file system
    my $tmpdir = tempdir(CLEANUP => 0);

    my @fs = 
	grep { $devs->{volume}{$_}{type} =~ /^ext/ }
	grep { defined $devs->{volume}{$_}{type} }
	keys %{$devs->{volume}};


    my @mounted;
    eval {
    
	foreach (@fs) {
	    run("mount -oro -t $devs->{volume}{$_}{type} $_ $tmpdir");
	    last if -f "$tmpdir/etc/fstab";
	    run("umount $tmpdir");
	    push @mounted, $tmpdir;
	}

	# and now try to mount the rest


	my $fstab = new IO::File "$tmpdir/etc/fstab";
	foreach (grep { /^\// } <$fstab>) {
	    my ($dev, $mp, $type, $options, undef) = split;
	    next if $options =~ /noauto/
		or $mp eq "/"
		or $mp !~ /^\//;
	    run("mount -t $type $dev $tmpdir/$mp");
	    push @mounted, "$tmpdir/$mp";
	}
	close($fstab);

	run("mount -o bind /dev $tmpdir/dev");
	push @mounted, "$tmpdir/dev";

	run("chroot $tmpdir grub-mkdevicemap");
	run("chroot $tmpdir /usr/sbin/grub-install '(hd0)'");
	system("/bin/bash --login")
		if $ENV{_SHELL};
    };
    if ($@) {
	warn "** EVAL: $@\n";
    }
    map { system("umount $_") } reverse @mounted;
    rmdir($tmpdir);

}

1;
# vim:sts=4 sw=4 aw ai sm:
