{ Ekran powitania: słowo NAS dużymi literami, powitanie zależne od godziny i tabela z modelem, jądrem,
  czasem pracy, obciążeniem i pamięcią. Kompilacja i start: fpc hello.pas && ./hello   (wypisuje raz i kończy)
  Pisze zwykłe kody escape bez crt, więc działa też w skrypcie logowania. }
program hello;
{$mode objfpc}{$H+}
uses sysutils, dateutils, classes, unix;

type
  TRow = record
    Name, Value: string;
  end;

const
  Big: array[1..6] of string = (
    '███╗   ██╗ █████╗ ███████╗',
    '████╗  ██║██╔══██╗██╔════╝',
    '██╔██╗ ██║███████║███████╗',
    '██║╚██╗██║██╔══██║╚════██║',
    '██║ ╚████║██║  ██║███████║',
    '╚═╝  ╚═══╝╚═╝  ╚═╝╚══════╝');
  Shades: array[1..6] of string = ('93', '93', '33', '33', '33', '90');
  Days: array[1..7] of string = ('poniedziałek', 'wtorek', 'środa', 'czwartek', 'piątek', 'sobota', 'niedziela');
  Months: array[1..12] of string = ('stycznia', 'lutego', 'marca', 'kwietnia', 'maja', 'czerwca', 'lipca',
    'sierpnia', 'września', 'października', 'listopada', 'grudnia');

var
  rows: array of TRow;
  side: array[1..6] of string;
  when: TDateTime;
  greet, model, load: string;
  total, avail: double;
  up, i: integer;

function Esc(const code: string): string; begin Result := #27'[' + code + 'm'; end;
function Rep(const s: string; n: integer): string;
var i: integer;
begin Result := ''; for i := 1 to n do Result := Result + s; end;

{ Kolumny na ekranie: bajty kontynuacji UTF-8 ($80-$BF) i kody kolorów się nie liczą }
function Width(const s: string): integer;
var i: integer; skip: boolean = false;
begin
  Result := 0;
  for i := 1 to Length(s) do begin
    if s[i] = #27 then skip := true;
    if not skip and not (s[i] in [#$80..#$BF]) then Inc(Result);
    if skip and (s[i] = 'm') then skip := false;
  end;
end;

function Pad(const s: string; n: integer): string; begin Result := s + Rep(' ', n - Width(s)); end;

{ Pierwszy wiersz, który wypisuje polecenie; '', gdy nic nie wypisuje albo go nie ma }
function Ask(const cmd: string): string;
var f: Text;
begin
  Result := '';
  if POpen(f, cmd + ' 2>/dev/null', 'R') <> 0 then Exit;
  if not Eof(f) then ReadLn(f, Result);
  PClose(f);
end;

function ProcFile(const name: string): string;
begin
  Result := GetEnvironmentVariable('PROC');
  if Result = '' then Result := '/proc';
  Result := Result + '/' + name;
end;

function Field(const s: string; n: integer): string;
begin Result := s.Split([' ', #9], TStringSplitOptions.ExcludeEmpty)[n]; end;

procedure Add(const name, value: string);
begin
  SetLength(rows, Length(rows) + 1);
  rows[High(rows)].Name := name; rows[High(rows)].Value := value;
end;

{ Czyta plik z $PROC wiersz po wierszu: plik w /proc ma rozmiar 0, więc czytamy go jako tekst, nie blokiem }
procedure Meminfo;
var f: Text; s: string;
begin
  Assign(f, ProcFile('meminfo')); Reset(f);
  while not Eof(f) do begin
    ReadLn(f, s);
    if s.StartsWith('MemTotal:') then total := StrToFloat(Field(s, 1))
    else if s.StartsWith('MemAvailable:') then avail := StrToFloat(Field(s, 1));
  end;
  Close(f);
end;

begin
  if GetEnvironmentVariable('NOW') <> '' then when := ScanDateTime('yyyy-mm-dd hh:nn:ss', GetEnvironmentVariable('NOW'))
  else when := Now;
  case HourOf(when) of
    5..11: greet := 'Dzień dobry';
    12..17: greet := 'Dzień dobry';
  else greet := 'Dobry wieczór';
  end;
  model := Ask('getsysinfo model');
  if model = '' then model := Ask('uname -n');
  side[2] := Esc('1;93') + greet + '!';
  side[3] := Esc('0') + 'To jest ' + Esc('1') + model + Esc('0') + '.';
  side[5] := Esc('0') + Days[DayOfTheWeek(when)] + ', ' + IntToStr(DayOf(when)) + ' ' + Months[MonthOf(when)]
    + ' ' + IntToStr(YearOf(when)) + ', ' + FormatDateTime('hh:nn', when);

  WriteLn;
  for i := 1 to 6 do WriteLn('  ', Esc(Shades[i]), Big[i], Esc('0'), '    ', side[i], Esc('0'));
  WriteLn;

  Add('NAS', model);
  Add('Jądro', Field(Ask('cat ' + ProcFile('version')), 2));
  up := Trunc(StrToFloat(Field(Ask('cat ' + ProcFile('uptime')), 0)));
  Add('Czas pracy', Format('%d d %d h %d min', [up div 86400, up div 3600 mod 24, up div 60 mod 60]));
  load := Ask('cat ' + ProcFile('loadavg')).Replace('.', ',');
  Add('Obciążenie', Field(load, 0) + '  ' + Field(load, 1) + '  ' + Field(load, 2) + '   (1, 5 i 15 minut)');
  Meminfo;
  Add('Pamięć', Format('zajęte %.1f z %.1f GiB  ', [(total - avail) / 1048576, total / 1048576]).Replace('.', ',')
    + Esc('32') + Rep('█', Round((total - avail) / total * 20)) + Esc('90') + Rep('░', 20 - Round((total - avail) / total * 20))
    + Esc('0') + Format(' %.0f %%', [(total - avail) / total * 100]));

  WriteLn('  ', Esc('33'), '┌', Rep('─', 14), '┬', Rep('─', 57), '┐');
  for i := 0 to High(rows) do
  begin
    WriteLn('  │ ', Esc('1;33'), Pad(rows[i].Name, 12), Esc('0;33'), ' │ ', Esc('0'), Pad(rows[i].Value, 55), Esc('33'), ' │');
    if i = 0 then WriteLn('  ├', Rep('─', 14), '┼', Rep('─', 57), '┤');
  end;
  WriteLn('  └', Rep('─', 14), '┴', Rep('─', 57), '┘', Esc('0'));
  WriteLn;
end.
