// 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, support, appstream;

procedure LicenseCheck;
var L, Posn, Count : Integer;
    OK, Match : Boolean;
    Line, S,
    FileName,
    License : String;
    LicenseList : tStringList;

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

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

    if not OK then
        writeln (rsFtr + ' licensecheck') // Failed to run
    else
    begin
        Writeln;
        LicenseList := tStringList.Create;
        LicenseList.text := S;
        Count := 0;

        // Unmangle filenames
        for Count := 0 to High (MyFiles) do
            Unmanglename (MyFiles[Count].Fname);

        for L := 0 to LicenseList.Count -1 do
        begin
            Line := LicenseList.Strings [L];
            Posn      := 4; // Strip leading .//
            FileName := ExtractSubstr (Line, Posn, [Chr(9)]);
            License  := ExtractSubstr (Line, Posn, []);

            Count := 0;
            Match    := FileName = MyFiles[Count].Fname;
            While not Match and (count < High (MyFiles)) do
            begin
                Count := Count +1;
                Match := FileName = MyFiles[Count].Fname;
            end;

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

                MyFiles[Count].Actual := License;
            end
            else
                Writeln (FileName,' ' + rshul + ' ', License); // has unused license
        end;
        LicenseList.Free;
    end;
end;

end.
