#!/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");
  $options=getopt($shortopts, $longopts);
  $group=$argv[$argc-1];

  
  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);
$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";
}
?>
