procedure WriteCommandLine;
begin
  Output.Writeln('');
  Output.Writeln('Usage:');
  Output.Writeln('');
  Output.Writeln('nxCommand.exe /Type:cmdExecScript /Script:backup.nxscript /Source:srcalias|srcpath /Destination:destalias|destpath');
  Output.Writeln('');
  Output.Writeln('');
end;

Procedure DoOpenTable( aSender : TnxBackupController; aTable : TnxTable; aIsSource : Boolean);
begin
  if aIsSource then
  begin
    Output.Writeln('  Backing up table "'+aTable.TableName+'"');
    Output.Flush;
  end;
end;

var
  btBackupSession: TnxSession;
  btSourceDatabase: TnxDatabase;
  btTargetDatabase: TnxDatabase;
  btBackupController: TnxBackupController;
  Source, Destination: string;
begin
  if CmdParams.IndexOf('/?')>-1 then
  begin
    WriteCommandLine;
    exit;
  end;

  Source:=Cmdparams.Values['/Source'];
  If Source='' Then
  Begin   
    Writecommandline;
    Raise(-1, 'No Source Specified');
  End;
  
  Destination:=Cmdparams.Values['/Destination'];
  If Destination='' Then
  Begin   
    WriteCommandline;
    Raise(-1, 'No Destination Specified');
  End;

  Output.WriteLn('');
  Output.WriteLn('Started Backup from "'+Source+'" to "'+Destination+'" ...');
  Output.WriteLn('');
  Output.Flush;
  btBackupSession := TnxSession.Create(nil);
  btSourceDatabase := TnxDatabase.Create(nil);
  btTargetDatabase := TnxDatabase.Create(nil);
  btBackupController := TnxBackupController.Create(nil);
  try
    btBackupController.OnAfterTableOpen := @DoOpenTable;
    btBackupSession.ServerEngine := ServerEngine;
    btBackupSession.Active := True;

    btSourceDatabase.Session := btBackupSession;
    if pos('\', Source)>0 then
      btSourceDatabase.AliasPath := Source
    else
      btSourceDatabase.AliasName := Source;
    btSourceDatabase.Active := True;

    btTargetDatabase.Session := btBackupSession;
    if pos('\', Destination)>0 then
      btTargetDatabase.AliasPath := Destination
    else
      btTargetDatabase.AliasName := Destination;
    btTargetDatabase.Active := True;

    btBackupController.OriginalDatabase := btSourceDatabase;
    btBackupController.CloneDatabase := btTargetDatabase;
    btBackupController.SourceThreadPriority := 0; // values allowed -15..15
    btBackupController.Active := True;
    btBackupController.Backup;
    Output.WriteLn('');
    Output.WriteLn('... Success!');
  finally
    btSourceDatabase.Active := false;
    btTargetDatabase.Active := false;
    btBackupSession.CloseInactiveTables;
    btBackupSession.CloseInactiveFolders;
    btBackupController.Free;
    btTargetDatabase.Free;
    btSourceDatabase.Free;
    btBackupSession.Free;
  end;
end.
