#!/usr/bin/perl -w
####################################################################################################

my $display_error      = 1;
my $display_warning    = 0;
my $display_infomation = 0;

my $receipts_dir  = '/Library/Receipts';
my $resources_dir = '/Library/Printers/PPDs/Contents/Resources';

my $drv_name      = 'Muratec MFX-2570 Printer Driver';
my $pkg_file      = 'Muratec MFX-2570 PS.pkg';
my $ppd_file      = 'MuratecMFX-2570PS.ppd.gz';
my @lang_list	  = ('en.lproj'); # not use

sub main {

	my $exec = 'n';

	print_msg("\nAre you sure you want to uninstall $drv_name? [y/n]\n");

	do {
		$exec = <STDIN>;
		chomp($exec);

	} while (($exec ne 'y') && ($exec ne 'n'));

	if ($exec eq 'y') {

		my $idx = 0;
		my @remove_file_list = ("$receipts_dir/$pkg_file");

		# Mac 10.5
		push(@remove_file_list, "$resources_dir/$ppd_file");

		# Mac 10.2-10.4
#		for ($idx = 0; $idx < @lang_list; $idx++) {
#			push(@remove_file_list, "$resources_dir/$lang_list[$idx]/$ppd_file");
#		}

		my $removable = 1;
		# check permission
		for ($idx = 0; (($idx < @remove_file_list) && ($removable != 0)); $idx++) {
			if (is_removable("$remove_file_list[$idx]") == 0) {
				$removable = 0;
			}
		}

		if ($removable) {

			print_msg("\n");

			# execute uninstall
			for ($idx = 0; $idx < @remove_file_list; $idx++) {
				remove_file("$remove_file_list[$idx]");
			}

			print_msg("\nUninstallation was completed.\n\n");
		} else {
			print_msg("\nERROR: Must be run with root permission -- prefix command with 'sudo'.\n\n");
		}
	}
}

sub is_removable {
	my $file = shift;

	if (-r $file) {
		if (-w $file) {
			return (1);
		}
	} else {
		return (1);
	}
	return (0);
}

sub remove_file {
	my $file = shift;

	if (-w $file) {
        @command_args = (
            'rm',
            '-rf',
            $file,
        );
        system(@command_args);
        $return_code = $? >> 8;
        if ($return_code != 0) {
	        print_error("Unable to remove '$file': $!\n");
	    } else {
			print_msg("$file is removed.\n");
		}
	} else {
		print_msg("$file is not found.\n");
	}
}

sub print_error {
	if ($display_error) {
	    my $msg = shift;
	    print STDERR "ERROR      : $msg";
    }
}

sub print_warn {
	if ($display_warning) {
	    my $msg = shift;
	    print STDERR "WARNING    : $msg";
    }
}

sub print_info {
	if ($display_infomation) {
	    my $msg = shift;
	    print STDOUT "INFOMATION : $msg";
    }
}

sub print_msg {
    my $msg = shift;
    print STDOUT "$msg";
}


main();
