#!/usr/bin/perl -w
#
# Copyright (c) 2000-2013 University of Utah and the Flux Group.
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
#
use English;
use Getopt::Std;
use strict;

# Drag in path stuff so we can find emulab stuff.
BEGIN { require "/etc/emulab/paths.pm"; import emulabpaths; }

my $IMAGEZIP    = "$LBINDIR/imagezip";
my $IMAGEUNZIP  = "$LBINDIR/imageunzip";

#
# Create a disk image cache.
#
sub usage()
{
    print STDERR "Usage: mkimagecache [-c | -t count] [-s size] <imagename>\n";
    print STDERR "       mkimagecache -r <imagename>\n";
    print STDERR "options:\n";
    print STDERR "  -c count  - Create count\n";
    print STDERR "  -t count  - Create as many as needed to reach count\n";
    print STDERR "  -s size   - Size of lvm in GB; overrides base lvm\n";
    print STDERR "  -r        - Remove all cached images\n";
    exit(-1);
}
my $optlist = "c:s:t:r";
my $count   = 1;
my $total   = 0;
my $size    = 0;
my $clear   = 0;

#
# Turn off line buffering on output
#
$| = 1;

# Need this for predicates.
use libsetup;
use libutil;
use libtestbed;
use libvnode_xen;

my $VGNAME = libvnode_xen::VGNAME();

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (@ARGV != 1) {
    usage();
}
if (defined($options{"c"})) {
    $count = $options{"c"};
}
if (defined($options{"t"})) {
    $count = $total = $options{"t"};
}
if (defined($options{"s"})) {
    $size = $options{"s"};
}
if (defined($options{"r"})) {
    $clear = 1;
}
my $imagename     = $ARGV[0];
# See libvnode_xen ...
my $imagelockname = "xenimage.$imagename";
my $imagelvmname  = "image+" . $imagename;
my $imagelvmpath  = libvnode_xen::lvmVolumePath($imagelvmname);

if ((my $locked = TBScriptLock($imagelockname,
			       TBSCRIPTLOCK_GLOBALWAIT(), 1800))
    != TBSCRIPTLOCK_OKAY()) {
    die("Could not get the $imagelockname lock after a long time!\n");
}

#
# Look for existing cache files.
#
my @files = glob("/dev/$VGNAME/_C_${imagename}_*");
my $idx   = 0;

#
# Delete all existing cache files.
#
if ($clear) {
    foreach my $file (@files) {
	system("lvremove -f $file");
	if ($?) {
	    TBScriptUnlock();
	    exit(1);
	}
    }
    TBScriptUnlock();
    exit(0);
}

#
# Base must exist.
#
if (! -e $imagelvmpath) {
    print STDERR "No base lvm exists for $imagename!\n";
    TBScriptUnlock();
    usage();
}

#
# Need the base size for copy.
#
my $lvsize;

if ($size) {
    $lvsize = "$size" . "G";
}
else {
    $lvsize = `lvs $imagelvmpath --noheadings -o lv_size`;
    if ($?) {
	TBScriptUnlock();
	die("Could not get lv size of $imagelvmpath\n");
    }
    chomp($lvsize);
}

while ($count > 0) {
    if (grep {$_ eq "/dev/$VGNAME/_C_${imagename}_${idx}"} @files) {
	$count--
	    if ($total);
	$idx++;
	next;
    }
    my $cachename = "_C_${imagename}_${idx}";
    my $cachefile = "/dev/$VGNAME/$cachename";
    my $imagemetadata;
    
    if (libvnode_xen::LoadImageMetadata($imagename, \$imagemetadata)) {
	print STDERR "Cannot load image metadata for $imagename\n";
	TBScriptUnlock();
	exit(1);
    }
    if (libvnode_xen::CreatePrimaryDisk("image+" . $imagename,
					$imagemetadata, $cachename, undef)) {
	mysystem2("lvremove -f $cachefile")
	    if (-e $cachefile);
	TBScriptUnlock();
	exit(1);
    }
    $idx++;
    $count--;
}
TBScriptUnlock();
exit(0);
