#!/usr/bin/env nu

const FHS_USUAL_BINS = [
  "/bin",
  "/sbin",
  "/usr/bin",
  "/usr/sbin",
  "/usr/local/bin",
]
const NIX_USUAL_SYS_BIN_STARTERS = [
  "/nix/",
  "/run/current-system/",
  "/run/wrappers/",
  "/etc/profiles/per-user",
]
const NIX_USUAL_USER_BIN_STARTERS = [
  "~/.nix-profile/",
  "~/.local/state/nix",
]

def "str starts-with-any?" [potentials: list<string>]: string -> bool {
  let path = $in
  $potentials | any {|potential| $path | str starts-with $potential}
}

# Color given text, reset styles after
def color_surround [color, text: string]: nothing -> string {
  $"(ansi $color)($text)(ansi reset)"
}

def hl_single_path [orig_path: string] {
  let path_in_home = $orig_path | str starts-with $env.HOME
  mut path = $orig_path
  if $path_in_home {
    $path = $orig_path | str replace $env.HOME "~"
  }
  let fancy_path = if ($path | str starts-with "~/.dot/") {
    color_surround {fg: darkorange, attr: b} $path
  } else if ($path | str starts-with-any? $NIX_USUAL_SYS_BIN_STARTERS) {
    color_surround cyan $path
  } else if ($path | str starts-with-any? $NIX_USUAL_USER_BIN_STARTERS) {
    color_surround {fg: cyan, attr: b} $path
  } else if $path_in_home {
    color_surround {fg: blue, attr: b} $path
  } else if ($path | str starts-with-any? $FHS_USUAL_BINS) {
    color_surround green $path
  } else {
    $path
  }

  mut binaries_count = 0
  let fancy_path_info = if ($path | path exists) {
    $binaries_count = ls --long $orig_path | where mode =~ x | length
    let count_info = if $binaries_count == 0 {
      "[empty]"
    } else {
      "(" + ($binaries_count | into string) + ")"
    }
    color_surround black_bold $count_info
  } else {
    color_surround xterm_red3a "[not found]"
  }

  {
    fancy_path: $fancy_path
    fancy_path_info: $fancy_path_info
    binaries_count: $binaries_count
  }
}

# Pretty print the entries of $PATH or any given PATH-like, highlighting different kind of path
# entries, whether they exist, and the number of binaries available.
def main [
  path_like?: string # PATH-like value to show entries of (defaults to $PATH)
]: nothing -> nothing {
  let path_data = if $path_like != null { $path_like } else { $env.PATH }
  let path_literal = if $path_data == $env.PATH { "$PATH" } else { "given PATH-like" }
  let path_entries = $path_data | split row ":"

  print "" # blank line
  print -n $"Pretty (color_surround {fg: darkorange3a, attr: bi} $path_literal), "
  print    $"(color_surround {attr: b} ($path_entries | length | into string)) entries in order of priority:"
  print "" # blank line

  mut total_binaries = 0
  for p in $path_entries {
    let data = hl_single_path $p
    $total_binaries += $data.binaries_count
    print $"  - ($data.fancy_path) ($data.fancy_path_info)"
  }

  # IDEA: would be nice to see 'unique' bin names, to remove duplicates across path entries
  print "" # blank line
  print $"Total binaries: ($total_binaries)"
  print "" # blank line
}
