#!/bin/sh
#
# Script to reset admin user's password

# Ensure ZEUSHOME is setup to point to our installation
if [ -z "$ZEUSHOME" ]
then
    # Have a good guess, we live in $ZEUSHOME/zxtm/bin
    OLD_PWD=`pwd`
    cd `dirname $0`/../..
    ZEUSHOME=`pwd`
    export ZEUSHOME
    cd $OLD_PWD
fi

if [ ! -d "$ZEUSHOME/zxtm" ]
then
   echo "reset-admin-password: FATAL: ZEUSHOME not set"
   exit 1
fi

exec $ZEUSHOME/perl/miniperl -Tx $0 ${1+"$@"}

#!perl -w
#line 26

=head1 Reset Admin Password

Resets the admin password to a new value. If the 'admin'
user account does not exist then one is created.

=cut

BEGIN {
   ($ENV{"ZEUSHOME"}) = ( $ENV{"ZEUSHOME"} =~ m@^(.*)$@ ); # Untaint

   unshift( @INC,
      "$ENV{ZEUSHOME}/zxtmadmin/lib/perl",
      "$ENV{ZEUSHOME}/admin/lib/perl",
      "$ENV{ZEUSHOME}/zxtm/lib/perl",
      "$ENV{ZEUSHOME}/perl"
   );

   $ENV{PATH} = '/bin/:/usr/bin';
}

use strict;
use Zeus::ZInstall::Common;
use Zeus::ZXTM::StorageManager;
use Zeus::ZXTM::UsersConfig;
use Zeus::ZXTM::AccessControl qw( checkPassword );
use Zeus::ZXTM::LogUtils qw( logAuditEvent );
use Zeus::Session qw( createEphemeralSession );

my $arg = $ARGV[0];
if( $arg ) {
   print <<'EOF';
   This script allows you to reset the 'admin' user's password to the one
   supplied. If the admin user does not exist on the system then it will
   be created.

   The script should be run with no arguments.
EOF
   exit( 0 );
}

print "\n";

if ( $< ) { die "$0 must be run as root\n" }

my $password = "";
while( 1 ) {
   $password = Zeus::ZInstall::Common::get_password( "Enter a new password" );

   if( !$password ) {
      # Unlikey to happen, but just in case...
      exit 0;
   }

   # checkPassword will only check the quality of the password as no
   # username is supplied.
   my( $ret, $reason ) = checkPassword( $password );
   if( $ret ) {
      last;
   }

   print "\nError: $reason\n\n";
}


# Change the admin password (will create the user if it doesn't already exist)
my $storage = new Zeus::ZXTM::StorageManager();
my $users_config = $storage->getUsersConfig();

# Note whether the 'admin' user already existed before we came along.
my $admin_existed = $users_config->userExists( "admin" );

$users_config->setUserDetails(
  "admin" => {
     password => $password,
     group    => "admin"
   }
);

my $session = createEphemeralSession();
logAuditEvent( 'event' => 'adminpasswordreset', 'session' => $session );

if( $admin_existed ) {
   print " The admin password has been changed.\n";
} else {
   print "A user account named 'admin' has been created with the supplied password.\n";
}

exit 0;
