program drvtool;

uses
  Windows, SysUtils, DevDrv, CmdLine;

const
  DrvOptCount = 7;

  oiDevName = 1;
  oiLoad = 2;
  oiStart = 3;
  oiKill = 4;
  oiUnload = 5;
  oiQuery = 6;
  oiHelp = 7;

  DrvOpts: array[1..DrvOptCount] of TOptionRec = (
    (OptionName:' '; OptionDesc:'name of the device driver';
      Flag:0; Present: false; Option: otString; Param: ''),
    (OptionName:'l'; OptionDesc:'load the driver';
      Flag: 0; Present: false; Option: otBool; OnOff: false),
    (OptionName:'r'; OptionDesc:'run (start) the driver (if not loaded, load first)';
      Flag: 0; Present: false; Option: otBool; OnOff: false),
    (OptionName:'k'; OptionDesc:'kill (stop) the driver';
      Flag:0; Present: false; Option: otBool; OnOff: false),
    (OptionName:'u'; OptionDesc:'unload the driver (if running, stop first)';
      Flag:0; Present: false; Option: otBool; OnOff: false),
    (OptionName:'q'; OptionDesc:'query the driver status'; Flag:0; Present: false;
      Option: otBool; OnOff: true),
    (OptionName:'?'; OptionDesc:'print possible command line options';
      Flag:0; Present: false; Option: otBool; OnOff: false)
  );

procedure Run;
var
  dv: TDevDrv;
  r: integer;
  state: DWORD;
  unloaded: boolean;
  dn: string;
begin
  dn := DrvOpts[oiDevName].Param;
  if dn = '' then begin
    Writeln('Device name not specified.');
    exit;
  end;

  r := 0;
  unloaded := false;

  dv := TDevDrv.Create(dn, 0);

  if DrvOpts[oiLoad].OnOff or DrvOpts[oiStart].OnOff then
    r := dv.CheckDeviceLoaded;

  if DrvOpts[oiStart].OnOff and (r = 0) then
    r := dv.CheckDeviceStarted;

  if (DrvOpts[oiKill].OnOff or DrvOpts[oiUnload].OnOff) and (r = 0) then
    r := dv.CheckDeviceStopped(true, false);

  if DrvOpts[oiUnload].OnOff then begin
    r := dv.CheckDeviceUnloaded;
    if r = 0 then
      unloaded := true;
  end;

  if (r = 0) and DrvOpts[oiQuery].OnOff and (not unloaded) then begin
    r := dv.GetState(state);
    if r = 0 then
      writeln('Driver state: ' + dv.GetStateMsg(state));
  end;

  if unloaded then
    writeln('Driver unloaded.');
  if r <> 0 then
    writeln({'Error: ' + }dv.ErrorLookup(r));
{  sp.Free;}
end;

begin
  if ParamCount = 0 then begin
    Writeln('drvtool v1.00 - tool for controlling Window NT device drivers');
    Writeln('                based on gwiopm - www.wideman-one.com');
    Writeln('');
{    Writeln('http://jindrich.com/freeware/drvtool.zip');
    Writeln('');}
    Writeln('Usage: drvtool [-option] [drvdir]drvname[.sys]');
    Writeln('       drvtool -? for list of options');
    Writeln('');
  end else begin
    if ProcessCommandLine(@DrvOpts, DrvOptCount) then begin
      if DrvOpts[oiHelp].OnOff then
        PrintOptionsHelp
      else
        Run;
    end else begin
      Writeln('Invalid command line.');
    end;
  end;
end.
