{ NAS desk: a menu bar with drop-down boxes and dialog boxes with shadows, drawn by hand.
  Build and run: fpc menu.pas && ./menu   Left/Right pick a menu, Up/Down an entry, Enter opens it,
  Esc or Enter closes the box, q quits. crt reads the keys; the screen goes out as escape codes. }
program menu;
{$mode objfpc}{$H+}
uses crt, sysutils, classes, unix;

const
  Titles: array[1..3] of string = ('System', 'Storage', 'Help');
  Entries: array[1..3, 1..3] of string = (('Memory', 'Load and uptime', 'Processor'),
    ('Volumes', 'RAID groups', ''), ('Keys', '', ''));
  Counts: array[1..3] of integer = (3, 2, 1);
  Bar = '30;47'; Pick = '30;42'; Desk = '37;44'; Shade = '90;40'; Hot = '31;47';
var
  con: Text; facts: TStringList; menuNo, entry: integer; dialog: boolean; c: char;

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

{ Columns on the screen: UTF-8 continuation bytes ($80-$BF) and colour codes do not count }
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;
{ A box in colour col with the six edge characters of e and a shadow 2 columns right and 1 line down }
function Box(x, y, w, h: integer; const col: string; const e: array of string): string;
var i: integer;
begin
  Result := Esc(Shade);
  for i := 1 to h do Result := Result + At(x + 2, y + i) + Rep('░', w);
  Result := Result + Esc(col) + At(x, y) + e[0] + Rep(e[1], w - 2) + e[2];
  for i := 1 to h - 2 do Result := Result + At(x, y + i) + e[3] + Rep(' ', w - 2) + e[3];
  Result := Result + At(x, y + h - 1) + e[4] + Rep(e[1], w - 2) + e[5];
end;

{ The lines a command prints; Proc reads a file of $PROC (default /proc) through cat }
function Run(const cmd: string): TStringList;
var f: Text; s: string;
begin
  Result := TStringList.Create;
  if POpen(f, cmd, 'R') <> 0 then Exit;
  while not Eof(f) do begin ReadLn(f, s); Result.Add(s); end;
  PClose(f);
end;
function Proc(const name: string): TStringList;
begin
  if GetEnvironmentVariable('PROC') = '' then Result := Run('cat /proc/' + name)
  else Result := Run('cat ' + GetEnvironmentVariable('PROC') + '/' + name);
end;

function Field(const s: string; n: integer): string;
begin Result := s.Split([' ', #9], TStringSplitOptions.ExcludeEmpty)[n]; end;
function Gib(kb: double): string;
begin
  if kb >= 1073741824 then Result := FormatFloat('0.00', kb / 1073741824) + ' TiB'
  else Result := FormatFloat('0.0', kb / 1048576) + ' GiB';
end;
function Meter(part: double): string;
begin Result := Esc('32;47') + Rep('█', Round(part * 16)) + Esc('90;47') + Rep('░', 16 - Round(part * 16)) + Esc(Bar) + Format('%4.0f %%', [part * 100]); end;

{ The lines of the dialog box of menu m, entry e }
procedure Gather(m, e: integer);
var t, seen: TStringList; s, chip: string; total: double = 0; avail: double = 0; i: integer;
begin
  facts.Clear; seen := TStringList.Create; t := seen;
  case m * 10 + e of
    11: begin t := Proc('meminfo');
          for s in t do if s.StartsWith('MemTotal:') then total := StrToFloat(Field(s, 1))
            else if s.StartsWith('MemAvailable:') then avail := StrToFloat(Field(s, 1));
          facts.Add(Pad('Total', 12) + Gib(total));
          facts.Add(Pad('Used', 12) + Pad(Gib(total - avail), 10) + Meter((total - avail) / total));
          facts.Add(Pad('Available', 12) + Gib(avail));
        end;
    12: begin t := Proc('uptime'); i := Trunc(StrToFloat(Field(t[0], 0))); t.Free;
          facts.Add(Pad('Up for', 12) + Format('%d d %d h %d min', [i div 86400, i div 3600 mod 24, i div 60 mod 60]));
          t := Proc('loadavg');
          facts.Add(Pad('Load', 12) + Field(t[0], 0) + '  ' + Field(t[0], 1) + '  ' + Field(t[0], 2) + '   1 / 5 / 15 min');
        end;
    13: begin t := Proc('cpuinfo');
          for s in t do
            if s.StartsWith('model name') and (facts.Count = 0) then facts.Add(Trim(s.Substring(s.IndexOf(':') + 1)))
            else if s.StartsWith('processor') then total := total + 1
            else if s.StartsWith('physical id') then chip := Field(s, 3)
            else if s.StartsWith('core id') and (seen.IndexOf(chip + '/' + Field(s, 3)) < 0) then seen.Add(chip + '/' + Field(s, 3));
          facts.Add(Pad('Cores', 22) + IntToStr(seen.Count));
          facts.Add(Pad('Logical processors', 22) + FloatToStr(total));
        end;
    21: begin s := GetEnvironmentVariable('DF');
          if s = '' then t := Run('df -kP 2>/dev/null') else t := Run('cat ' + s);
          for s in t do
            if (Length(s.Split([' '], TStringSplitOptions.ExcludeEmpty)) = 6) and Field(s, 5).StartsWith('/share/CACHEDEV') then
              facts.Add(Pad(Field(s, 5).Substring(7), 16) + Pad(Gib(StrToFloat(Field(s, 1))), 11)
                + Meter(StrToFloat(Field(s, 2)) / StrToFloat(Field(s, 1))));
        end;
    22: begin t := Proc('mdstat');
          for i := 0 to t.Count - 2 do
            if t[i].StartsWith('md') then
              facts.Add(Pad(Field(t[i], 0), 8) + Pad(Field(t[i], 3), 8) + Pad(Gib(StrToFloat(Field(t[i + 1], 0))), 12)
                + IntToStr(t[i + 1].CountChar('U')) + ' disks up');
        end;
    31: facts.AddStrings(['Left, Right   choose a menu', 'Up, Down      choose an entry', 'Enter         open it',
          'Esc, Enter    close the box', 'q             quit']);
  end;
  if t <> seen then t.Free; seen.Free;
end;

procedure Draw;
var s, title: string; i, k, x, h, top: integer;
begin
  s := Esc('0') + Esc(Desk);
  for i := 2 to 23 do s := s + At(1, i) + Rep('░', 80);
  s := s + Esc(Bar) + At(1, 1) + Rep(' ', 80) + At(1, 24) + Rep(' ', 80) + At(2, 24) + Esc(Hot) + 'q' + Esc(Bar)
    + ' Quit   ' + Esc(Hot) + 'Enter' + Esc(Bar) + ' Open   ' + Esc(Hot) + 'Esc' + Esc(Bar) + ' Close';
  x := 2;
  for i := 1 to 3 do begin
    if i = menuNo then s := s + At(x, 1) + Esc(Pick) + ' ' + Titles[i] + ' ' + Box(x, 2, 21, Counts[i] + 2, Bar,
      ['┌', '─', '┐', '│', '└', '┘']) else s := s + At(x, 1) + Esc(Bar) + ' ' + Titles[i] + ' ';
    if i = menuNo then
      for k := 1 to Counts[i] do
        if k = entry then s := s + At(x + 1, 2 + k) + Esc(Pick) + Pad(' ' + Entries[i, k], 19)
        else s := s + At(x + 1, 2 + k) + Esc(Bar) + Pad(' ' + Entries[i, k], 19);
    x := x + Width(Titles[i]) + 2;
  end;
  if dialog then begin
    h := facts.Count + 5; top := (24 - h) div 2 + 2; title := ' ' + Entries[menuNo, entry] + ' ';
    s := s + Box(12, top, 56, h, '97;47', ['╔', '═', '╗', '║', '╚', '╝']) + At(40 - Width(title) div 2, top) + title;
    for i := 0 to facts.Count - 1 do s := s + At(15, top + 2 + i) + Esc(Bar) + facts[i];
    s := s + At(36, top + h - 2) + Esc(Pick) + '   OK   ';
  end;
  Write(con, s + Esc('0')); Flush(con);
end;
begin
  Assign(con, ''); Rewrite(con);
  facts := TStringList.Create; menuNo := 1; entry := 1; dialog := false; Write(con, #27'[?25l');
  repeat
    Draw; c := ReadKey;
    if c = #0 then begin
      c := ReadKey;
      if not dialog then case c of
          #75: begin menuNo := (menuNo + 1) mod 3 + 1; entry := 1; end;
          #77: begin menuNo := menuNo mod 3 + 1; entry := 1; end;
          #72: if entry > 1 then Dec(entry);
          #80: if entry < Counts[menuNo] then Inc(entry);
      end;
      c := #0;
    end
    else if (c = #13) and not dialog then begin Gather(menuNo, entry); dialog := true; end
    else if c in [#13, #27] then dialog := false;
  until c in ['q', 'Q'];
  Write(con, Esc('0') + #27'[2J' + At(1, 1) + #27'[?25h'); Flush(con); facts.Free;
end.
