module Process

def logon_user(user, domain, passwd, type, provider = LOGON32_PROVIDER_DEFAULT)

def logon_user(user, domain, passwd, type, provider = LOGON32_PROVIDER_DEFAULT)
  token = FFI::MemoryPointer.new(:ulong)
  bool = LogonUserW(
    user,                       # User
    domain,                     # Domain
    passwd,                     # Password
    type,                       # Logon Type
    provider,                   # Logon Provider
    token                       # User token handle
  )
  unless bool
    if (FFI.errno == ERROR_LOGON_TYPE_NOT_GRANTED) && (type == LOGON32_LOGON_BATCH)
      user_utf8 = user.encode( "UTF-8", invalid: :replace, undef: :replace, replace: "" ).delete("\0")
      raise SystemCallError.new("LogonUserW (User '#{user_utf8}' must hold 'Log on as a batch job' permissions.)", FFI.errno)
    else
      raise SystemCallError.new("LogonUserW", FFI.errno)
    end
  end
  token.read_ulong
end