program DatedBackup;
{$mode objfpc}{$H+}
{ Copies one file into backups/ under a name with the date and time }
uses
  SysUtils, Classes;
var
  Source, Target: string;
  InFile, OutFile: TFileStream;
begin
  Source := ParamStr(1);
  if not FileExists(Source) then
  begin
    WriteLn('There is no file ', Source);
    Halt(1);
  end;
  ForceDirectories('backups');
  Target := 'backups/' + ChangeFileExt(ExtractFileName(Source), '')
    + FormatDateTime('-yyyy-mm-dd-hhnnss', Now) + ExtractFileExt(Source);
  if FileExists(Target) then
  begin
    WriteLn('There is ', Target, ' already');
    Halt(1);
  end;
  InFile := TFileStream.Create(Source, fmOpenRead or fmShareDenyWrite);
  try
    OutFile := TFileStream.Create(Target, fmCreate);
    try
      WriteLn(OutFile.CopyFrom(InFile, 0), ' bytes to ', Target);
    finally
      OutFile.Free;
    end;
  finally
    InFile.Free;
  end;
end.
