// Reconcile DEP-5 debian/copyright to licensecheck
//
// Copyright : 2024-2026 P Blackman
// License   : BSD-2-clause
//
// Process command line options

unit options;
{$mode delphi}

interface

var
    Option_Version : Boolean = False;
    Option_Help    : Boolean = False;
    Option_Format  : Boolean = False;
    Option_Long    : Boolean = False;
    Option_Short   : Boolean = False;
    Option_SPDX    : Boolean = False;

procedure ShowVersions;
procedure ShowHelp;
procedure CheckParam (P : String);
procedure GetOptions;


implementation uses Process, SysUtils, StrUtils, gettext, support, rstrings;

var
    ReadMeFile : Text;
    FallbackLang,
    Lang5char   : Ansistring;
    Lang2char   : string[2];

// Get Debian package version
function GetVersion (Package : String) : String;
var S1 : String;

begin
    if RunCommand ('/usr/bin/dpkg-query',
        ['-f', '''${Version}''', '-W', Package],
        S1, [poUsePipes, poWaitOnExit])
    then
        result := S1
    else
        result := '';
end;

procedure ShowVersions;
begin
    Writeln (Lang2char + ': Versions: licenserecon ' + (GetVersion('licenserecon'))
            + '  licensecheck ' + (GetVersion('licensecheck')));
end;

function OpenHelpFile : Boolean;
begin
    result := OpenFile ('/usr/share/doc/licenserecon/ReadMe.'+ Lang2char, ReadMeFile);
    if not result then
        result := OpenFile ('/usr/share/doc/licenserecon/ReadMe', ReadMeFile);
end;

procedure ShowHelp;
var line : String;
begin
    if OpenHelpFile then
    begin
	while not EOF (ReadMeFile) do
	begin
	    Readln (ReadMeFile, Line);
	    Writeln (Line);
	end;
    
	Close (ReadMeFile);
    end
    else
	Writeln ('Cannot open ReadMe file');
end;

procedure CheckParam (P : String);
begin
    if SameText (P, '-v') or SameText (P, '--version') then
        Option_Version := true
    else if SameText (P, '-h') or SameText (P, '-?') or SameText (P, '--help') then
        Option_Help := True
    else if SameText (P, '-f') or SameText (P, '--format') then
        Option_Format := true
    else if SameText (P, '-s') or SameText (P, '--short')
         or SameText (P, '-t') or SameText (P, '--terse')  then
        Option_Short   := true
    else if SameText (P, '-l') or SameText (P, '--long')   then
        Option_Long := true
    else if SameText (P, '-x') or SameText (P, '--spdx')   then
        Option_SPDX := true
    else
        Writeln (rsIuo + ' ', P); // Ignoring unknown option
end;

procedure GetOptions;
var P : Integer;
begin
    for P := 1 to ParamCount do
        CheckParam (ParamStr(P));

    // This combination make no sense
    if Option_Short then
        Option_Long := False;

    // Setup language id
    GetLanguageIDs(Lang5char, FallbackLang);
    Lang2char := LeftStr(Lang5char, 2);
end;

end.
