#!/usr/bin/perl

$crypt_only = 0;
if ($ARGV[0] eq "--crypt-only") {
    $crypt_only = 1;
    shift @ARGV;
}

$root = "";
if ($ARGV[0] eq  "--root") {
    $root = $ARGV[0];
    shift @ARGV;
}

sub randchar {
    $i = int(rand(62));

    if ($i < 26) {
	return chr(ord("A") + $i);
    }
    $i = $i - 26;
    if ($i < 26) {
	return chr(ord("a") + $i);
    }
    $i = $i - 26;

    return chr(ord("0") + $i);
}

srand(time());
$salt = &randchar . &randchar . &randchar;

$newpw = crypt($ARGV[0], $salt);

if ($crypt_only) {
    print "$newpw\n";
    exit 0;
}

$lines = "";
open(PASSWD, "<$root/etc/passwd") || die("can't open $root/etc/passwd");
while (<PASSWD>) {
    if (/^root:/) {
	($rest) = /^root:[^:]*:(.*)$/;
	$lines = $lines . "root:$newpw:" . $rest . "\n";
    } else {
	$lines = $lines . $_;
    }
}

close(PASSWD);

open(PASSWD, ">$root/etc/passwd") || die("can't create new $root/etc/passwd");
print PASSWD $lines;
close (PASSWD);

