#!/usr/bin/env perl


use strict;
use warnings;

# check user-id
my $username = getpwuid( $< );
if ($username ne 'root') {
	print "You have to be root!\n";
	&printHelp(2);
}

# parse command line arguments
my ($isofile, $devdisk) = @ARGV;
if (scalar(@ARGV) < 2) {
	&printHelp(3);
}


# to make things easy
if ($devdisk =~ /^\\dev/) {
	print "Full disk path is given. Perfect\n";
} else {
	print "Destination disk is given without /dev. Adding it now\n";
	$devdisk = '/dev/' . $devdisk;
	print "Full destination path is: $devdisk\n";
}


print "Inventorizing possible mounts on destination disk\n";
my @mountedvolumes;
my @mountoutput = (`mount`);
my $diskregex = $devdisk . 's\d{1,2}';
#print "DiskRegex: $diskregex\n";
foreach my $mountline (@mountoutput) {
	chomp($mountline);
	if ($mountline =~ /($diskregex)/) {
		push(@mountedvolumes, $1);
	}
}

print "Unmounting volumes on destination disk\n";
foreach my $mountedvolume (@mountedvolumes) {
	print "Umounting volume: $mountedvolume\n";
	my $unmountcommand = "diskutil unmount $mountedvolume";
	system($unmountcommand);
	&checkCmdLineExitCode($unmountcommand, $?);

}



# making up output file name
my $outputfile = substr($isofile, 0, -4);
#print "Outputfile: $outputfile\n";

print "Making up HDIUtil-command\n";
my $hdiutilcommand = "/usr/bin/hdiutil convert -format UDRW -ov -o $outputfile $isofile";


print "Converting iso to raw image\n";
system($hdiutilcommand);
&checkCmdLineExitCode($hdiutilcommand, $?);



print "Making up DD-command\n";
my $ddcommand = "/opt/local/bin/gdd bs=1M status=progress if=$outputfile\.dmg of=$devdisk";
print "DD-command: $ddcommand\n";
system($ddcommand);


exit(0);


sub checkCmdLineExitCode {
	my ($command, $exitcode) = @_;
	if ($exitcode != 0) {
		print "Something executing '$command'. Exiting\n";
		exit($exitcode);
	}
}


sub printHelp {
	my ($errorlevel) = @_;
	print "Usage. : # $0 isofile disk\n";
	print "Example: # $0 /Users/krusjme/Downloads/kubuntu19.iso /dev/disk2\n";

	if (defined($errorlevel)) {
		if ($errorlevel > 0) {
			exit($errorlevel);
		}
	}
}