// Reconcile DEP-5 debian/copyright to licensecheck
//
// Copyright : 2024-2025 P Blackman
// License   : BSD-2-clause
//
// Check if Dep5 license string matches an SPDX license header in the file

unit spdx2;
{$mode delphi}

interface

function CheckSPDX2 (Fname : AnsiString; Dep5,  Actual : String) : Boolean;


implementation uses SysUtils, StrUtils, support, options;

// Extract license short string for an SPDX license
function GetFileLicense (Fname : AnsiString) : String;
const MaxLines : Integer = 60;
      SPDX_Str : String = 'SPDX-License-Identifier:';
var Lines,
    Lpos : Integer;
    Line : AnsiString;
    Lfile : Text;

begin
    result := '';
    Lines := 0;
    if OpenFile (FName, Lfile) then
    begin
        while not EOF (Lfile) and (Lines < MaxLines) do
        begin
            readln (Lfile, Line);
            Lpos := NPos (SPDX_Str, Line, 1);

            if lpos > 0 then
            begin
                result := Trim (MidStr (Line, LPos + Length (SPDX_Str), 60 ) );
                Lines  := MaxLines // terminate loop
            end
            else
                inc (Lines);
        end;
        Close (Lfile);
    end;
end;

// Return true if Actual is match for d/copyright
function CheckSPDX2 (Fname : AnsiString; Dep5, Actual : String) : Boolean;
var License : String;

begin
    result := false;

    if Dep5 <> Actual then
    begin
        License := GetFileLicense (FName);
        if (License  <> '') and (CompareText (License, Dep5) = 0) then
            result := true;
    end;
end;

end.
