#!/usr/bin/perl

# CDRX.pl v.0.3.1
# Jason's CD-RW burning script
# 2002.01.19

use strict;

###################
# Global Variables
###################

my (%index_hash,
	$dev_type,
	$ref_label,
	$referrer,
	$referrer_check,
	$thing,
	$type,
	$target_dev,
	$target_label,
	$dev_choice,
	%speeds,
	$readdir,
	$writedir,
	$iso_name,
	%dev_array,
	$dir_Create_iso_referrer,
	%file_list,
	$new_read_dir,
	$new_write_dir,
	$burn_copy_cd_referrer,
	$burn_iso_cd_referrer,
	$burn_dir_cd_referrer,
	$burn_files_cd_referrer,
	$scsibus,
	$target,
	$lun,
	$dev_name,
	$index_num,
	%index_hash,
	$install_referrer,
	@scan,
	$cdrom_def,
	$cdrom_label,
	$cdrw_def,
	$cdrw_label,
	$write_speed,
	$read_dir_def,
	$write_dir_def);

#################
# Main Flow
#################

whoami();
check_reqs();
unless (</var/db/cdrx.*>) {
	intro();
	new_install();
}
Menu();

#######################
# Start of Subroutines
#######################

sub intro {
	print "\n\n\n\n\n\n\n\n\n\n\n";
	print "\t\t*******************************************************\n";
	print "\t\t***                                                 ***\n";
	print "\t\t***                Welcome to CDRX.                 ***\n";
	print "\t\t***                 Version 0.3.1                   ***\n";
	print "\t\t***                                                 ***\n";
	print "\t\t***                       ---                       ***\n";
	print "\t\t***                                                 ***\n";
	print "\t\t***                   Jason Dixon                   ***\n";
	print "\t\t***                                                 ***\n";
	print "\t\t***  Proceed to the Main Menu by pressing enter...  ***\n";
	print "\t\t*******************************************************\n";
	print "\n\n\n\n\n\n\n\n\n\n\n";
	<STDIN>;
}

#################
# Menus
#################

sub Menu {
	my $main_menu_choice;
	printbuffer();
	print "::: CDRX Main Menu :::\n\n\n";
	print "Choose one of the following: \n\n\n";
	print "\t(1) Setup\n";
	print "\t(2) CD-RW blanking\n";
	print "\t(3) Create ISO Image\n";
	print "\t(4) Burn to CD-R/RW\n";
	print "\t(5) Quit\n\n\n";
	chomp ($main_menu_choice = <STDIN>);
	$main_menu_choice =~ s/ +//;
	while (!($main_menu_choice =~ /^[1-5]\b/)) {
		print "Not a valid response.  Please choose 1-5: \n";
		chomp ($main_menu_choice = <STDIN>);
	}
	SWITCH: {
                if ($main_menu_choice == 1) { Setup(); }
       	        if ($main_menu_choice == 2) { Blank(); }
       		if ($main_menu_choice == 3) { Create_menu(); }
               	if ($main_menu_choice == 4) { Burn_menu(); }
		else {
			printbuffer(); 
			print "\t\t\t\t******************\n";
			print "\t\t\t\t***  Goodbye!  ***\n"; 
			print "\t\t\t\t******************\n\n\n\n\n\n";
			exit; 
		}
	}
}

sub Setup {
	my $setup_menu_choice;
	printbuffer();
	print "::: CDRX Setup :::\n\n\n";
	print "Choose one of the following: \n\n\n";
	print "\t(1) View current settings\n";
	print "\t(2) Setup CD-rom read device\n";
	print "\t(3) Setup CD-R/W write device\n";
	print "\t(4) Choose CD-R/W write speed\n";
	print "\t(5) Configure \"READ\" directory\n";
	print "\t(6) Configure temporary write directory\n";
	print "\t(7) Return to Main Menu\n\n\n";
	chomp ($setup_menu_choice = <STDIN>);
	$setup_menu_choice =~ s/ +//;
	while (!($setup_menu_choice =~ /^[1-7]\b/)) {
		print "Not a valid response.  Please choose 1-7: \n";
		chomp ($setup_menu_choice = <STDIN>);
	}
	SWITCH: {
                if ($setup_menu_choice == 1) { view_settings(); }
                if ($setup_menu_choice == 2) { setup_cdrom(); }
                if ($setup_menu_choice == 3) { setup_cdrw(); }
		if ($setup_menu_choice == 4) { choose_speed(); }
                if ($setup_menu_choice == 5) { config_read_dir(); }
                if ($setup_menu_choice == 6) { config_temp_dir(); }
		else { Menu(); }
 	}
}

sub Create_menu {
	my $create_menu_choice;
        printbuffer();
        print "::: Create ISO Image :::\n\n\n";
        print "Choose one of the following:\n\n\n";
        print "\t(1) Create ISO from CD-rom device\n";
        print "\t(2) Create ISO from \"READ\" directory\n";
	print "\t(3) Create ISO from assorted files\n";
        print "\t(4) Return to Main Menu\n\n\n";
        chomp ($create_menu_choice = <STDIN>);
        $create_menu_choice =~ s/ +//;
        while (!($create_menu_choice =~ /^[1-4]\b/)) {
                print "Not a valid response.  Please choose 1-4: \n";
                chomp ($create_menu_choice = <STDIN>);
        }
	SWITCH: {
		if ($create_menu_choice == 1) { cd_Create_iso(); }
		if ($create_menu_choice == 2) { dir_Create_iso(); }
		if ($create_menu_choice == 3) { files_Create_iso(); }
		else { Menu(); }
	}
}

sub Burn_menu {
	my $burn_menu_choice;
	printbuffer();
	print "::: Burn to CD-R/W :::\n\n\n";
	print "Choose one of the following:\n\n\n";
	print "\t(1) CD-to-CD instant copy\n";
	print "\t(2) Burn an existing ISO Image\n";
	print "\t(3) Burn from \"READ\" directory\n";
	print "\t(4) Burn assorted files\n";
	print "\t(5) Return to Main Menu\n\n\n";
	chomp ($burn_menu_choice = <STDIN>);
	$burn_menu_choice =~ s/ +//;
	while (!($burn_menu_choice =~ /^[1-5]\b/)) {
		print "Not a valid response.  Please choose 1-5: \n";
		chomp ($burn_menu_choice = <STDIN>);
	}
	SWITCH: {
		if ($burn_menu_choice == 1) { burn_copy_cd(); }
		if ($burn_menu_choice == 2) { burn_iso_cd(); }
		if ($burn_menu_choice == 3) { burn_dir_cd(); }
		if ($burn_menu_choice == 4) { burn_files_cd(); }
		else { Menu(); }
	}
}


#################
# Setup
#################

sub view_settings {
	db_handle();
	printbuffer();
        print "::: View settings :::\n\n\n";
	print "CD-rom read device (target,lun label):     $cdrom_def  $cdrom_label\n";
	print "CD-R/W write device (target,lun label):    $cdrw_def  $cdrw_label\n";
	print "CD-R/W write speed:                        $write_speed\n";
	print "READ directory:                            $read_dir_def\n";
	print "WRITE directory:                           $write_dir_def\n";
	print "\n\n\nPress enter to return to the Setup Menu\n";
	<STDIN>;
	Setup();
}

sub setup_cdrom { 
	my($referrer_check) = @_;
	my $i;
	$referrer = "CDROM";
	$ref_label = "CDROMLBL";
	$dev_type = "READ";
	$thing = "device";
	db_handle();
	scanbus();
	printbuffer();
	print "::: Setup CD-rom read device :::\n\n\n";
	if ($cdrom_label) {
		print "Your default CD-rom device is the $cdrom_label\n\n";
	}
	print "The list of available devices are:\n\n";
	for ($i=0; $i<@scan; $i++) {
		print "\t\($index_hash{$i}[0]\) $index_hash{$i}[4]\n";
	}
	devchoice();
	dotfile($referrer, $target_dev);
	dotfile($ref_label, $target_label);
	settings_result_print($index_hash{$dev_choice - 1}[4],$dev_type,$thing,$referrer_check);
}

sub setup_cdrw {
	my($referrer_check) = @_;
	my $i;
	$referrer = "CDRW";
	$ref_label = "CDRWLBL";
	$dev_type = "WRITE";
	$thing = "device";
	db_handle();
	scanbus();
	printbuffer();
	print "::: Setup CD-R/W write device :::\n\n\n";
	if ($cdrw_label) {
		print "Your default CD-R/W device is the $cdrw_label\n\n";
	}
	print "The list of available devices are:\n\n";
	for ($i=0; $i<@scan; $i++) {
		print "\t\($index_hash{$i}[0]\) $index_hash{$i}[4]\n";
	}
	devchoice();
	dotfile($referrer, $target_dev);
	dotfile($ref_label, $target_label);
	settings_result_print($index_hash{$dev_choice - 1}[4],$dev_type,$thing,$referrer_check);
}

sub devchoice {
	print "\nPlease choose one of the above listed devices as your $dev_type device:\n\n";
	chomp ($dev_choice = <STDIN>);
	$dev_choice =~ s/ +//;
	SWITCH: {
		if ($dev_choice eq "") { print "That is not a valid option.\n"; devchoice(); }
		if ($dev_choice =~ /[\D]/) { print "That is not a valid option.\n"; devchoice(); }
		if (!($index_hash{$dev_choice - 1}[0])) { print "That is not a valid option.\n"; devchoice(); }
		else {
			$target_dev = join(",", $index_hash{$dev_choice - 1}[1], $index_hash{$dev_choice - 1}[2], $index_hash{$dev_choice - 1}[3]);
			$target_label = $index_hash{$dev_choice - 1}[4];
		}
	}
	return ($target_dev, $target_label);
}

sub choose_speed {
	my($referrer_check) = @_;
	my ($index,$rate);
	my $speed_choice;
	$referrer = "SPEED";
	$type = "write";
	$thing = "speed";
	printbuffer();
	print "::: Choose CD-R/W write speed :::\n\n\n";
	print "Please choose one of the following speeds for your CD-R/W device:\n\n";
	%speeds = qw( 1 2X 2 4X 3 6X 4 8X 5 12X 6 16X 7 20X 8 24X 9 32X );
	while (($index,$rate) = each(%speeds)) {
		print "($index)\t$rate\n";
	}
	print "\n\n";
	chomp ($speed_choice = <STDIN>);
	$speed_choice =~ s/ +//;
	while (!($speeds{$speed_choice})) {
		print "Not a valid response.  Please choose 1-9: \n";
		chomp ($speed_choice = <STDIN>);
        }
	dotfile($referrer, $speeds{$speed_choice});
	settings_result_print($speeds{$speed_choice},$type,$thing,$referrer_check);
}

sub config_read_dir {
	my($referrer_check) = @_;
	$referrer = "READDIR";
	$type = "READ";
	$thing = "directory";
	db_handle();
        printbuffer();
        print "::: Setup READ directory :::\n\n\n";
	if ($referrer_check == 1) {
		print "HINT:\nThe \"READ\" directory is where you expect to read ISO images,\n";
		print "files or directories from while performing your burn.\n";
		print "Don't worry too much about this, you can always change it later.\n\n";
		print "A good suggestion might be your home directory.\n\n\n";
	} else {
		print "Your \"READ\" directory is where you expect to read ISO images or files from.\n";
		print "Configure this to reflect where you have stored your files TO BE BURNED.\n\n\n";
	}
	if ($read_dir_def) {
		print "Your default \"READ\" directory is $read_dir_def\n\n";
	}
       	print "Please insert the directory to read your ISO image from:\n\n";
       	chomp ($readdir = <STDIN>);
	while (!(opendir(READDIR, "$readdir"))) {
		print "Sorry, can't use $readdir.  Please try again:\n";
		chomp ($readdir = <STDIN>);
	}
       	closedir(READDIR);
       	dotfile($referrer, $readdir);
	settings_result_print($readdir,$type,$thing,$referrer_check);
}

sub config_temp_dir { 
	my($referrer_check) = @_;
	$referrer = "WRITEDIR";
	$type = "WRITE";
	$thing = "directory";
	db_handle();
	printbuffer();
	print "::: Setup WRITE directory :::\n\n\n";
	if ($referrer_check == 1) {
		print "HINT:\nThe \"WRITE\" directory is basically just a directory\n";
		print "for this program to write ISO images to.  You want to\n";
		print "make sure this directory or partition has enough space\n";
		print "available before writing to disk.\n\n";
		print "A good suggestion might be /usr/local or /tmp\n";
		print "(providing /tmp has enough space).\n\n\n";
	} else {
		print "Your \"WRITE\" directory is where you would like to write\n";
		print "your ISO images, whether permanently (creating ISO images)\n";
		print "or temporarily (burning direct to CD-R/W).\n\n\n";
	}
	if ($write_dir_def) {
		print "Your default \"WRITE\" directory is $write_dir_def\n\n";
	}
	print "Please insert the directory to write your temporary and/or ISO image to:\n\n";
	chomp ($writedir = <STDIN>);
	while (!(opendir(WRITEDIR, "$writedir"))) {
		print "Sorry, can't use $writedir.  Please try again:\n";
		chomp ($writedir = <STDIN>);
	}
	closedir(WRITEDIR);
	dotfile($referrer, $writedir);
	settings_result_print($writedir,$type,$thing,$referrer_check);
}

sub settings_result_print {
        my($object,$type,$thing,$return_handler) = @_;
        printbuffer();
        print "*******************************************\n";
        print "You've chosen $object\n";
        print "as your $type $thing.\n\n";
        if ($return_handler == 1) {
                print "Press enter to return to the Install Wizard\n";
	} elsif ($return_handler == 2) {
		print "Press enter to continue \"CD-to-CD\" copying\n";
	} elsif ($return_handler == 3) {
		print "Press enter to continue \"ISO to CD\" burning\n";
	} elsif ($return_handler == 4) {
		print "Press enter to continue creating your ISO\n";
	} elsif ($return_handler == 5) {
		print "Press enter to continue \"directory to CD\" burning\n";
        } else {
                print "Press enter to return to the Setup Menu\n";
        }
        print "*******************************************\n\n\n\n\n\n";
        <STDIN>;
        if ($return_handler == 1) {
                install_handler();
	} elsif ($return_handler == 2) {
		burn_copy_cd();
	} elsif ($return_handler == 3) {
		burn_iso_cd();
	} elsif ($return_handler == 4) {
		dir_Create_iso();
	} elsif ($return_handler == 5) {
		burn_dir_cd();
        } else {
                Setup();
        }
}

#################
# Blanking
#################

sub Blank {
	my $blank_choice;
	my $option;
	my $continue;
	my $no_media;
	printbuffer();
	print "Choose one of the following blank types: \n\n\n";
	print "\t(1) All = Blank the entire disk\n";
	print "\t(2) Fast = Minimally blank the disk \(PNA, TOC and pregap\)\n";
	print "\t(3) Return to Main Menu\n\n\n";
	chomp ($blank_choice = <STDIN>);
	while (!($blank_choice =~ /^[1-3]\b/)) {
		print "Not a valid response.  Please choose 1-3: \n";
		chomp ($blank_choice = <STDIN>);
	}
	if ($blank_choice == 1) {
		$option = "all";
	} elsif ($blank_choice == 2) {
		$option = "fast";
	} else {
		Menu();
	}
	printbuffer();
	print "*********************************************\n";
	print "About to start a \"$option\"-style CD-RW blanking.\n\n";
	print "Enter Y to continue or any other key\nto return to the Main Menu\n";
	print "*********************************************\n\n\n\n\n\n";
	chomp ($continue = <STDIN>);
	if ($continue =~ /[Yy]/) {
		db_handle();
		printbuffer();
		print "Blanking...\n\n\n";
		system"cdrecord dev=$cdrw_def blank=$option 2>/tmp/cdrx.burn.err";
		$no_media = `cat /tmp/cdrx.burn.err | grep cdrecord | grep 'output error'`;
		while ($no_media =~ /output error/) {
			printbuffer();
			print "It appears you have no disk (or a bad one) in your CD-R/W drive.\n\n";
			print "Please correct and press enter to try again...\n\n\n";
			<STDIN>;
			system"cdrecord dev=$cdrw_def blank=$option 2>/tmp/cdrx.burn.err";
			$no_media = `cat /tmp/cdrx.burn.err | grep cdrecord | grep 'output error'`;
		}
		printbuffer();
		print "******************************************\n";
		print "Blanking is complete.\n\n";
		print "Press enter to return to the Main Menu\n";
		print "******************************************\n\n\n";
		<STDIN>;
		Menu();
	} else {
		Menu();
	}
}


#################
# ISO 
#################

sub cd_Create_iso {
	my $read_cdrom_dev;
        printbuffer();
        print "::: Create ISO from CDrom :::\n\n\n";
	$read_cdrom_dev = quick_choose_cdrom();
	write_dir_check();
	db_handle();
	name_your_iso();
	print "Creating ISO Image...\n\n\n";
	sleep 2;
	system"dd if=$read_cdrom_dev of=$write_dir_def/$iso_name bs=1024k";
	finished_iso_print();
}

sub dir_Create_iso {
	my($referrer_check) = @_;
	my @contents;
	my @read_dir_size;
	my @write_dir_avail;
	printbuffer();
	unless ($referrer_check == 5) {
		print "::: Create ISO from directory :::\n\n\n";
	} else {
		print "::: Burn from \"READ\" directory to CD :::\n\n\n";
	}
	read_dir_check();
	printbuffer();
	print "The contents of your \"READ\" directory will be listed below.\n";
	print "Press the spacebar to scroll through multiple screens.\n\n";
	print "Press enter to continue...\n\n\n";
	<STDIN>;
	printbuffer();
	db_handle();
	@contents = system"ls -aR $read_dir_def | more";
	foreach (@contents) {
		print $_;
	}
	@read_dir_size = split(/\t/, `du -ms $read_dir_def`);
	print "\n\n\nThe total size (in megabytes) of all files to be included is:  $read_dir_size[0].\n\n";
	print "Press enter to continue\n";
	<STDIN>;
	printbuffer();
	unless ($referrer_check == 5) {
		write_dir_check();
	}
	@write_dir_avail = split(/ +/, `df -m $write_dir_def | grep -v sys`);
	if ($write_dir_avail[3] > $read_dir_size[0]) {
		unless ($referrer_check == 5) {
			name_your_iso();
		} else {
			$iso_name = "cdrx-tmp2.iso";
		}
		print "Creating ISO Image...\n\n\n";
		sleep 2;
		system"mkisofs -r -o $write_dir_def/$iso_name $read_dir_def";
		unless ($referrer_check == 5) {
			finished_iso_print();
		} else {
			sub_burn_dir_cd();
		}
	} else {
		printbuffer();
		print "**************************************************\n";
		print "Sorry, your \"WRITE\" directory does not have\n";
		print "enough space to handle the temporary ISO image.\n\n";
		print "Press enter to change your directory settings...\n";
		print "**************************************************\n\n\n\n\n\n";
		<STDIN>;
		unless ($referrer_check == 5) {
			$dir_Create_iso_referrer = 4;
		} else {
			$dir_Create_iso_referrer = 5;
		}
		config_temp_dir($dir_Create_iso_referrer);
	}
}

sub files_Create_iso {
	my($referrer_check) = @_;
	my @burn_list = ();
	my @real_burn_list = ();
	my %file_list;
	my $file_choice;
	my %uniq = ();
	my $burn_string;
	printbuffer();
	unless ($referrer_check == 6) {
        	print "::: Create ISO from files :::\n\n\n";
	} else {
		print "::: Burn assorted files to CD :::\n\n\n";
	}
	read_dir_check();
	printbuffer();
	print "Listing the contents of your current directory...\n\n";
	%file_list = dir_file_list();
	print "\nPlease choose a file number, \"L\" to list again\n\"C\" to change directories, or \"Q\" to quit:\n";
	chomp ($file_choice = <STDIN>);
	while (!($file_choice =~ /[Qq]/)) {
		if ($file_list{$file_choice -1}) {
			push(@burn_list,$file_list{$file_choice -1});
			print "\nPlease choose again [#/L/C/Q]:\n";
			chomp ($file_choice = <STDIN>);
		} elsif ($file_choice =~ /[Ll]/) {
			dir_file_list();
			print "\nPlease choose again [#/L/C/Q]:\n";
			chomp ($file_choice = <STDIN>);
		} elsif ($file_choice =~ /[Cc]/) {
			printbuffer();
			read_dir_check();
			printbuffer();
			print "Listing the contents of your current directory...\n\n";
			dir_file_list();
			print "\nPlease choose again [#/L/C/Q]:\n";
			chomp ($file_choice = <STDIN>);
		} else {
			print "\nNot a valid choice.  Please try again (#/List/Change/Quit):\n";
			chomp ($file_choice = <STDIN>);
		}
	}
	@burn_list = sort(@burn_list);
	foreach (@burn_list) {
		push(@real_burn_list,$_) unless $uniq{$_}++;
	}
	print "\n\nYour selections are:\n\n";
	foreach (@real_burn_list) {
		print "$_\n";
	}
	print "\n\n\n";
	write_dir_check();
	unless ($referrer_check == 6) {
		name_your_iso();
	} else {
		$iso_name = "cdrx-tmp3.iso";
	}
	db_handle();
	printbuffer();
	print "Creating ISO Image...\n\n\n";
	sleep 2;
	$burn_string = join(" ", @real_burn_list);
	system"mkisofs -r -o $write_dir_def/$iso_name $burn_string 2>/tmp/cdrx.error";
	unless ($referrer_check == 6) {
		finished_iso_print();
	} else {
		sub_burn_files_cd();
	}
}

sub dir_file_list {
	my $p;
	my $s=1;
	my $t=1;
	my @file_list = ();
	%file_list = ();
	db_handle();
	opendir(READ_DIR,$read_dir_def);
	foreach (sort readdir(READ_DIR)) {
		chomp;
		unless ((-d "$read_dir_def/$_") || (!-r "$read_dir_def/$_")) {
			push(@file_list,"$read_dir_def/$_");
		}
	}
	closedir(READ_DIR);
        for ($p=0; $p<@file_list; $p++) {
                $file_list{$p} = $file_list[$p];
                print "($s) $file_list[$p]\n";
		if ($t == 20) {
                        print "\n[Press enter to continue]\n";
                        <STDIN>;
			$t=0;
                }
		$t++;
                $s++;
        }
	return %file_list;
}

sub read_dir_check {
	db_handle();
	print "Your default \"READ\" directory is $read_dir_def\n";
        print "Press enter to read from this directory\n";
        print "or enter a new directory here: \n\n";
	chomp ($new_read_dir = <STDIN>);
        if ($new_read_dir) {
                $referrer = "READDIR";
                while (!(opendir(READDIR, "$new_read_dir"))) {
			print "Sorry, can't use $new_read_dir.  Please try again:\n";
			chomp ($new_read_dir = <STDIN>);
                }
                closedir(READDIR);
                dotfile($referrer, $new_read_dir);
                print "\nYour new \"READ\" directory is $new_read_dir.\n\n";
                print "Press enter to continue...\n";
                <STDIN>;
        }
}

sub write_dir_check {
	db_handle();
	print "Your default \"WRITE\" directory is $write_dir_def\n";
        print "Press enter to write to this directory\n";
        print "or enter a new directory here: \n\n";
	chomp ($new_write_dir = <STDIN>);
        if ($new_write_dir) {
                $referrer = "WRITEDIR";
                while (!(opendir(WRITEDIR, "$new_write_dir"))) {
                        print "Sorry, can't use $new_write_dir.  Please try again:\n\n";
                        chomp ($new_write_dir = <STDIN>);
                }
                closedir(WRITEDIR);
                dotfile($referrer, $new_write_dir);
                print "\nYour new \"WRITE\" directory is $new_write_dir.\n\n";
                print "Press enter to continue...\n";
                <STDIN>;
        }
}

sub name_your_iso {
	db_handle();
        print "\nProceeding to create your ISO.\n\n";
	print "What would you like the file to be named? :\n\n";
	chomp ($iso_name = <STDIN>);
	check_iso_name();
	while (-e "$write_dir_def/$iso_name") {
		print "\nSorry, there is already a file by the name of $iso_name in $write_dir_def.\n";
		print "Please choose another name:\n\n";
		chomp ($iso_name = <STDIN>);
		check_iso_name();
	}
        print "\n\nYour iso will be called $iso_name.\n\n";
	print "Press enter to continue...\n";
	<STDIN>;
	return;
}

sub check_iso_name {
        $iso_name =~ tr/A-Z/a-z/;
	$iso_name =~ s/\W+//;
        while (!($iso_name)) {
                print "That is not a valid response.  Please try again:\n\n";
                chomp ($iso_name = <STDIN>);
        }
        if (!($iso_name =~ /iso$/)) {
                $iso_name = $iso_name . ".iso";
        }
	return;
}
	
sub finished_iso_print {
        printbuffer();
        print "******************************************\n";
        print "Your ISO is now finished.\n\n";
        system"ls -l $write_dir_def/$iso_name";
        print "\n\nPress enter to return to the Main Menu\n";
        print "******************************************\n\n\n\n\n\n";
        <STDIN>;
        Menu();
}

sub quick_choose_cdrom {
	my @dev_array;
	my $k;
	my $m=1;
	my $cdrom_read_choice;
	print "Please choose one of the following devices to read from:\n\n";
        @dev_array = split(/\n/, `ls /dev/cdr*`);
        for ($k=0; $k<@dev_array; $k++) {
                $dev_array{$k} = $dev_array[$k];
                print "($m) $dev_array[$k]\n";
                $m++;
        }
        print "\n";
        chomp ($cdrom_read_choice = <STDIN>);
        $cdrom_read_choice =~ s/ +//;
        $cdrom_read_choice =~ s/\D+$//;
        $cdrom_read_choice =~ s/^\D+//;
        while ((!($cdrom_read_choice =~ /\d/)) || (!($dev_array{$cdrom_read_choice - 1}))) {
                print "That is not an option, please choose again:\n";
                chomp ($cdrom_read_choice = <STDIN>);
        }
        print "\nYou have chosen $dev_array{$cdrom_read_choice - 1}.\n\n";
	return $dev_array{$cdrom_read_choice - 1};
}


#################
# Burning
#################

sub burn_copy_cd {
	my $cdrom_fs_size;
	my $read_cdrom_dev;
	my $mount_err;
	my @write_dir_avail;
	db_handle();
	printbuffer();
	print "::: CD-to-CD instant copy :::\n\n\n";
	$read_cdrom_dev = quick_choose_cdrom();
	if (!(`mount -l -tiso9660` =~ /$read_cdrom_dev/)) {
		system"mount -tiso9660 $read_cdrom_dev /mnt 2>/tmp/cdrx.mount.err";
		$mount_err = `grep No /tmp/cdrx.mount.err`;
		while ($mount_err) {
			print "Sorry, it appears you have no valid media in that drive.\n";
			print "Press enter to try again...\n\n";
			<STDIN>;
			system"mount -tiso9660 $read_cdrom_dev /mnt 2>/tmp/cdrx.mount.err";
			$mount_err = `grep No /tmp/cdrx.mount.err`;
		}
		$cdrom_fs_size = `du -ms /mnt`;
		$cdrom_fs_size =~ s/\D+$//;
		system"umount /mnt";
	} else {
		$cdrom_fs_size = `du -ms $read_cdrom_dev`;
		$cdrom_fs_size =~ s/\D+$//;
	}
	@write_dir_avail = split(/ +/, `df -m $write_dir_def | grep -v sys`);
	if ($write_dir_avail[3] > $cdrom_fs_size) {
		print "Writing temporary ISO image...\n\n";
		system"umount $read_cdrom_dev 2>/dev/null";  				# making sure dev isn't mounted
		$iso_name = "cdrx-tmp.iso";
		system"dd if=$read_cdrom_dev of=$write_dir_def/$iso_name bs=1024k";
		print "Burning temporary ISO image to CD-R/W...\n\n";
		chop($write_speed);
		system"cdrecord -v -eject dev=$cdrw_def speed=$write_speed -data $write_dir_def/$iso_name 2>/tmp/cdrx.burn.err";
		no_media_check();
		system"rm -f $write_dir_def/$iso_name";
		burn_complete_print();
	} else {
	print "Sorry, your \"WRITE\" directory does not have enough space to handle the temporary ISO image.\n";
	print "Press enter to change your directory settings...\n\n";
	<STDIN>;
	$burn_copy_cd_referrer = 2;
	config_temp_dir($burn_copy_cd_referrer);
	}
}
	
sub burn_iso_cd {
	my @iso_list = ();
	my %iso_list = ();
	my $i;
	my $j=1;
	my $iso_image_choice;
	my $write_choice;
	my @iso_name_split;
	db_handle();
	printbuffer();
	print "::: Write ISO Image to CD-R/RW :::\n\n\n";
	read_dir_check();
	db_handle();
	print "Your choice of ISO images include:\n\n";
	while (<$read_dir_def/*>) {
		if (/[..][iI][sS][oO]$/) {
			push(@iso_list,$_);
		}
	}
	if (@iso_list == 0) {
		print "There are no ISO's in your \"READ\" directory.\n";
		print "Press enter to change your directory settings...\n\n";
		<STDIN>;
		$burn_iso_cd_referrer = 3;
		config_read_dir($burn_iso_cd_referrer);
	}
        for ($i=0; $i<@iso_list; $i++) {
                $iso_list{$i} = $iso_list[$i];
                print "($j) $iso_list[$i]\n";
                $j++;
        }
        print "\n\nPlease choose one of the ISO images for writing:\n";
        chomp ($iso_image_choice = <STDIN>);
        $iso_image_choice =~ s/ +//;
        $iso_image_choice =~ s/\D+//;
        while ((!($iso_image_choice =~ /\d/)) || (!($iso_list{$iso_image_choice - 1}))) {
                print "That is not a valid option, please try again:\n";
                chomp ($iso_image_choice = <STDIN>);
        }
        printbuffer();
        print "*******************************************\n";
        print "You have chosen $iso_list{$iso_image_choice - 1}.\n";
        print "Are you sure you wish to continue?\n\n";
        print "Please enter \"Y\" to proceed with write\n";
        print "or any other key to return to Main Menu\n";
        print "*******************************************\n\n\n\n\n\n";
	chomp ($write_choice = <STDIN>);
        $write_choice =~ s/ +//;
        if (!($write_choice =~ /[Yy]/)) {
                Menu();
        } else {
        printbuffer();
        print "Starting CD-R/W write in 3 seconds...\n\n\n";
        sleep 3;
	print "Burning...\n\n\n";
        chop($write_speed);
	system"cdrecord -v -eject dev=$cdrw_def speed=$write_speed -data $iso_list{$iso_image_choice - 1} 2>/tmp/cdrx.burn.err";
	@iso_name_split = split(/\//,$iso_list{$iso_image_choice - 1});
	$iso_name = $iso_name_split[$#iso_name_split];
	no_media_check();
	burn_complete_print();
	}
}

sub burn_dir_cd {
	$burn_dir_cd_referrer = 5;
	dir_Create_iso($burn_dir_cd_referrer);
}

sub sub_burn_dir_cd {
	db_handle();
	print "Burning temporary ISO image to CD-R/W...\n\n";
	chop($write_speed);
	system"cdrecord -v -eject dev=$cdrw_def speed=$write_speed -data $write_dir_def/$iso_name 2>/tmp/cdrx.burn.err";
	no_media_check();
	system"rm -f $write_dir_def/$iso_name";
	burn_complete_print();
}

sub burn_files_cd {
	$burn_files_cd_referrer = 6;
	files_Create_iso($burn_files_cd_referrer);
}

sub sub_burn_files_cd {
	db_handle();
	print "Burning temporary ISO image to CD-R/W...\n\n";
	chop($write_speed);
	system"cdrecord -v -eject dev=$cdrw_def speed=$write_speed -data $write_dir_def/$iso_name 2>/tmp/cdrx.burn.err";
	no_media_check();
	system"rm -f $write_dir_def/$iso_name";
	burn_complete_print();
}	

sub burn_complete_print {
        printbuffer();
        print "******************************************\n";
        print "Your CD burning is complete.\n\n";
        print "Press enter to return to the Main Menu  \n";
        print "******************************************\n\n\n\n\n\n";
        <STDIN>;
        Menu();
}

sub no_media_check {
	my $no_media;
	$no_media = `cat /tmp/cdrx.burn.err | grep cdrecord | grep 'output error'`;
	while ($no_media =~ /output error/) {
		printbuffer();
		print "It appears you have no disk, a bad disk,\nor a non-blank disk in your CD-R/W drive.\n\n";
		print "Please correct and press enter to try again...\n\n\n";
		<STDIN>;
		system"cdrecord -v -eject dev=$cdrw_def speed=$write_speed -data $write_dir_def/$iso_name 2>/tmp/cdrx.burn.err";
		$no_media = `cat /tmp/cdrx.burn.err | grep cdrecord | grep 'output error'`;
	}
	return;
}


##################
# helper functions
##################

sub scanbus {
	my $i;
	my @initial_breakup_array;
	my $target_and_lun;
	my @target_and_lun;
	@scan = split(/\n/, `cdrecord --scanbus | grep -v [\*] | grep -A10 scsibus | grep -v scsibus`);
	for ($i=0; $i<@scan; $i++) {
		@initial_breakup_array = split(/'/, $scan[$i]);
		$target_and_lun = $initial_breakup_array[0];
		$target_and_lun =~ s/\s+//;
		$target_and_lun =~ s/\s.*//;
		@target_and_lun = split(/,/, $target_and_lun);
		$scsibus = $target_and_lun[0];
		$target = $target_and_lun[1];
		$lun = $target_and_lun[2];
		$dev_name = join(" ", $initial_breakup_array[1], $initial_breakup_array[3]);
		$dev_name =~ s/\'+/ /;
		$dev_name =~ s/\'/ /;
		$index_num = ($i + 1);
		$index_hash{$i} = [$index_num, $scsibus, $target, $lun, $dev_name];
	}
	return;
}

sub dotfile {
        my($key, $value) = @_;
	my %settings;
        dbmopen (%settings, "/var/db/cdrx", 0666) || die "can't open cdrx database: $!";
        $settings{$key} = $value;
        dbmclose (%settings);
}

sub db_handle {
	my %settings;
        dbmopen (%settings, "/var/db/cdrx", 0666) || die "can't open cdrx database: $!";
        $cdrom_def = $settings{"CDROM"};
        $cdrom_label = $settings{"CDROMLBL"};
        $cdrw_def = $settings{"CDRW"};
        $cdrw_label = $settings{"CDRWLBL"};
        $write_speed = $settings{"SPEED"};
        $read_dir_def = $settings{"READDIR"};
        $write_dir_def = $settings{"WRITEDIR"};
        dbmclose (%settings);
        return;
}

sub whoami {
        my $whoami = `whoami`;
        chomp $whoami;
        if (!($whoami eq "root")) {
                printbuffer();
                print"  *********************************************************************\n";
                die "  * Sorry, you must be the superuser (root) to run this script.  Bye! *\n  *********************************************************************\n\n\n\n";
        }
}

sub check_reqs {
        my @reqs= qw(cdrecord dd mkisofs);
        foreach (<@reqs>) {
                if (!(`which $_ 2>/dev/null`)) {
                        die "\n***************************************\n$_ was not found.\n\nPlease make sure $_ is installed,\nor check your \$PATH variable.\n***************************************\n\n";
                }
        }
}

sub new_install {
	unless (-d("/var/db")) {
		mkdir("/var/db",0755) || die "cannot mkdir /var/db/: $!";
	}
	unless (</var/db/cdrx.*>) {
		printbuffer();
		print "****************************************************************\n\n";
		print "Welcome to the CDRX install wizard.\n\n";
		print "This wizard will attempt to help you setup your initial settings.\n";
		print "This includes your:\n\n";
		print "\t- CDrom device\n";
		print "\t- CD-R/W device\n";
		print "\t- CD-R/W write speed\n";
		print "\t- \"Read-from\" directory\n";
		print "\t- \"Write-to\" directory\n\n\n";
		print "Please press enter to continue...\n\n\n";
		print "****************************************************************\n\n\n";
		<STDIN>;
		printbuffer();
		install_handler();
		Menu();
	}
}

sub install_handler { 
	$install_referrer = 1;
	db_handle();
	SWITCH: {
		if (!($cdrom_def)) { setup_cdrom($install_referrer); }
		if (!($cdrw_def)) { setup_cdrw($install_referrer); }
		if (!($write_speed)) { choose_speed($install_referrer); }
		if (!($read_dir_def)) { config_read_dir($install_referrer); }
		if (!($write_dir_def)) { config_temp_dir($install_referrer); }
	}
	return;
}

sub printbuffer {
        print "\n\n\n\n\n\n\n\n\n\n\n";
        print "\n\n\n\n\n\n\n\n\n\n\n";
        print "\n\n\n\n\n\n\n\n\n\n\n";
	print "\n\n\n\n\n\n\n\n\n\n\n";
	print "\n\n\n\n\n\n\n\n\n\n\n";
	print "\n\n\n\n\n\n\n\n\n\n\n";
}

