#!/usr/bin/perl

# Copyright (c) 2010 Peter Palfrader

# Resets the password for a kerberos principal given on the command line.
# If the principal does not exist, try to create them.

use strict;
use Heimdal::Kadm5;
use Getopt::Long;
use English;
use String::Random;

my $USAGE = "Usage: $PROGRAM_NAME [--admin=<admin>] [--keytab=<file>] <principal>\n";

sub getname() {
	my $username = getpwuid($UID);
	die "Cannot get current username\n" unless defined $username;
	return $username;
};

my $params;
Getopt::Long::config('bundling');
GetOptions (
	'--help'	=> \$params->{'help'},
	'--admin=s'	=> \$params->{'admin'},
	'--keytab=s'	=> \$params->{'keytab'},
) or die ($USAGE);

if ($params->{'help'}) {
	print $USAGE;
	exit (0);
};

die $USAGE if (scalar @ARGV != 1);
my $name = shift @ARGV;

unless (defined $params->{'admin'}) {
	$params->{'admin'} = getname().'/admin';
};
unless (defined $params->{'keytab'}) {
	$params->{'keytab'} = '/etc/userdir-ldap/keytab.'.getname();
};

my $client = Heimdal::Kadm5::Client->new(
	Principal => $params->{'admin'},
	Keytab => $params->{'keytab'}
	);
die "Unable to get Heimdal Client object.\n" unless defined $client;


my $password = '844u6MrG0gTS';

my $rnd = new String::Random;
my $password = $rnd->randregex('[a-zA-Z0-9]{16}');

my $principal = $client->getPrincipal($name);
unless (defined $principal) {
	print "Principal appears to not exist.  Trying to add.\n";
	$principal = $client->makePrincipal($name);
	my $ret = $client->createPrincipal($principal, $password, undef);
	die "Failed to create principal $name.\n" unless ($ret);
	print "Created principal $name with password '$password'.\n";
} else {
	my $ret = $client->changePassword($name, $password);
	die "Failed to change password for $name.\n" unless ($ret);
	print "Changed password of principal $name to '$password'.\n";
};
