#!/bin/sh
#
# lrls - lr with GNU ls style output
#
# Usage (Bash, Zsh):
#
#     # Clear any system-level aliases:
#     unalias ls la ll 2>/dev/null
#     alias ls='lrls -A'
#     alias la='lrls'
#     alias ll='lrls -lh'
#
# Set the environment variable LR_GNU_COLORS=1 to override (some) of the output
# colors to match the default GNU colors.

use_strip=1
check_depth=1

if [ -t 1 ]; then
  use_color=1
  use_column=1
fi

if [ -n "${use_color}" ] && [ -n "${LR_GNU_COLORS}" ]; then
  gnu_colors=1
fi

# shellcheck disable=SC2220,SC2249,SC2213
while getopts ':01ABC:DFGHLPQST:UWXde:f:hlo:qst:x' opt; do
  case "${opt}" in
    # If we're not entering directories:
    # - Avoid depth check so directory names aren't skipped entirely.
    # - Avoid strip so directory names aren't replaced with dots.
    d)
      unset check_depth
      unset use_strip
      ;;
    # Avoid git column for long lr output.
    l)
      unset use_column
      ;;
  esac
done

# If more than one path is given as an arg, strip can produce ambiguous output
# for multi-segment paths (and has no effect on single-segment paths).
if [ "$#" -gt "${OPTIND}" ]; then
  unset use_strip
fi

lr -1 \
  ${use_color:+-GG} \
  ${use_strip:+-s} \
  ${check_depth:+-t '!type == d || depth > 0'} \
  ${gnu_colors:+-t 'type == f && color 15 || print'} \
  ${gnu_colors:+-t 'type == p && color 11 || print'} \
  ${gnu_colors:+-t 'mode == "+x" && color 10 || print'} \
  ${gnu_colors:+-t 'type == l && color 14 || print'} \
  ${gnu_colors:+-t 'type == d && color 12 || print'} \
  "$@" | {
  if [ -n "${use_column}" ]; then
    git column --mode=dense --pad=2
  else
    cat
  fi
}
