<?php

require_once 'globals.php';


class NewUserCommand extends CConsoleCommand
{
  public function run($args)
  {
    if(count($args) < 2)
    {
      echoln("yiic newuser <username> <password> [field=value [...]]");
      echo("Accepted fields are: ");
      foreach(User::model()->attributeNames() as $index => $attr)
      {
        if($index>0)
          echo(", ");
        echo("$attr");
      }
      return;
    }
    $username = $args[0];
    $password = $args[1];

    $model = new User();

    $model->username = $username;
    $model->password = $model->hashPassword($password);
    $model->password_repeat = $model->password;
    $model->password_last_update = date("Y-m-d H:i:s");
    $model->apikey = rand_str('0123456789QAZWSXEDCRFVTGBYHNUJMIKOLP', 32);
    $model->create_time = DateHelper::ensureObjectEx(null);
    $model->update_time = DateHelper::ensureObjectEx(null);
    $model->email = "$username@unknown.com";
    $model->superuser = true;
    $model->status = User::STATUS_ACTIVE;
    $model->first_name = null;
    $model->last_name = null;
    $model->matriculation_number = null;
    $model->password_timeout = null;
    $model->can_change_password = true;
    $model->refresh_password_at_first_login = false;

    for($i=2;$i<count($args);$i++)
    {
      $arg = $args[$i];
      $splitIndex = strpos($arg, "=");
      if($splitIndex!==false)
      {
        $field = substr($arg, 0, $splitIndex);
        $value = substr($arg, $splitIndex + 1);

        echoln("SET $field=$value");
        $model->$field = $value;
      }
      else
      {
        echoln("SKIPPED $arg");
      }
    }

    if($model->insert())
      echoln("User created");
    else
      echoln("User NOT created, ERROR");
  }
}
