#!/usr/bin/php
<?php
(file_exists("/usr/share/mcms/user_management_functions.php")) or die("Unable to open /usr/share/mcms/user_management_functions.php");
(include("/usr/share/mcms/user_management_functions.php")) or die("Unable to open /usr/share/mcms/user_management_functions.php");

function parseargs($argc, $argv){
  global $gecos, $uid, $gid, $groups, $homedir, $shell, $password, $forcepwchange, $quiet, $comment, $group, $randpass, $verbose;
  if($argc<2 || in_array($argv[1],array('--help','-h','-help','-?'))) {
    echo "Usage: $argv[0] [options] GROUP\n";
    echo "  -g, --gid GID                 group ID of the new account (default: auto)\n";
    echo "  -q, --quiet                   do not print summary of group addition\n";
    echo "  -h, --help                    print this help message\n";
    exit(254);
  }
  $shortopts="g:qv";
  $longopts=array("gid:", "quiet");
  $opt_index=null;
  $options=getopt($shortopts, $longopts, $opt_index);
  if ($opt_index+1 < $argc) {
    echo "Too many parameters specified index $opt_index argc $argc\n";
    usage();
  }
  if(isset($argv[$opt_index])) {
    $group=$argv[$opt_index];
  } else {
    echo "GROUP not provided\n";
    usage();
  }
  if ( $group[0] == "-" ) {
    echo "Invalid group name, starts with \"-\"\n";
    usage();
  }
  
  if (isset($options['g']) || isset($options['gid']) ) {
    if (isset($options['g'])) {
      $gid=(int)$options['g'];
    } else {
      $gid=(int)$options['gid'];
    }
    $gidtest=popen("getent group $gid | awk 'BEGIN{FS=\":\"}{print $3}'","r");
    $gidresult=(int)trim(fgets($gidtest));
    if($gid==$gidresult) {
      echo "Specified gid $gid already exists!\n";
      exit(3);
    }
  } else {
    $gid="auto";
  }

  if (isset($options['q']) || isset($options['quiet']) ) {
    $quiet=true;
  } else {
    $quiet=false;
  }

  if (isset($options['v']) || isset($options['verbose']) ) {
    $quiet=false;
    $verbose=true;
  } else {
    $verbose=false;
  }
}  //end parseargs

//execution starts here
init();
parseargs($argc,$argv);

$groupcheck=popen("getent group $group","r");
$groupfound=trim(fgets($groupcheck,4096));
if($groupfound!="") {
  echo "Group $group already exists\n";
  exit(5);
}

ldap_add_group($group,$gid);
flush_nscd();
$gidp=popen("getent group $group | awk 'BEGIN{FS=\":\"}{print $3}'", "r");
if ( $gidp == FALSE ) {
  echo "Failed to add group $group\n";
  exit(3);
} else {
  $gidused=trim(fgets($gidp,4096));
  pclose($gidp);
}

if(!$quiet) {
  echo "Created group $group with gid: $gidused\n";
}
?>
