// Reconcile DEP-5 debian/copyright to licensecheck
//
// Copyright : 2024 P Blackman
// License   : BSD-2-clause
//
// Test for false positive on some SPDX licences

unit spdx;
{$mode delphi}

interface

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


implementation uses StrUtils, support;

// Extract license short string, expecting an SPDX license
function GetFileLicense (Fname : AnsiString) : String;
const maxlines : Integer = 100;
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', line, 1);

            if lpos > 0 then
            begin
				// Could make more generic, with a conversion table, SPDX -> Dep5
				if IsWordPresent ('LGPL-2.1-or-later', line, WhiteSpace) then
					result := 'LGPL-2.1+';
            
                lines := maxlines // terminate loop
            end
            else
                lines := lines + 1;
        end;
        Close (lfile);
    end;
end;

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

begin
    result := false;

    if (Dep5 = 'LGPL-2.1+') and (Actual = 'LGPL-2.1') then
    begin
        License := GetFileLicense (FName);
        if (License  <> '') and (license [length(License)] = '+') then
            result := true;
    end;
end;

end.
