#!/usr/bin/env perl

# Use mandatory external modules
use strict;
use Cwd;
use File::Basename;
use Data::Dumper;
use POSIX;
use Config;
use Time::HiRes;
use DBI;

# Determine installation dir name
our $SELF_DIR = dirname(dirname(dirname(Cwd::abs_path(__FILE__))));

# Include parts of the system
require $SELF_DIR . '/lib/config.pm';
require $SELF_DIR . '/lib/log.pm';

# Read config file and status
our $config = ReadConfig("mmm_lvm.conf");

my $res = RemoveLvmSnapshot();

print "$res\n";
exit(0);

#-----------------------------------------------------------------
sub RemoveLvmSnapshot() {
    my $this = $config->{this};
    my $host = $config->{host}->{$this};
    if (!$host) {
        return "ERROR: Invalid 'this' value: '$this'!";
    }

    return RemoveSnapshot();
}

#-----------------------------------------------------------------
sub RemoveSnapshot() {
    my $this = $config->{this};
    my $host = $config->{host}->{$this};

    # Unmount snapshot
    my $res = system("umount", $host->{lvm_mount_dir});
    if ($res) {
        return "ERROR: Can't umount snapshot: $!";
    }

    my @command = ($config->{bin_lvremove}, '-f', "/dev/" . $host->{lvm_volume_group} . "/mmm_snapshot");
    my $lvm_res = system(@command);
    print "LVM res = '$lvm_res'\n";
    
    if ($lvm_res) {
        return  "ERROR: Can't remove snapshot: $!";
    }
    
    return "OK: Snapshot removed!";
}
