/*
 * call-seq:
 * conn.simple_bind(dn=nil, password=nil)  => self
 * conn.simple_bind(dn=nil, password=nil) { |conn| }  => nil
 *
 * Bind an LDAP connection, using the DN, +dn+, and the credential, +password+.
 * If a block is given, +self+ is yielded to the block.
 */
VALUE
rb_ldap_conn_simple_bind_s (int argc, VALUE argv[], VALUE self)
{
  RB_LDAP_DATA *ldapdata;

  VALUE arg1, arg2;
  char *dn = NULL;
  char *passwd = NULL;

  Data_Get_Struct (self, RB_LDAP_DATA, ldapdata);
  if (!ldapdata->ldap)
    {
      if (rb_iv_get (self, "@args") != Qnil)
        {
          rb_ldap_conn_rebind (self);
          GET_LDAP_DATA (self, ldapdata);
        }
      else
        {
          rb_raise (rb_eLDAP_InvalidDataError,
                    "The LDAP handler has already unbound.");
        }
    }

  if (ldapdata->bind)
    {
      rb_raise (rb_eLDAP_Error, "already bound.");
    };
  switch (rb_scan_args (argc, argv, "02", &arg1, &arg2))
    {
    case 0:
      break;
    case 1:
      if (arg1 == Qnil)
        {
          dn = NULL;
        }
      else
        {
          dn = StringValueCStr (arg1);
        }
      break;
    case 2:
      if (arg1 == Qnil)
        {
          dn = NULL;
        }
      else
        {
          dn = StringValueCStr (arg1);
        }
      if (arg2 == Qnil)
        {
          passwd = NULL;
        }
      else
        {
          passwd = StringValueCStr (arg2);
        }
      break;
    default:
      rb_bug ("rb_ldap_conn_simple_bind_s");
    }

  ldapdata->err = ldap_simple_bind_s (ldapdata->ldap, dn, passwd);
  Check_LDAP_Result (ldapdata->err);
  ldapdata->bind = 1;

  if (rb_block_given_p ())
    {
      rb_ensure (rb_yield, self, rb_ldap_conn_unbind, self);
      return Qnil;
    }
  else
    {
      return self;
    };
}