// Reconcile DEP-5 debian/copyright to licensecheck
//
// Copyright : 2023-2024 P Blackman
// License   : BSD-2-clause
//
// Test for false positive on GPL or-later licences, or with trailing .0

unit gpl;
{$mode delphi}

interface

function CheckGPL (Fname : AnsiString; Dep5 : String; var Actual: String) : Boolean;
Function AdjustGPL (LicenseStr : String) : String;


implementation uses StrUtils, support;

// Extract license short string, expecting a GPL license
function GetFileLicense (Fname : AnsiString) : String;
const maxlines : Integer = 100;
var lines,
    lpos : Integer;
    L1,L2, 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 ('GPL', line, 1);

            if lpos > 0 then
            begin
                L1 := ExtractSubstr(line, lpos, WhiteSpace);
                Result := L1;

                if L1 = 'GPL' then
                begin
                    L2 := ExtractSubstr(line, lpos, WhiteSpace + ['"']);
                    if (Length(L2) = 3) and (L2[3] = '+') then
                        result := L1 + L2;
                end;

                lines := maxlines // terminate loop
            end
            else
                lines := lines + 1;
        end;
        Close (lfile);
    end;
end;

// Return true if Actual is 2+ or 3+ as shown in d/copyright
function CheckGPL (Fname : AnsiString; Dep5 : String; var Actual: String) : Boolean;
var License : String;

begin
    result := false;

    if (Dep5 = 'GPL-3+') and (Actual = 'GPL-3')
    or (Dep5 = 'GPL-2+') and (Actual = 'GPL-2') then
    begin
        License := GetFileLicense (FName);
        if (License  <> '') and (license [length(License)] = '+') then
        begin
            // False positive so update Actual to match Dep5
            Actual := Dep5;
            result := true;
        end;
    end;
end;


// In d/copyright, change GPL3.0 to GPL3 etc,
// so strings match licencecheck
Function AdjustGPL (LicenseStr : String) : String;
begin
    iF StartsStr ('GPL', LicenseStr)
    and (FindPart ('.0', LicenseStr) <> 0) then
    begin
        LicenseStr := DelChars (LicenseStr, '.');
        LicenseStr := DelChars (LicenseStr, '0');
    end;

    result := LicenseStr;
end;

end.
