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

unit spdx;
{$mode delphi}

interface

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


implementation uses StrUtils, support;

// Extract license short string, testing for an SPDX style license
function GetFileLicense (Fname : AnsiString) : String;
const MaxLines : Integer = 200;
var Lines : Integer;
    Line  : AnsiString;
    Lfile : Text;

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

            // Could make more generic, with a conversion table, SPDX -> Dep5
            if IsWordPresent ('LGPL-2.1-or-later', Line, WhiteSpace+['''']) then
                result := 'LGPL-2.1+'
            else
            if IsWordPresent ('LGPL-2.1+', Line, WhiteSpace) then
                result := 'LGPL-2.1+'
            else
            if IsWordPresent ('GPL-2.0-or-later', Line, WhiteSpace) then
                result := 'GPL-2+'
            else
            if IsWordPresent ('GPL-3.0-or-later', Line, WhiteSpace) then
                result := 'GPL-3+';

            if result = '' then
                inc (Lines)
            else
                Lines := MaxLines; // Exit loop
        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')
    or (Dep5 = 'GPL-2+')    and (Actual = 'GPL-2')
    or (Dep5 = 'GPL-3+')    and (Actual = 'GPL-3') then
    begin
        License := GetFileLicense (FName);
        if (License  <> '') and (license [length(License)] = '+') then
            result := true;
    end;
end;

end.
