// Reconcile DEP-5 debian/copyright to licensecheck
//
// Copyright : 2023-2025 P Blackman
// License   : BSD-2-clause
//

unit licensechecking;
{$mode delphi}

interface

procedure LicenseCheck;


implementation uses Classes, Process, StrUtils, options, rstrings, appstream, filedata;

procedure LicenseCheck;
var Posn, F : Integer;
    OK, Match : Boolean;
    lc_output,
    FileName,
    License : String;
    Line : AnsiString;
    LicenseList : tStringList;

begin
    if not Option_Format then
        Writeln (rsRl + ' licensecheck ....');

    if Option_SPDX then
        OK := RunCommand('/usr/libexec/lrc-lc', [ 'spdx' ], lc_output,  [poUsePipes, poWaitOnExit])
    else
        OK := RunCommand('/usr/libexec/lrc-lc', ['debian'], lc_output,  [poUsePipes, poWaitOnExit]);

    if not OK then
        writeln (rsFtr + ' licensecheck') // Failed to run
    else
    begin
        Writeln;

        LicenseList := tStringList.Create;
        LicenseList.text := lc_output;
        UnmangleFileNames;

        for Line in LicenseList do
        begin
            Posn     := 4; // Strip leading .//
            FileName := ExtractSubstr (Line, Posn, [Chr(9)]);
            License  := ExtractSubstr (Line, Posn, []);
            Match    := GetMatch (F, Filename);

            If Match then
            begin
                if EndsStr ('appdata.xml' , FileName)
                or EndsStr ('metainfo.xml', FileName) then
                    License := GetMetadataLicense (FileName);

                SetActualLicense(F, License);
            end
            else
                Writeln (FileName,' ' + rshul + ' ', License); // has unused license
        end;
        LicenseList.Free;
    end;
end;

end.
