#!/bin/sh
# -*- perl -*-
# This code allows us to start perl from our path or an environment variable
# rather than hardcoding a path into the #! line.  It works from sh or csh.
(exit $?0) && eval 'exec ${QPERLQ-perl} -x $0 ${1+"$@"}'
if (! $?QPERLQ) setenv QPERLQ perl
exec $QPERLQ -x $0 $argv:q

#!/usr/local/bin/perl -w
#
# $Id: passwdcrypt,v 1.1 1997/12/20 18:20:21 ejb Exp $
# $Source: /home/ejb/scripts/RCS/passwdcrypt,v $
# $Author: ejb $
#

require 5.002;
use strict;

my $whoami = ($0 =~ m,([^/\\]*)$,) ? $1 : $0;
#my $dirname = ($0 =~ m,(.*)[/\\][^/\\]+$,) ? $1 : ".";

$| = 1;

my $salt = undef;
my $passwd = undef;
my $saltlen = 2;

if (@ARGV > 2)
{
    &usage();
}

if (@ARGV == 1)
{
    if (length($ARGV[0]) == $saltlen)
    {
	$salt = $ARGV[0]
    }
    else
    {
	$passwd = $ARGV[0];
    }
}
elsif (@ARGV == 2)
{
    if ((length($ARGV[0]) != $saltlen) && (length($ARGV[1]) != $saltlen))
    {
	&usage();
    }
    elsif (length($ARGV[0]) == $saltlen)
    {
	($salt, $passwd) = @ARGV;
    }
    else
    {
	($passwd, $salt) = @ARGV;
    }
}
elsif (@ARGV != 0)
{
    &usage();
}

if (! defined $salt)
{
    $salt = &rand_salt();
}
if (! defined $passwd)
{
    $passwd = &read_password();
}

print crypt($passwd, $salt), "\n";



sub read_password
{
    my $match = 0;
    system("stty -echo");
    my $try1 = "";

    while (! $match)
    {
	print "Password: ";
	chop($try1 = <STDIN>);
	print "\nRepeat password: ";
	chop(my $try2 = <STDIN>);
	system("stty echo");
	print "\n";

	if ($try1 eq $try2)
	{
	    $match = 1;
	}
	else
	{
	    print "Mismatch -- try again.\n";
	}
    }

    $try1;
}

sub rand_salt
{
    my @salt_choices = ('a'..'z', 'A'..'Z', '0'..'9', '.', '/');
    my $slen = scalar(@salt_choices);
    my $t = ((time % 10000) * $$);
    $t %= ($slen ** 2);
    join('', @salt_choices[$t / $slen, $t % $slen]);
}

sub usage
{
    warn "Usage: $whoami [salt] [password]\n";
    die "  salt is two characters.\n";
}
