#!/usr/bin/perl

use strict;
use warnings;

use Email::Valid::Loose qw( );

use Piny::Config;
use Piny::User;

my ( $email, $username, $password );

# Configure the strictness of our email checks.
my $checker = Email::Valid::Loose->new
  ( "-fqdn"        => 1
  , "-fudge"       => 0
  , "-local_rules" => 0
  , "-mxcheck"     => 1
  , "-tldcheck"    => 0
  );

# Check to see if we're in batch mode.
if ( scalar @ARGV == 3 and $ARGV[0] eq "--batch" ) {

  ( undef, $email, $username ) = @ARGV;

  $email = $checker->address( $email );

  chomp( $password = <STDIN> );

# Some other incorrect argument arrangement.
} elsif ( scalar @ARGV ) {
  print "You can't pass any arguments to this script!\n";
  exit 2;
} else {

  # If they didn't provide a terminal definition, then assume xterm.
  # Everybody emulates xterm to at least a basic extent.
  if ( not exists $ENV{"TERM"} ) {
    $ENV{"TERM"} = "xterm";
    print "I don't know what terminal you're using; guessing xterm...\n";
  };

  # Disable buffering.
  $|++;

  my ( $password2 );

  while ( 1 ) {

    print "Email address to associate with new user: ";
    chomp ( $email = <STDIN> );

    if ( $email eq "" ) {
      print "You must provide an email address!\n";
      next;
    };

    $email = $checker->address( $email );
    if ( not defined $email ) {
      print "Please, at least pretend to provide a valid email address.\n";
      next;
    };

    last;

  };

  while ( 1 ) {

    print "Desired username: ";
    chomp ( $username = <STDIN> );

    if ( $username eq "" ) {
      print "You have to enter a username!\n";
      next;
    };

    if ( $username =~ /^(git|iki)-/ ) {
      print "Your username cannot start with git- or iki-!\n";
      next;
    };

    if ( $username !~ /^[a-zA-Z][a-zA-Z0-9_.-]{0,30}$/ ) {
      print "Usernames must be less than 32 bytes long, consist only of letters, digits, underscores, periods, and dashes, and must start with a letter. Usernames are case sensitive.\n";
      next
    };

    last;

  };

  while ( 1 ) {

    system( "stty", "-echo" );
    print "Desired password: ";
    chomp ( $password = <STDIN> );
    print "\nRetype password: ";
    chomp ( $password2 = <STDIN> );
    print "\n";
    system( "stty", "echo" );

    if ( $password ne $password2 ) {
      print "Provided passwords do not match; try again.\n";
      next;
    };

    if ( $password eq "" ) {
      print "You have to enter a password!\n";
      next;
    };

    last;

  };

};

# All the correctness checks should be repeated here. There are multiple
# pathways to get to this point, but only a single path from here on down.
if ( not defined $email or $email eq "" )            { print "Email address is undefined!\n"; exit 3; };
if ( not defined $username or $username eq "" )      { print "Username is undefined!\n"; exit 3; };
if ( $username =~ /^(git|iki)-/ )                    { print "Username must not begin with git- or iki-!\n"; exit 3; };
if ( $username !~ /^[a-zA-Z][a-zA-Z0-9_.-]{0,30}$/ ) { print "Usernames must be less than 32 bytes long, consist only of letters, digits, underscores, periods, and dashes, and must start with a letter. Usernames are case sensitive.\n" };
if ( not defined $password or $password eq "" )      { print "Password is undefined!\n"; exit 3; };

# Here on down is the actual creation code.

my $config = Piny::Config->new( );
my $dest = $config->piny_adminemail;

unless( open( MAIL, "|/usr/lib/sendmail -t" ) ) {
  die "Couldn't execute sendmail: $!\n";
};
print MAIL <<END;
To: $dest
Subject: Creating piny account $username
Content-type: text/plain; charset=us-ascii

A new piny account ``$username'' has been created.

Email: $email
END
close( MAIL );

my @saltchars =
  ( 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
  , 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
  , '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
  , '.', '/'
  );

my $salt = "\$6\$";

foreach my $n ( 1 .. 16 ) {
  $salt .= $saltchars[int ( rand ( scalar @saltchars ) )];
};

$salt .= "\$";

my $crypt = crypt( $password, $salt );

my $ret = system( "/usr/sbin/useradd", "-c", "$email", "-k", "/var/empty", "-g", "users", "-m", "-p", $crypt, "-s", "/usr/bin/pinyshell", $username );

if ( $ret ) {
  print "An error occured creating the user; most likely, that username is already taken.\n";
  exit 1;
};

my $u = Piny::User->new( $username );

open( GITCONFIG, ">", $u->home . "/.gitconfig" ) or die "Could not open .gitconfig for new user: $!\n";
print GITCONFIG <<END;
[user]
	email = $email
END
close( GITCONFIG );

chown( $u->uid, (getgrnam("users"))[2] , $u->home . "/.gitconfig" );

print "Your user has been created. Try logging in!\n";

exit 0;