{ NAS summary in two columns: the system on the left, volumes and network ports on the right.
  Build and run: fpc stats.pas && ./stats   (prints once and ends)
  Each part of the NAS is a record; each panel is a list of lines that a procedure frames. }
program stats;
{$mode objfpc}{$H+}
uses sysutils, classes, unix;

type
  TSystem = record
    Model, Cpu, Load: string; Cores, Logical, CpuTemp, SysTemp: integer; MemTotal, MemAvail: double;
  end;
  TVolume = record Name: string; Size, Used: double; end;
  TPort = record Name: string; Received, Sent: double; end;

var
  sys: TSystem;
  vols: array of TVolume;
  ports: array of TPort;
  left, right, lines: TStringList;
  v: TVolume; p: TPort; 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;

{ 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;
function Field(const s: string; n: integer): string;
begin Result := s.Split([' ', #9], TStringSplitOptions.ExcludeEmpty)[n]; end;

{ The lines a command prints; /proc files are read through cat, because their size reads as 0 }
function Run(const cmd: string): TStringList;
var f: Text; s: string;
begin
  Result := TStringList.Create;
  if POpen(f, cmd + ' 2>/dev/null', '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 Size(kb: double): string;
const units: array[0..3] of string = ('KiB', 'MiB', 'GiB', 'TiB');
var u: integer = 0;
begin
  while (kb >= 1024) and (u < 3) do begin kb := kb / 1024; Inc(u); end;
  Result := FormatFloat('0.0', kb) + ' ' + units[u];
end;
function Meter(part: double; cells: integer): string;
var c: string;
begin
  if part > 1 then part := 1;
  if part > 0.9 then c := '31' else if part > 0.7 then c := '33' else c := '32';
  Result := Esc(c) + Rep('█', Round(part * cells)) + Esc('90') + Rep('░', cells - Round(part * cells))
    + Esc('0') + Format('%4.0f %%', [part * 100]);
end;
function Temp(c: integer): string;
begin
  if c >= 55 then Result := Esc('31') else if c >= 45 then Result := Esc('33') else Result := Esc('32');
  if c = 0 then Result := '--' else Result := Result + IntToStr(c) + ' °C' + Esc('0');
end;

procedure ReadSystem(var s: TSystem);
var t, seen: TStringList; line, chip: string;
begin
  t := Run('getsysinfo model'); if t.Count > 0 then s.Model := t[0] else s.Model := 'NAS'; t.Free;
  s.CpuTemp := StrToIntDef(Field(Run('getsysinfo cputmp').Text + ' 0', 0), 0);
  s.SysTemp := StrToIntDef(Field(Run('getsysinfo systmp').Text + ' 0', 0), 0);
  t := Proc('cpuinfo'); seen := TStringList.Create; chip := '';
  for line in t do
    if line.StartsWith('model name') then s.Cpu := Trim(line.Substring(line.IndexOf(':') + 1))
    else if line.StartsWith('processor') then Inc(s.Logical)
    else if line.StartsWith('physical id') then chip := Field(line, 3)
    else if line.StartsWith('core id') and (seen.IndexOf(chip + '/' + Field(line, 3)) < 0) then seen.Add(chip + '/' + Field(line, 3));
  s.Cores := seen.Count; seen.Free; t.Free;
  t := Proc('loadavg'); s.Load := Field(t[0], 0) + '  ' + Field(t[0], 1) + '  ' + Field(t[0], 2); t.Free;
  t := Proc('meminfo');
  for line in t do
    if line.StartsWith('MemTotal:') then s.MemTotal := StrToFloat(Field(line, 1))
    else if line.StartsWith('MemAvailable:') then s.MemAvail := StrToFloat(Field(line, 1));
  t.Free;
end;

procedure ReadVolumes;
var t: TStringList; line: string;
begin
  if GetEnvironmentVariable('DF') = '' then t := Run('df -kP') else t := Run('cat ' + GetEnvironmentVariable('DF'));
  for line in t do
    if (Length(line.Split([' '], TStringSplitOptions.ExcludeEmpty)) = 6) and Field(line, 5).StartsWith('/share/CACHEDEV') then
    begin
      SetLength(vols, Length(vols) + 1);
      with vols[High(vols)] do begin Name := Field(line, 5).Substring(7); Size := StrToFloat(Field(line, 1)); Used := StrToFloat(Field(line, 2)); end;
    end;
  t.Free;
end;

procedure ReadPorts;
var t: TStringList; line: string;
begin
  t := Proc('net/dev');
  for line in t do
    if Trim(line).StartsWith('eth') then
    begin
      SetLength(ports, Length(ports) + 1);
      with ports[High(ports)] do begin
        Name := Trim(line.Substring(0, line.IndexOf(':')));
        Received := StrToFloat(Field(line.Substring(line.IndexOf(':') + 1), 0)); Sent := StrToFloat(Field(line.Substring(line.IndexOf(':') + 1), 8));
      end;
    end;
  t.Free;
end;

{ Adds the lines of a panel of width w, framed and with a title, to the column col }
procedure Panel(col: TStringList; const title: string; lines: TStringList; w: integer);
var s: string;
begin
  col.Add(Esc('33') + '┌─ ' + Esc('1') + title + Esc('0;33') + ' ' + Rep('─', w - Width(title) - 5) + '┐' + Esc('0'));
  for s in lines do col.Add(Esc('33') + '│ ' + Esc('0') + Pad(s, w - 4) + Esc('33') + ' │' + Esc('0'));
  col.Add(Esc('33') + '└' + Rep('─', w - 2) + '┘' + Esc('0'));
  lines.Clear;
end;

begin
  ReadSystem(sys); ReadVolumes; ReadPorts;
  left := TStringList.Create; right := TStringList.Create; lines := TStringList.Create;
  lines.AddStrings([Pad('Cores', 20) + IntToStr(sys.Cores), Pad('Logical processors', 20) + IntToStr(sys.Logical), '',
    Pad('CPU', 20) + Temp(sys.CpuTemp), Pad('System', 20) + Temp(sys.SysTemp), '',
    Pad('Load', 8) + sys.Load, Pad('', 8) + Meter(StrToFloat(Field(sys.Load, 0)) / sys.Logical, 20), '',
    Pad('Memory', 8) + Size(sys.MemTotal - sys.MemAvail) + ' of ' + Size(sys.MemTotal),
    Pad('', 8) + Meter((sys.MemTotal - sys.MemAvail) / sys.MemTotal, 20)]);
  Panel(left, 'System', lines, 39);
  for v in vols do begin
    lines.Add(Pad(v.Name, 16) + Size(v.Used) + ' of ' + Size(v.Size));
    lines.Add(Pad('', 8) + Meter(v.Used / v.Size, 20));
  end;
  Panel(right, 'Volumes', lines, 39);
  for p in ports do begin
    lines.Add(Pad(p.Name, 8) + Pad('received', 10) + Esc('32') + Size(p.Received / 1024) + Esc('0'));
    lines.Add(Pad('', 8) + Pad('sent', 10) + Esc('32') + Size(p.Sent / 1024) + Esc('0'));
  end;
  Panel(right, 'Network', lines, 39);
  WriteLn(Esc('30;43'), Pad(' ' + sys.Model + '   ' + sys.Cpu, 79), Esc('0'));
  while right.Count < left.Count do right.Add('');
  while left.Count < right.Count do left.Add(Rep(' ', 39));
  for i := 0 to left.Count - 1 do WriteLn(left[i], ' ', right[i]);
  left.Free; right.Free; lines.Free;
end.
