// 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+';

            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')
    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.
