#!/usr/bin/perl -w
#
# $Id$
# Copyright B. Cornec 2005-2014
# Provided under the GPL v2
#
# Get the complete network configuration of the system
#
use strict 'vars';
use ProjectBuilder::Base;
use ProjectBuilder::Version;
use Data::Dumper;
use Getopt::Long qw(:config auto_abbrev no_ignore_case);
use English;


=pod

=head1 NAME

mr-label labelling tool

=head1 DESCRIPTION

mr-label labels VFAT devices or files representing VFAT devices

=head1 SYNOPSIS

mr-label [-v][-h][-l label] device|file

=head1 ARGUMENTS

=over 4

=item B<device|file>

This is the VFAT device or file representing a VFAT device to modify with regards to its label

=back 

=head1 OPTIONS

=over 4

=item B<-v|--verbose>

Increase verbosity

=item B<-h|--help>

Print a brief help message and exits.

=item B<--man>

Prints the manual page and exits.

=item B<-l label> 

This is the new label to put on the VFAT filesystem

=back

=head1 WEB SITES

The main Web site of the project is available at L<http://www.mondorescue.org>. Bug reports should be filled using the trac instance of the project at L<http://trac.mondorescue.org/>.

=head1 USER MAILING LIST

For community exchanges around MondoRescue please use the list L<http://sourceforge.net/mailarchive/forum.php?forum_name=mondo-devel>

=head1 AUTHORS

The MondoRescue team lead by Bruno Cornec L<mailto:bruno@mondorescue.org>.

=head1 COPYRIGHT

MondoRescue is distributed under the GPL v2.0 license or later,
described in the file C<COPYING> included with the distribution.

=cut

# Global variables
my ($mrver,$mrrev) = pb_version_init();
my $appname = "mr-label";
my %opts;					# CLI Options

# Initialize the syntax string

pb_syntax_init("$appname Version $mrver-$mrrev\n");

GetOptions("help|?|h" => \$opts{'h'}, 
		"man" => \$opts{'man'},
		"verbose|v+" => \$opts{'v'},
		"label|l=s" => \$opts{'l'},
) || pb_syntax(-1,0);

if (defined $opts{'h'}) {
	pb_syntax(0,1);
}
if (defined $opts{'man'}) {
	pb_syntax(0,2);
}
if (defined $opts{'v'}) {
	$pbdebug++;
}
pb_log_init($pbdebug, $pbLOG);
pb_temp_init($pbdebug);

my $label=$opts{'l'};
die "Unable no label defined, use -l label" if (not defined $label);

my $inputf  = $ARGV[0];
die "$0: no input file defined" if (not defined $inputf);

my($inputfh, $buffer);
open($inputfh,  "+< $inputf") || die "$0: cannot open $inputf for reading/writing: $!";
binmode($inputfh) || die "binmode failed: $!";

# 42 first bytes are untouched
if (! seek($inputfh, 43,0)) {
	die "Unable to seek $inputf: $!";
}

# Label is then the 11 following bytes
my $size = read($inputfh, $buffer, 11);
if ($size != 11) {
	die "Unable to read existing label: $!";
}
pb_log(1,"Previous label was ***$buffer***\n");
my $hexlabel=sprintf("%-11s", uc($label));
pb_log(1,"New label is ***$hexlabel***\n");
# Go back
seek($inputfh, 43,0);
print $inputfh $hexlabel;
close($inputfh) || die "couldn't close $inputf: $!";
