// 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, test for an SPDX license
function GetFileLicense (Fname : AnsiString) : String;
const MaxLines : Integer = 100;
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+';

            inc (Lines);
        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.
