linux_slicefix.pl 33.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
#! /usr/bin/perl

my $VOL_ID = '/lib/udev/vol_id';
my $BLKID = '/sbin/blkid';
my $FDISK = '/sbin/fdisk';
my $MOUNT = '/bin/mount';
my $UMOUNT = '/bin/umount';
my $RM = '/bin/rm';
my $CP = '/bin/cp';
my $CPIO = 'cpio';
my $GZIP = 'gzip';
12 13 14 15
my $MKSWAP = '/sbin/mkswap';
my $UUIDGEN = 'uuidgen';
my $LOSETUP = 'losetup';
my $TUNE2FS = 'tune2fs';
16 17
my $LOCALIZED1 = '/.localized';
my $LOCALIZED2 = '/root/.localized';
18 19 20

use constant GZHDR1 => 0x1f8b0800;
use constant GZHDR2 => 0x1f8b0808;
21 22
use constant LARGEST_PAGE_SIZE => 0x4000;
use constant UUID_OFFSET => 1036;
23

24 25 26 27 28
#
# Turn off line buffering on output
#
$| = 1;

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
# Load up the paths. Done like this in case init code is needed.
BEGIN
{
    if (! -e "/etc/emulab/paths.pm") {
	die("Yikes! Could not require /etc/emulab/paths.pm!\n");
    }
    require "/etc/emulab/paths.pm";
    import emulabpaths;
}

use strict;

sub get_uuid
{
	my ($device) = @_;
	my $uuid;

	if (-x $VOL_ID) {
		open CMD, $VOL_ID . " --uuid $device |" || die
		     "Couldn't run vol_id: $!\n";

		$uuid = <CMD>;
		chomp $uuid;

		close CMD;
	}
	elsif (-x $BLKID) {
56
		open CMD, "$BLKID|" || die
57 58 59 60 61
			"Couldn't run blkid: $!\n";

		while (<CMD>) {
			next unless m#^$device:\s+#;
			chomp;
62
			next unless s/.*\s+UUID="([a-f0-9-]+)".*/\1/;
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
			$uuid = $_;
		}

		close CMD;
	}
	else {
		print STDERR "Can't find program to get FS UUID\n";
	}

	return $uuid;
}

sub get_label
{
	my ($device) = @_;
	my $label;

	if (-x $VOL_ID) {
		open CMD, $VOL_ID . " --label-raw $device|" || die
		     "Couldn't run vol_id: $!\n";

		$label = <CMD>;
		chomp $label;

		close CMD;
	}
	elsif (-x $BLKID) {
90
		open CMD, "$BLKID|" || die
91 92 93 94 95
			"Couldn't run blkid: $!\n";

		while (<CMD>) {
			next unless m#^$device:\s+#;
			chomp;
96
			next unless s/.*\s+LABEL="([^"]*)".*/\1/;
97 98 99 100 101 102 103 104 105 106 107 108
			$label = $_;
		}

		close CMD;
	}
	else {
		print STDERR "Can't find program to get FS label\n";
	}

	return $label;
}

109 110 111 112 113 114 115
sub set_random_rootfs_uuid
{
	my ($root) = @_;
	
	system("$TUNE2FS -U random $root");
}

116 117 118 119 120 121 122
sub disable_time_dependent_fsck
{
	my ($root) = @_;
	
	system("$TUNE2FS -i 0 $root >/dev/null 2>&1");
}

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
sub kernel_version_compare
{
	my ($v1, $v2) = @_;

	my $v1_code = sprintf "%x%02x%02x", (split /\./, $v1)[0 .. 2];
	my $v2_code = sprintf "%x%02x%02x", (split /\./, $v2)[0 .. 2];

	if ($v1_code < $v2_code) {
		return -1;
	}
	elsif ($v1_code == $v2_code) {
		return 0;
	}
	else {
		return 1;
	}
}

sub find_swap_partitions
{
	my ($device) = @_;
	my @swap_devices;

	open CMD, $FDISK . " -l $device|" ||
	     die "Couldn't run fdisk: $!\n";

	while (<CMD>) {
		next unless m#^$device#;
		split /\s+/;
		if ($_[4] eq '82') {
			push @swap_devices, $_[0];
		}
	}

	close CMD;

	return @swap_devices;
}

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
sub set_swap_uuid
{
	my ($device, $uuid) = @_;
	my $swap_header;
	
	if (!open DEVICE, "+<$device") {
		print STDERR "Couldn't open $device: $!\n";      
		return 1;
	}
	
	my $id;
	for (my $i = 0x1000; $i <= LARGEST_PAGE_SIZE; $i <<= 1) {
		seek DEVICE, 0, 0;
		read DEVICE, $swap_header, $i;
		$id = unpack('Z10', substr($swap_header, $i - 10));
		last if ($id eq 'SWAPSPACE2');
	}
	                              
	if ($id ne 'SWAPSPACE2') {
		print STDERR "Device $device does not contain a new-style swap header\n";
		close DEVICE;
		return 1;
	}
	
	my $new_uuid = pack('H8H4H4H4H12', split(/-/, $uuid));
	substr $swap_header, UUID_OFFSET, 16, $new_uuid;
	
	seek DEVICE, 0, 0;
	print DEVICE $swap_header;
	
	close DEVICE;
}

195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
sub fix_grub_dom0mem
{
	my ($imageroot, $file) = @_;
	my $dom0mem = $ENV{"SLICEFIX_DOM0MEM"};

	if (!$dom0mem ||
	    system("grep -q 'dom0_mem=' $imageroot/$file 2>/dev/null")) {
		return;
	}

	print STDERR "Setting dom0 memory to $dom0mem\n";
	open FILE, "+<$imageroot/$file" ||
	     die "Couldn't open $imageroot/$file: $!\n";

	my @buffer = ();
	while (<FILE>) {
		s#dom0_mem=\w+#dom0_mem=$dom0mem#g;
		push @buffer, $_;
	}

	seek FILE, 0, 0;
216
	truncate FILE, 0;
217 218 219 220 221 222 223 224

	print FILE @buffer;

	close FILE;

	return;
}

225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
sub fix_swap_partitions
{
	my ($imageroot, $root, $old_root) = @_;
	my @swapdevs;

	return undef unless (-x $MKSWAP);

	my ($root_disk) = ($root =~ m#^(/dev/[a-z]+)#);
	my ($old_root_disk) = ($old_root =~ m#^(/dev/[a-z]+)#);
	my @swap_partitions = find_swap_partitions($root_disk);
	my ($l, $u) = binary_supports_blkid("$imageroot/sbin/swapon");

	for my $part (@swap_partitions) {
		my $swapdev = $part;
		next if system("$MKSWAP $part");
		my $uuid = get_uuid($part);
		if ($u) {
			if ($uuid) {
				$swapdev = "UUID=$uuid";
			}
			else {
				# BusyBox's mkswap doesn't support UUIDs, so
				# we'll need to generate it and write it out.
				$uuid = `$UUIDGEN`;
				chomp $uuid;
				set_swap_uuid($swapdev, $uuid);
				$swapdev="UUID=$uuid";
			}
		}
		elsif ($old_root) {
			$swapdev =~ s#^$root_disk#$old_root_disk#;
		}

		push @swapdevs, $swapdev;
	}

	return undef unless (@swapdevs);

	my @buffer;
	if (!open FSTAB, "+<$imageroot/etc/fstab") {
		print STDERR "Failed to open fstab: $!\n";
		return undef;
	}

	@buffer = grep {!/^[^#].*\bswap\b.*$/} <FSTAB>;
270 271 272 273 274
	if (@swapdevs > 0) {
		push @buffer, "# the following swap devices added by linux_slicefix\n";
		for (@swapdevs) {
			push @buffer, "$_\tnone\tswap\tsw\t0 0\n";
		}
275 276 277 278 279 280
	}
	seek FSTAB, 0, 0;
	print FSTAB @buffer;
	close FSTAB;
}

281
sub file_replace_string
282
{
283
	my ($imageroot, $file, $ostr, $nstr) = @_;
284 285
	my @buffer;

286 287
	if (!$ostr) {
		print STDERR "old string is empty\n";
288 289 290
		return 1;
	}

291 292 293 294
	open FILE, "+<$imageroot/$file" ||
	     die "Couldn't open $imageroot/$file: $!\n";

	while (<FILE>) {
295
		s#$ostr#$nstr#g;
296 297 298 299
		push @buffer, $_;
	}

	seek FILE, 0, 0;
300
	truncate FILE, 0;
301

302
	print FILE @buffer;
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339

	close FILE;

	return 1;
}

sub rewrite_lilo_config
{
	my ($imageroot, $old_root, $new_root) = @_;
	my @buffer;

	open FILE, "+<$imageroot/etc/lilo.conf" ||
	     die "Couldn't open $imageroot/etc/lilo.conf: $!\n";

	while (<FILE>) {
		chomp;
		next if /^\s*root\s*=\s*/;
		s/^\s*boot\s*=\s*.*$/boot = $new_root/g;
		if (/append\s*=\s*/i) {
			s/\s*root=[^"'\s]*//g;
			s/(["'])\s*$/ root=$new_root$1/;
		}
		push @buffer, $_;
	}

	seek FILE, 0, 0;

	print FILE "$_\n" for (@buffer);

	close FILE;

	return 1;
}

sub set_runlilo_flag
{
	my ($imageroot, $default_entry, $new_root) = @_;
340
	my $cmdline;
341 342 343

	open FILE, ">$imageroot/var/emulab/boot/runlilo" ||
	     die "Couldn't write to runlilo file: $!\n";
344 345
	
	$cmdline = "$default_entry root=$new_root";
346

347
	print FILE "$cmdline\n";
348 349 350

	close FILE;

351
	return $cmdline;
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
}

sub find_default_grub_entry
{
	my ($imageroot, $conf) = @_;
	my @buffer;
	my $default = 0;
	my $current_entry = -1;
	my ($kernel, $cmdline, $initrd);

	open FILE, "$imageroot/$conf" || die "Couldn't read grub config: $!\n";
	while (<FILE>) {
		if (/^default\s+(\d+)$/) {
			$default = $1;
			next;
		}
		elsif (/^\s*(\S+)\s+(.*)$/) {
			if ($1 eq 'title') {
				$current_entry++;
			}

			next if ($current_entry < $default);
			last if ($current_entry > $default);

			if ($1 eq 'kernel') {
				$_ = $2;
				($kernel, $cmdline) = /^(\S+)\s+(.*)$/;
			}
			elsif ($1 eq 'initrd') {
				$initrd = $2;
			}
		}
	}
	close FILE;

	return ($kernel, $cmdline, $initrd);
}

390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
sub find_default_grub2_entry
{
	my ($imageroot, $conf) = @_;
	my @buffer;
	my $default = 0;
	my $current_entry = -1;
	my ($kernel, $cmdline, $initrd);

	open FILE, "$imageroot/$conf" || die "Couldn't read grub config: $!\n";
	while (<FILE>) {
		if (/^set\s+default\s*=\s*["']?(\d+)["']?$/) {
			$default = $1;
			next;
		}
		elsif (/^\s*(\S+)\s+(.*)$/) {
			if ($1 eq 'menuentry') {
				$current_entry++;
			}

			next if ($current_entry < $default);
			last if ($current_entry > $default);

412
			if ($1 eq 'linux' || $1 eq 'linux16') {
413 414 415
				$_ = $2;
				($kernel, $cmdline) = /^(\S+)\s+(.*)$/;
			}
416
			elsif ($1 eq 'initrd' || $1 eq 'initrd16') {
417 418 419 420 421 422 423 424 425
				$initrd = $2;
			}
		}
	}
	close FILE;

	return ($kernel, $cmdline, $initrd);
}

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
sub set_grub_root_device
{
	my ($imageroot, $grub_config, $root) = @_;
	my ($root_disk, $root_part) =
	   ($root =~ m#/dev/(.+)(\d+)#);
	my $grub_disk;

	if (-f $BOOTDIR . "/edd_map") {
		open FILE, $BOOTDIR . "/edd_map";
		while (<FILE>) {
			chomp;
			split /=/;
			if ($_[0] eq $root_disk) {
				$grub_disk = hex($_[1]) - 0x80;
				print "Found GRUB root device using EDD\n";
				last;
			}
		}
		close FILE;
	}

	if (not defined $grub_disk) {
		$grub_disk = $root;
449
		$grub_disk =~ s/^\/dev\/[hs]d(.).*$/$1/;
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
		$grub_disk =~ y/[a-h]/[0-7]/;
		print "Found GRUB root device by guessing\n";
	}

	printf "GRUB root device is (hd%d,%d)\n", $grub_disk, $root_part - 1;
	$root_part--;

	open FILE, "+<$imageroot/$grub_config" or
	     die "Couldn't open GRUB config: $!\n";
	my @buffer;
	while (<FILE>) {
		s/^(\s*)root \([^)]*\)/$1root (hd$grub_disk,$root_part)/;
		push @buffer, $_;
	}
	seek FILE, 0, 0;
465
	truncate FILE, 0;
466
	print FILE @buffer;
467 468 469
	close FILE;
}

470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
sub set_grub2_root_device
{
	my ($imageroot, $grub_config, $root) = @_;
	my ($root_disk, $root_part) =
	   ($root =~ m#/dev/(.+)(\d+)#);
	my $grub_disk;

	if (-f $BOOTDIR . "/edd_map") {
		open FILE, $BOOTDIR . "/edd_map";
		while (<FILE>) {
			chomp;
			split /=/;
			if ($_[0] eq $root_disk) {
				$grub_disk = hex($_[1]) - 0x80;
				print "Found GRUB root device using EDD\n";
				last;
			}
		}
		close FILE;
	}

	if (not defined $grub_disk) {
		$grub_disk = $root;
		$grub_disk =~ s/^\/dev\/[hs]d(.).*$/$1/;
		$grub_disk =~ y/[a-h]/[0-7]/;
		print "Found GRUB root device by guessing\n";
	}

	printf "GRUB root device is (hd%d,%d)\n", $grub_disk, $root_part;

	open FILE, "+<$imageroot/$grub_config" or
	     die "Couldn't open GRUB config: $!\n";
	my @buffer;
	while (<FILE>) {
504 505 506 507
		# XXX eat the newline so the RE does not!
		chomp;
		s/^(\s*set\s+root\s*=\s*["']?\(?)[^)'"]*(\)?["']?)/$1hd$grub_disk,$root_part$2/;
		push @buffer, "$_\n";
508 509
	}
	seek FILE, 0, 0;
510
	truncate FILE, 0;
511 512 513 514
	print FILE @buffer;
	close FILE;
}

515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
sub find_default_lilo_entry
{
	my ($imageroot, $conf) = @_;
	my %images;
	my %globals;
	my @image_list;
	my ($kernel, $cmdline, $initrd);
	my $default;

	open FILE, "$imageroot/$conf" || die "Couldn't read lilo config: $!\n";
	while (<FILE>) {
		chomp;

		my $command;
		my $args;
		s/\s*#.*$//; # Remove comments
		s/\s+$//; # Remove trailing whitespace
		next if (/^$/); # Skip blank lines
		if (/^\s*image\s*=\s*(.*)\s*$/i) {
			push @image_list, $1;
			$images{$1} = {'image' => $1};
		}
		elsif (/^\s*(?:label|alias)\s*=\s*(.*)\s*$/i) {
			$images{$1} = $images{$image_list[-1]};
		}
		elsif (/^\s*(\S+)\s*=\s*(.*)\s*$/) {
			($command, $args) = (lc $1, $2);
		}
		elsif (/^\s*(?:read-only|ro)$/) {
			($command, $args) = ('read-only', 'ro');
		}
		elsif (/^\s*(?:read-write|rw)$/) {
			($command, $args) = ('read-only', 'rw');
		}
		else {
			($command, $args) = ($_, 1);
		}

		if (@image_list) {
			${$images{$image_list[-1]}}{$command} = $args;
		}
		else {
			$globals{$command} = $args;
		}
	}
	close FILE;

	if (exists $globals{'default'}) {
		$default = $globals{'default'};
	}
	else {
		$default = $image_list[0];
	}

	my $root = $images{$default}{'root'};
	$initrd = $images{$default}{'initrd'};
	$cmdline = $images{$default}{'append'};
	$kernel = $images{$default}{'image'};
	my $ro = $images{$default}{'read-only'};
	if (not defined $root) {
		$root = $globals{'root'};
	}
	if (not defined $initrd) {
		$initrd = $globals{'initrd'};
	}
	if (not defined $cmdline) {
		$cmdline = $globals{'append'};
	}
	if (not defined $ro) {
		$ro = $globals{'read-only'};
	}

	$cmdline =~ s/^"(.*)"$/$1/;
	if ($root && $cmdline !~ /\broot=\S+\b/) {
		$cmdline .= " root=$root";
	}
	if ($ro && $cmdline !~ /\br[ow]\b/) {
		$cmdline .= " $ro";
	}

	return ($default, $kernel, $cmdline, $initrd);
}

sub guess_bootloader
{
	my ($device) = @_;
	my $buffer;
	my $bootloader;

	open DEVICE, $device || die "Couldn't open $device: $!\n";
	read DEVICE, $buffer, 512;
	close DEVICE;

	if ($buffer =~ /GRUB/) {
		$bootloader = 'grub';
	}
	elsif ($buffer =~ /LILO/) {
		$bootloader = 'lilo';
	}

	return $bootloader;
}

sub udev_supports_label
{
	my ($imageroot) = @_;
	my ($handles_label, $handles_uuid) = (0, 0);

	if (! -d "$imageroot/etc/udev/rules.d") {
		return (0, 0);
	}

	my @files = glob "$imageroot/etc/udev/rules.d/*";
628 629 630
	if (@files) {
		@files = glob "$imageroot/lib/udev/rules.d/*";
	}
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
	for my $file (@files) {
		open FILE, $file or next;
		my @buffer = <FILE>;
		close FILE;
		if (grep(/[^#]*ID_FS_UUID/, @buffer)) {
			$handles_uuid = 1;
		}

		if (grep(/[^#]*ID_FS_LABEL/, @buffer)) {
			$handles_label = 1;
		}
	}

	return ($handles_label, $handles_uuid);
}

sub binary_supports_blkid
{
	my ($file) = @_;
	my $handles_label = 0;
	my $handles_uuid = 0;

	if (-x $file) {
		local $/;
		my $buffer;
		open FILE, $file or
		     die "Couldn't grep $file: $!\n";
		$buffer = <FILE>;
		close FILE;

		if ($buffer =~ /libblkid\.so/) {
			$handles_label = 1;
			$handles_uuid = 1;
		}
		else{ 
			if ($buffer =~ /LABEL/) {
				$handles_label = 1;
			}
			if ($buffer =~ /UUID/) {
				$handles_uuid = 1;
			}
		}
	}

	return ($handles_label, $handles_uuid);
}

sub get_fstab_root
{
	my ($imageroot) = @_;
	my $root;

	open FSTAB, "$imageroot/etc/fstab" ||
	     die "Couldn't open fstab: $!\n";

	while (<FSTAB>) {
		split /\s+/;
		if ($_[1] eq '/') {
			$root = $_[0];
		}
	}

	close FSTAB;

	return $root;
}

sub check_kernel
{
	my ($kernel) = @_;
	my $offset = 0;;
	my $buffer;
	my $rc;
	my $kernel_file = "/tmp/kernel.$$";
	my $kernel_has_ide = 0;
	my $version_string;

Mike Hibler's avatar
Mike Hibler committed
708
	open KERNEL, $kernel or die "Couldn't open $kernel: $!\n";
709 710 711 712 713 714 715 716 717
	read KERNEL, $buffer, 4;
	while ($rc = read KERNEL, $buffer, 1, length($buffer)) {
		my ($value) = unpack 'N', $buffer;
		if ($value == GZHDR1 || $value == GZHDR2) {
			last;
		}
		$buffer = substr $buffer, 1;
	}
	if ($rc == 0) {
718
		close KERNEL;
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
		return undef;
	}

	open GZIP, "|$GZIP -dc > $kernel_file 2> /dev/null";
	print GZIP $buffer;
	while (read KERNEL, $buffer, 4096) {
		print GZIP $buffer;
	}
	close KERNEL;
	close GZIP;

	open KERNEL, $kernel_file or die "Couldn't open raw kernel: $!\n";
	while (<KERNEL>) {
		if (/ide[-_]disk/) {
			$kernel_has_ide = 1;
		}
		if (/Linux version (\S+)/) {
			$version_string = $1;
		}
	}
	close KERNEL;

	unlink "$kernel_file";

	return ($version_string, $kernel_has_ide);
}

sub check_initrd
{
	my ($initrd) = @_;
	my $decompressed_initrd = "/tmp/initrd.$$";
	my $initrd_dir = "/tmp/initrd.dir.$$";
	my $handles_label = 0;
	my $handles_uuid = 0;

	return undef if (! -f $initrd);

	mkdir $initrd_dir;
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811

	# Check to see if there's an uncompressed early cpio archive
	# prepended to the main gzip'd cpio hunk.  We have to parse the cpio
	# headers to find the correct next place to read, unfortunately.
	#
	# Assume that we won't find anything; in that case we will
	# decompress $initrd below.
	my $initrd_filename = $initrd;
	my $rc;
	my $buffer;
	my $offset = 0;
	open INITRD, $initrd or die "Couldn't open $initrd: $!\n";
	while ($rc = read INITRD, $buffer, 6) {
		# Basically, read any uncompressed newc-format CPIO
		# headers that we can.  If we find any, the compressed
		# CPIO blob follows the final uncompressed header.
		if ($buffer eq '070701' || $buffer eq '070702') {
			my $tbuf;
			$rc = read(INITRD,$tbuf,110-6);
			if ($rc != (110-6)) {
				die "Malformed early uncompressed initramfs!\n";
			}
			$buffer .= $tbuf;
			my $namesize = hex(substr($buffer,94,8));
			my $filesize = hex(substr($buffer,54,8));
			$offset += 110;
			$offset = (($offset + $namesize + 3) & ~3);
			$offset = (($offset + $filesize + 3) & ~3);
			seek(INITRD,$offset,0);
		}
		elsif ($offset > 0 && ord(substr($buffer,0,1)) == 0) {
			$offset += 4;
			seek(INITRD,$offset,0);
			next;
		}
		else {
			last;
		}
	}
	if ($offset > 0) {
		my $inner_initrd = "/tmp/initrd.inner.$$";
		seek(INITRD,$offset,0);
		open(INNERINITRD,">$inner_initrd")
			or die "Con't open $inner_initrd: $!\n";
		while ($rc = read(INITRD,$buffer,4096)) {
			print INNERINITRD $buffer;
		}
		close(INNERINITRD);
		# If we extracted an inner blob, change the filename we
		# will attempt to decompress.
		$initrd_filename = $inner_initrd;
	}
	close(INITRD);

	`$GZIP -dc < "$initrd_filename" > "$decompressed_initrd" 2> /dev/null`;
812
	if ($? >> 8) {
813
		`$CP "$initrd_filename" "$decompressed_initrd"`;
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
		if ($? & 0xff) {
			return undef;
		}
	}

	`$MOUNT -o ro,loop -t ext3 "$decompressed_initrd" "$initrd_dir" 2> /dev/null`;
	if ($? >> 8) {
		`$MOUNT -o ro,loop -t ext2 "$decompressed_initrd" "$initrd_dir" 2> /dev/null`;
		if ($? >> 8) {
			`cd "$initrd_dir" && $CPIO -idu < "$decompressed_initrd" > /dev/null 2>/dev/null`;
			if ($? >> 8) {
				return undef;
			}
		}
	}

	for ('/bin/busybox', '/bin/nash', '/bin/mount') {
		next unless (-f "$initrd_dir/$_");
		($handles_label, $handles_uuid) =
		    binary_supports_blkid("$initrd_dir/$_");
		last;
	}

	if (!$handles_label && !$handles_uuid) {
		($handles_label, $handles_uuid) =
		    udev_supports_label($initrd_dir);
	}

842 843 844 845 846 847 848
	#
	# XXX we are going to wing it here and assume "yes" and "yes" if the
	# initrd is the Fedora/CentOS "early cpio" variety. Would take more
	# machinery to extract the real initrd CPIO archive that appears to
	# be appended to the initial small one. I'm just not that in to it.
	#
	if (!$handles_label && !$handles_uuid && -f "$initrd_dir/early_cpio") {
849
	    print "Found initrd early_cpio; assuming handles label/UUID\n";
850 851 852
	    $handles_label = $handles_uuid = 1;
	}

853 854
	`$UMOUNT "$initrd_dir" > /dev/null 2> /dev/null`;
	`$RM -rf "$initrd_dir" "$decompressed_initrd"`;
855 856 857 858 859 860 861 862
	
	my @loopdevs;
	open LOSETUP, "$LOSETUP|";
	while (<LOSETUP>) {
		chomp;
		split /:/;
		push @loopdevs, $_[0];
	}
863
	close LOSETUP;
864 865 866 867 868
	
	for my $dev (@loopdevs) {
		`$LOSETUP -d $dev`;
	}
		
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
	return ($handles_label, $handles_uuid);
}

sub mount_image
{
	my ($root, $imageroot) = @_;
	my $fstype;

	for my $type (qw/ext3 ext2/) {
		`mount -t $type $root $imageroot`;
		if (!($? >> 8)) {
			$fstype = $type;
			last;
		}
	}

	return $fstype;
}

sub update_random_seed
{
	my ($imageroot) = @_;
	my $seed;
	my $size;
	my $rc = 1;

	if (! -f "$imageroot/var/lib/random-seed") {
		return undef;
	}

	print "Updating /var/lib/random-seed\n";
	open URANDOM, '/dev/urandom';
	$size = 512;
	while ($rc && $size > 0) {
		my $rc = read URANDOM, $seed, $size, length($seed);
		$size -= $rc;
	}
	close URANDOM;

	open SEED, ">$imageroot/var/lib/random-seed";
	print SEED $seed;
	close SEED;
}

913 914
sub fix_console
{
915
    my ($imageroot, $bloader, $file) = @_;
916 917 918 919 920 921 922 923 924

    my $console = $ENV{"SLICEFIX_CONSOLE"};
    if (!$console) {
	print STDERR "no SLICEFIX_CONSOLE, leaving console as is\n";
	return;
    }

    print STDERR "Setting console device to $console\n";

925
    # parse off speed if present
926
    my $sspeed = 115200;
927 928 929 930
    if ($console =~ /^([^,]+),(\d+)$/) {
	$console = $1;
	$sspeed = $2;
    }
931 932

    my $sunit = -1;
933
    my $sport = "";
934 935
    if ($console =~ /^sio(\d+)$/) {
	$sunit = ($1 > 1) ? $1 - 1 : 0;
936 937 938 939 940

	if ($bloader eq 'grub2' && $sunit < 4) {
	    my @smap = ("0x3F8", "0x2F8", "0x3E8", "0x2E8");
	    $sport = $smap[$sunit];
	}
941 942
    }

943 944
    fix_grub_console($imageroot, $file, $console, $sunit, $sspeed, $sport);
    fix_grub_defaults($imageroot, $console, $sunit, $sspeed, $sport);
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987

    # XXX we don't bother with /etc/inittab, only RHLnn-STD used it

    # Fixup upstart console config
    my $getty = "$imageroot/etc/init/ttyS0.conf";
    if (-e "$getty") {
	# If we don't already have a backup, create one
	if (! -e "$getty.preemulab") {
	    if (system("cp -p $getty $getty.preemulab")) {
		print STDERR "WARNING: could not backup old $getty!\n";
	    }
	}

	if ($sunit < 0) {
	    # XXX cannot use .override as old version don't support it,
	    # so get rid of it
	    if (unlink($getty) == 0) {
		print STDERR "could not remove $getty\n";
	    }
	} else {
	    # XXX wtf, apparently port/baud can be in either order
	    #     helluva way to run a command line...
	    file_replace_string($imageroot, "/etc/init/ttyS0.conf",
				"ttyS. [0-9]+ ", "ttyS$sunit $sspeed ");
	    file_replace_string($imageroot, "/etc/init/ttyS0.conf",
				"[0-9]+ ttyS. ", "$sspeed ttyS$sunit ");
	}
    }
    # previously moved out of the way
    elsif (-e "$getty.preemulab") {
	if ($sunit >= 0) {
	    # copy it back
	    system("cp -p $getty.preemulab $getty");
	    
	    # tweak it as above
	    file_replace_string($imageroot, "/etc/init/ttyS0.conf",
				"ttyS. [0-9]+ ", "ttyS$sunit $sspeed ");
	    file_replace_string($imageroot, "/etc/init/ttyS0.conf",
				"[0-9]+ ttyS. ", "$sspeed ttyS$sunit ");
	}
    }
}

988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
#
# Handle default settings file for grub since package installation
# might cause the grub.cfg file to get recreated.
#
# We just append variable definitions to the end of the file and
# override any existing settings. This would only adversely affect the
# GRUB_CMDLINE_LINUX param if it was being used for some other options.
# For vid or null we add:
#
# GRUB_CMDLINE_LINUX="console=tty0"
# GRUB_TERMINAL=console
# GRUB_SERIAL_COMMAND=""
#
# and for sio[1-3] we add:
#
# GRUB_CMDLINE_LINUX="console=ttySN,S"
# GRUB_TERMINAL=serial
# GRUB_SERIAL_COMMAND="serial --speed=S --unit=N"
#
sub fix_grub_defaults
{
    my ($imageroot, $console, $sunit, $sspeed, $sport) = @_;
    my $gdef = "$imageroot/etc/default/grub";

    if (! -e $gdef) {
	return;
    }
    if (! -e "$gdef.preemulab") {
	system("cp -p $gdef $gdef.preemulab");
    }

    if (!open(FILE, "+<$gdef")) {
	return;
    }

    my $esig = "# The remaining lines were added by Emulab slicefix";

    my @buffer = ();
    while (<FILE>) {
	if (/^$esig/) {
	    last;
	}
	push @buffer, $_;
    }

    # append our info
    push @buffer, "$esig\n";
    push @buffer, "# DO NOT ADD ANYTHING AFTER THIS POINT AS IT WILL GET REMOVED.\n";
    if ($sunit < 0) {
	push @buffer, "GRUB_CMDLINE_LINUX=\"console=tty0\"\n";
	push @buffer, "GRUB_TERMINAL=console\n";
	push @buffer, "GRUB_SERIAL_COMMAND=\"\"\n";
    } else {
	push @buffer, "GRUB_CMDLINE_LINUX=\"console=ttyS$sunit,$sspeed\"\n";
	push @buffer, "GRUB_TERMINAL=serial\n";
	if ($sport) {
	    push @buffer, "GRUB_SERIAL_COMMAND=\"serial --unit=$sunit --port=$sport --speed=$sspeed\"\n";
	} else {
	    push @buffer, "GRUB_SERIAL_COMMAND=\"serial --unit=$sunit --speed=$sspeed\"\n";
	}
    }

    seek FILE, 0, 0;
    truncate FILE, 0;

    print FILE @buffer;

    close FILE;
}

1058 1059
sub fix_grub_console
{
1060
	my ($imageroot, $file, $console, $sunit, $sspeed, $sport) = @_;
1061
	my $comunit = $sunit + 1;
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080

	open FILE, "+<$imageroot/$file" ||
	     die "Couldn't open $imageroot/$file: $!\n";

	my @buffer = ();
	while (<FILE>) {
	    #
	    # Fix up serial --unit=N --speed=S line:
	    #  vga/null: comment out
	    #  sio*: uncomment and make sure N is correct (must exist!)
	    #
	    if (/^(#?)serial\s/) {
		my $com = $1;
		if ($sunit < 0) {
		    if ($com) {
			push @buffer, $_;
		    } else {
			push @buffer, "#$_";
		    }
1081 1082
		} elsif ($sport) {
		    push @buffer, "serial --unit=$sunit --port=$sport --speed=$sspeed\n";
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
		} else {
		    push @buffer, "serial --unit=$sunit --speed=$sspeed\n";
		}
		next;
	    }
	    #
	    # grub1 terminal lines
	    #
	    if (/^terminal\s/) {
		if ($sunit < 0) {
		    push @buffer, "terminal --timeout=5 console\n";
		} else {
		    push @buffer, "terminal --dumb --timeout=0 serial console\n";
		}
		next;
	    }
	    #
	    # grub2 terminal_{input,output} lines
	    #
	    if (/^terminal_(input|output)\s/) {
		my $dir = $1;
		if ($sunit < 0) {
		    push @buffer, "terminal_$dir console\n";
		} else {
		    push @buffer, "terminal_$dir serial\n";
		}
		next;
	    }
	    #
	    # Kernel and initrd command lines with VGA (tty0)
	    #
	    if (/console=tty0\s/) {
		# get rid of any existing serial console clauses
		s#console=ttyS\S+##g;
		if ($sunit >= 0) {
		    # change tty0 to appropriate serial device
		    s#console=tty0#console=ttyS$sunit,$sspeed#;
		}
		push @buffer, $_;
		next;
	    }
	    #
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
	    # Xen command lines with VGA (vga)
	    #
	    if (/console=vga\s/) {
		# get rid of any existing serial console clauses
		s#console=com\d\S*##g;
		s#com\d=\S+##g;
		if ($sunit >= 0) {
		    # change vga to appropriate serial device
		    s#console=vga#console=com$comunit com$comunit=$sspeed#;
		}
		push @buffer, $_;
		next;
	    }
	    #
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
	    # Kernel and initrd command lines with serial (ttyS*)
	    #
	    if (/console=ttyS(\d+)/) {
		# get rid of any existing VGA clause
		s#console=tty0##g;
		if ($sunit < 0) {
		    # replace serial with VGA
		    s#console=ttyS\S+#console=tty0#g;
		} else {
		    # fixup serial lines
		    s#console=ttyS\S+#console=ttyS$sunit,$sspeed#g;
		}
		push @buffer, $_;
		next;
	    }
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
	    #
	    # Xen command lines with serial (console=comN, comN=<speed>)
	    #
	    if (/console=com(\d)/) {
		# get rid of any existing VGA clause
		s#console=vga##g;
		if ($sunit < 0) {
		    # replace serial with VGA
		    s#console=com\d\S*#console=vga#g;
		    s#com\d=\S+##g;
		} else {
		    # fixup serial lines
		    s#console=com\d\S*#console=com$comunit#g;
		    s#com\d=\S+#com$comunit=$sspeed#g;
		}
		push @buffer, $_;
		next;
	    }
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188

	    #
	    # Otherwise, just copy
	    #
	    push @buffer, $_;
	}

	seek FILE, 0, 0;
	truncate FILE, 0;

	print FILE @buffer;

	close FILE;

	return;
}

1189 1190 1191 1192 1193 1194
sub fix_sshd_config
{
	my ($imageroot) = @_;
	my $cfile = "$imageroot/etc/ssh/sshd_config";

	print STDERR "Adding security options to SSHD config\n";
1195 1196
	open FILE, "+<$cfile" ||
	    die "Couldn't open $cfile: $!\n";
1197

1198 1199
	my @buffer = ();
	while (<FILE>) {
1200 1201 1202 1203 1204
		s/^Protocol .*//;
		s/^PasswordAuthentication .*//;
		s/^ChallengeResponseAuthentication .*//;
		s/^PermitRootLogin .*//;
		s/^# Emulab.*//;
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
		push @buffer, $_;
	}
	push @buffer, "\n# Emulab config\n";
	push @buffer, "Protocol 2\n";
	push @buffer, "PasswordAuthentication no\n";
	push @buffer, "ChallengeResponseAuthentication no\n";
	push @buffer, "PermitRootLogin without-password\n";

	seek FILE, 0, 0;
	truncate FILE, 0;

	print FILE @buffer;
1217 1218 1219 1220 1221 1222

	close FILE;

	return;
}

1223 1224 1225 1226 1227 1228 1229 1230
#
# Localize the image. We only do this if the MFS we are running in
# has the necessary files.
#
sub localize
{
    my ($imageroot) = @_;

1231
    if (! -e "$LOCALIZED1" && ! -e "$LOCALIZED2") {
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
	return;
    }

    # Check the certs.
    if (! -d "$imageroot/etc/emulab") {
	if (!mkdir("$imageroot/etc/emulab", 0755)) {
	    print STDERR "Failed to mkdir $imageroot/etc/emulab\n";
	    return;
	}
    }
    if (-e "$ETCDIR/emulab.pem") {
	system("cmp -s $ETCDIR/emulab.pem $imageroot/etc/emulab/emulab.pem >/dev/null 2>&1");
	if ($?) {
	    print "Updating $imageroot/etc/emulab/emulab.pem\n";
1246
	    system("cp -pf $ETCDIR/emulab.pem $imageroot/etc/emulab/");
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
	    if ($?) {
		print STDERR "Failed to create $ETCDIR/emulab.pem\n";
		return;
	    }
	}
    }
    if (-e "$ETCDIR/client.pem") {
	system("cmp -s $ETCDIR/client.pem $imageroot/etc/emulab/client.pem >/dev/null 2>&1");
	if ($?) {
	    print "Updating $imageroot/etc/emulab/client.pem\n";
1257
	    system("cp -pf $ETCDIR/client.pem $imageroot/etc/emulab/");
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
	    if ($?) {
		print STDERR "Failed to create $ETCDIR/client.pem\n";
		return;
	    }
	}
    }

    # Check the root keys
    if (-e "/root/.ssh/authorized_keys2") {
	system("cmp -s /root/.ssh/authorized_keys2 $imageroot/root/.ssh/authorized_keys >/dev/null 2>&1");
	if ($?) {
	    print "Updating /root/.ssh/authorized_keys\n";
	    if (! -d "$imageroot/root/.ssh") {
		if (!mkdir("$imageroot/root/.ssh", 0700)) {
		    print STDERR "Failed to mkdir /root/.ssh\n";
		    return;
		}
	    }
1276
	    # copy authorized_keys
1277
	    system("cp -pf /root/.ssh/authorized_keys2 $imageroot/root/.ssh/authorized_keys");
1278 1279 1280 1281 1282 1283 1284 1285 1286
	    if ($?) {
		print STDERR "Failed to create /root/.ssh/authorized_keys\n";
		return;
	    }
	}
    }

    # Check the host keys.
    my $changehostkeys = 0;
1287 1288 1289 1290 1291 1292
    foreach my $kt ("", "dsa_", "ecdsa_", "ed25519_", "rsa_") {
	if (-e "/etc/ssh/ssh_host_${kt}key") {
	    system("cmp -s /etc/ssh/ssh_host_${kt}key $imageroot/etc/ssh/ssh_host_${kt}key >/dev/null 2>&1");
	    if ($?) {
		$changehostkeys = 1;
	    }
1293 1294 1295
	}
    }
    if ($changehostkeys) {
1296
	print "Updating /etc/ssh host keys\n";
1297 1298 1299 1300 1301 1302 1303

	if (! -d "$imageroot/etc/ssh") {
	    if (!mkdir("$imageroot/etc/ssh", 0755)) {
		print STDERR "Failed to mkdir $imageroot/etc/ssh\n";
		return;
	    }
	}
1304
	system("cp -pf /etc/ssh/ssh_host_* $imageroot/etc/ssh/");
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
	if ($?) {
	    print STDERR "Failed to create /etc/ssh/hostkeys\n";
	    return;
	}
    }

    # Check the time zone.
    if (-e "/etc/localtime") {
	system("cmp -s /etc/localtime $imageroot/etc/localtime >/dev/null 2>&1");
	if ($?) {
	    print "Updating /etc/localtime\n";

1317
	    system("cp -pf /etc/localtime $imageroot/etc/localtime");
1318 1319 1320 1321 1322 1323
	    if ($?) {
		print STDERR "Failed to create /etc/localtime\n";
		return;
	    }
	}
    }
1324 1325 1326

    # Check the NTP configuration.
    if (-e "/etc/ntp.conf") {
1327
	print "Updating /etc/ntp.conf\n";
1328

1329 1330 1331 1332 1333
	system("cp -pf /etc/ntp.conf $imageroot/etc/ntp.conf");
	if ($?) {
	    print STDERR "Failed to create /etc/ntp.conf\n";
	    return;
	}
1334

1335 1336 1337 1338 1339
	# XXX cannot use /etc/ntp.drift for Linux
	if (-d "$imageroot/var/lib/ntp") {
	    file_replace_string($imageroot, "/etc/ntp.conf",
				"/etc/ntp.drift",
				"/var/lib/ntp/ntp.drift");
1340 1341
	}
    }
1342 1343
}

1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
sub hardwire_boss_node
{
	my ($imageroot) = @_;
	my $bossnode;

	if (-r $ETCDIR . "/bossnode") {
		local $/;
		open BOSSNODE, $ETCDIR . "/bossnode";
		$bossnode = <BOSSNODE>;
		close BOSSNODE;

		chomp $bossnode;
	}
	else {
		return undef;
	}

	if (!-d "$imageroot/etc/emulab") {
		return undef;
	}

	print "Hardwiring boss to $bossnode\n";
	if (!open BOSSNODE, "$imageroot/etc/emulab/bossnode") {
		print STDERR "Failed to create /etc/emulab/bossnode\n";
		return undef;
	}

	print BOSSNODE "$bossnode\n";
	close BOSSNODE;

	return 1;
}

sub main
{
	my ($root, $old_root) = @_;
	my $imageroot = '/mnt';
	my $new_fstab_root;
	my $new_bootloader_root;
	my $old_bootloader_root;
	my $grub_config;
	my ($kernel, $cmdline, $initrd);
	my $lilo_default;
	my $lilo_commandline = 0;

1389
	my $old_uuid = get_uuid($root);
1390
	set_random_rootfs_uuid($root);
1391
	disable_time_dependent_fsck($root);
1392 1393 1394 1395 1396
	my $fstype = mount_image($root, $imageroot);
	my $uuid = get_uuid($root);
	my $label = get_label($root);
	my $bootloader = guess_bootloader($root);
	my $old_fstab_root = get_fstab_root($imageroot);
1397 1398 1399

	# HACK: there's no simple way to distinguish grub2 from grub
	# by the boot sector.
1400 1401 1402
	if ($bootloader eq 'grub' &&
	    (-f "$imageroot/boot/grub2/grub.cfg" ||
	     -f "$imageroot/boot/grub/grub.cfg")) {
1403 1404 1405
		$bootloader = 'grub2';
	}

1406 1407 1408 1409 1410
	if ($bootloader eq 'lilo') {
		($lilo_default, $kernel, $cmdline, $initrd) =
		    find_default_lilo_entry($imageroot, "/etc/lilo.conf");
	}
	elsif ($bootloader eq 'grub') {
1411
		for (qw#/boot/grub/menu.lst#) {
1412
			if (-f "$imageroot/$_") {
1413 1414 1415 1416 1417 1418 1419 1420
				$grub_config = $_;
				last;
			}
		}

		($kernel, $cmdline, $initrd) =
		    find_default_grub_entry($imageroot, $grub_config);

1421 1422
	}
	elsif ($bootloader eq 'grub2') {
1423
		for (qw#/boot/grub2/grub.cfg /boot/grub/grub.cfg#) {
1424 1425 1426 1427 1428 1429 1430 1431 1432
			if (-f "$imageroot/$_") {
				$grub_config = $_;
				last;
			}
		}

		($kernel, $cmdline, $initrd) =
		    find_default_grub2_entry($imageroot, $grub_config);

1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
	}
	else {
		print STDERR "Couldn't guess bootloader\n";
		return 1;
	}

	for my $token (split /\s+/, $cmdline) {
		next unless ($token =~ /^root=/);
		$token =~ s/^root=//;
		$old_bootloader_root = $token;
		last;
	}

	my ($initrd_does_label, $initrd_does_uuid) = 
	    check_initrd("$imageroot/$initrd");
	my ($mount_does_label, $mount_does_uuid) = 
	    binary_supports_blkid("$imageroot/bin/mount");

	my ($kernel_version, $kernel_has_ide) = 
	    check_kernel("$imageroot/$kernel");

1454
	print "Old root FS uuid: $old_uuid\n";
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
	print "Root FS UUID: $uuid\n";
	print "Root FS LABEL: $label\n";
	print "Installed bootloader: $bootloader\n";
	print "fstab root: $old_fstab_root\n";
	print "kernel: $kernel\n";
	print "kernel version: $kernel_version\n";
	print "kernel has IDE support: $kernel_has_ide\n";
	print "cmdline: $cmdline\n";
	print "initrd: $initrd\n";
	print "initrd blkid: $initrd_does_label $initrd_does_uuid\n";
	print "mount blkid: $mount_does_label $mount_does_uuid\n";
1466
	print "old bootloader root: $old_bootloader_root\n";
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496

	if ($uuid && $mount_does_uuid) {
		$new_fstab_root = "UUID=$uuid";
	}
	elsif ($label && $mount_does_label) {
		$new_fstab_root = "LABEL=$label";
	}
	elsif (kernel_version_compare($kernel_version, '2.6.21') < 0 ||
	       $kernel_has_ide) {
		$new_fstab_root = $old_root;
	}
	else {
		$new_fstab_root = $root;
	}

	if ($uuid && $initrd_does_uuid) {
		$new_bootloader_root = "UUID=$uuid";
	}
	elsif ($label && $initrd_does_label) {
		$new_bootloader_root = "LABEL=$label";
	}
	elsif (kernel_version_compare($kernel_version, '2.6.21') < 0 ||
	       $kernel_has_ide) {
		$new_bootloader_root = $old_root;
	}
	else {
		$new_bootloader_root = $root;
	}

	print "Rewriting /etc/fstab to use '$new_fstab_root' as root device\n";
1497
 	file_replace_string($imageroot, '/etc/fstab', $old_fstab_root,
1498
	                         $new_fstab_root);
1499 1500
	file_replace_string($imageroot, '/etc/fstab', $old_uuid,
	                         $uuid);
1501 1502 1503 1504 1505 1506 1507

	print "Rewriting $bootloader config to use '$new_bootloader_root' as root device\n";
	if ($bootloader eq 'lilo') {
		rewrite_lilo_config($imageroot, $old_bootloader_root, $new_bootloader_root);
		$lilo_commandline = set_runlilo_flag($imageroot, $lilo_default, $new_bootloader_root);
	}
	elsif ($bootloader eq 'grub') {
1508 1509 1510 1511
		print "grub config is $grub_config\n";
		#file_replace_string($imageroot, $grub_config, $old_bootloader_root,
		 #                        $new_bootloader_root);
		file_replace_string($imageroot, $grub_config, $old_uuid, $uuid);
1512 1513
		set_grub_root_device($imageroot, $grub_config, $root);
	}
1514
	elsif ($bootloader eq 'grub2') {
1515
		file_replace_string($imageroot, $grub_config, $old_bootloader_root,
1516
		                         $new_bootloader_root);
1517
		file_replace_string($imageroot, $grub_config, $old_uuid, $uuid);
1518
		file_replace_string($imageroot, $grub_config, $old_uuid, $uuid);
1519 1520
		set_grub2_root_device($imageroot, $grub_config, $root);
	}
1521
	fix_grub_dom0mem($imageroot, $grub_config);
1522
	fix_console($imageroot, $bootloader, $grub_config);
1523

1524 1525 1526
	fix_swap_partitions($imageroot, $root,
		$kernel_has_ide ? $old_root : undef );

1527
	update_random_seed($imageroot);
1528
	localize($imageroot);
1529
	fix_sshd_config($imageroot);
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
	hardwire_boss_node($imageroot);

	# Run any postconfig scripts
	if (-x $BINDIR . '/osconfig') {
		print "Checking for dynamic client-side updates to slice...\n";
		system($BINDIR . "/osconfig -m $imageroot -M \"-t $fstype\" -f $fstype " .
		       "-D $root -s Linux postload");
	}

	`umount $imageroot`;

	if ($lilo_commandline) {
		$root =~ m/^(.*)(\d+)$/;
		my $disk = $1;
		my $part = $2;

		system("$BINDIR/groklilo -c \"$lilo_commandline\" $part $disk");
		if ($?) {
			print STDERR "Failed to set LILO command line\n";
			return 1;
		}
	}

	return 0;
}

main(@ARGV);