// Reconcile DEP-5 debian/copyright to licensecheck
//
// Copyright : 2024 P Blackman
// License   : BSD-2-clause
//
// Test for false positive on GPL licences when in spdx mode

unit spdx2;
{$mode delphi}

interface

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


implementation uses StrUtils, support, options;

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

            if lpos > 0 then
            begin
                if IsWordPresent ('GPL-2.0-or-later', line, WhiteSpace) then
                    result := 'GPL-2.0-or-later'
                else
                if IsWordPresent ('GPL-3.0-or-later', line, WhiteSpace) then
                    result := 'GPL-3.0-or-later';

                lines := maxlines // terminate loop
            end
            else
                lines := lines + 1;
        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 not Option_SPDX then
        // test not relevant
    else
    if (Dep5 = 'GPL-2.0-or-later') and (Actual = 'GPL-2')
    or (Dep5 = 'GPL-3.0-or-later') and (Actual = 'GPL-3') then
    begin
        License := GetFileLicense (FName);
        if (License  <> '') and (License = Dep5) then
            result := true;
    end;
end;

end.
