#!/bin/sh
##
##   screens: choose a GNU screen session with the arrow keys and resume it
##
##   Copyright © 2008-2027, Silas Mariusz <silas@qnap.com.antispam>
##                          QNAP Club Polska
##
##   www.qnaputilities.com  forum.qnap.net.pl
##
##   LICENSE: GPL-2.0-or-later
##
##   ┌─────────┬──────────────────────────────────────────────┐
##   │ File    │ tools/screens/screens                        │
##   ├─────────┼──────────────────────────────────────────────┤
##   │ Package │ Bucket & Code Server IDE, recipe screens     │
##   ├─────────┼──────────────────────────────────────────────┤
##   │ Runs on │ a NAS: POSIX sh (BusyBox ash, dash, bash)    │
##   └─────────┴──────────────────────────────────────────────┘
##
# The menu lists the sessions `screen -ls` prints (name, process ID, state, start time from /proc) and runs the
# `screen` the caller's PATH gives, the one a person would type. A detached session resumes with -r; a session
# attached elsewhere offers -d -r (detach it there, resume here) or -x (share it); a dead one offers -wipe. Keys are
# read with stty and dd (QTS has no stty: TurboShell's coreutils one, beside this script, is used then), the screen
# is drawn with the terminal's own escape codes: no curses, no other program.
# Every attach names the session by its full pid.name, because screen matches a shorter name as a prefix.

VERSION=1.0

# --- words (English; Polish when the locale says pl) --------------------------------------------------------------
case "${LC_ALL:-${LC_MESSAGES:-${LANG:-}}}" in
  pl* | PL*)
    W_TITLE='Sesje GNU screen'
    W_NONE='Brak sesji screen.'
    W_NEW='Nowa sesja'
    W_QUIT='Zakończ'
    W_KEYS='↑↓ wybór   Enter wznów   n nowa sesja   q zakończ'
    W_KEYS2='↑↓ wybór   Enter wybierz   q wróć'
    W_DET='Odłączona'
    W_ATT='Podłączona'
    W_MULTI_DET='Wspólna, odłączona'
    W_MULTI_ATT='Wspólna, podłączona'
    W_DEAD='Nie działa'
    W_ATT_Q='Sesja „%s” jest podłączona na innym terminalu.'
    W_DR='Odłącz ją tam i wznów tutaj (screen -d -r)'
    W_X='Pokaż ją na obu terminalach (screen -x)'
    W_BACK='Wróć'
    W_DEAD_Q='Sesja „%s” nie działa: jej proces się zakończył, a plik gniazda został.'
    W_WIPE='Usuń niedziałające sesje (screen -wipe)'
    W_NAME='Nazwa nowej sesji (Enter: bez nazwy): '
    W_BADNAME='Nazwa może zawierać litery, cyfry oraz znaki . _ -. Spróbuj ponownie.'
    W_INSIDE='Jesteś w sesji screen %s. Odłącz ją (Ctrl-a d) i uruchom screens ponownie.'
    W_NOSCREEN='Nie znaleziono polecenia screen. Zainstaluj TurboShell albo dodaj screen do PATH.'
    W_NOSTTY='Nie znaleziono polecenia stty, a screens bez niego nie odczyta klawiszy. QTS go nie ma; TurboShell ma je w /usr/app/TurboShell/bin. Zainstaluj TurboShell albo uruchom screens z tego folderu.'
    W_BADOPT='screens nie przyjmuje opcji %s: sam wybiera -r, -d -r albo -x. Zobacz: screens --help'
    W_NEEDARG='Opcja %s wymaga wartości. Zobacz: screens --help'
    W_GONE='Sesja „%s” już nie istnieje. Lista została odświeżona.'
    ;;
  *)
    W_TITLE='GNU screen sessions'
    W_NONE='No screen sessions.'
    W_NEW='New session'
    W_QUIT='Quit'
    W_KEYS='↑↓ choose   Enter resume   n new session   q quit'
    W_KEYS2='↑↓ choose   Enter select   q back'
    W_DET='Detached'
    W_ATT='Attached'
    W_MULTI_DET='Shared, detached'
    W_MULTI_ATT='Shared, attached'
    W_DEAD='Dead'
    W_ATT_Q='Session "%s" is attached on another terminal.'
    W_DR='Detach it there and resume here (screen -d -r)'
    W_X='Show it on both terminals (screen -x)'
    W_BACK='Back'
    W_DEAD_Q='Session "%s" is dead: its process ended and its socket file is left.'
    W_WIPE='Remove dead sessions (screen -wipe)'
    W_NAME='Name for the new session (Enter for none): '
    W_BADNAME='A name can contain letters, digits and . _ -. Try again.'
    W_INSIDE='You are in screen session %s. Detach it (Ctrl-a d) and run screens again.'
    W_NOSCREEN='The screen command was not found. Install TurboShell or add screen to PATH.'
    W_NOSTTY='The stty command was not found, and screens cannot read keys without it. QTS has none; TurboShell has it in /usr/app/TurboShell/bin. Install TurboShell or run screens from that folder.'
    W_BADOPT='screens does not accept %s: it chooses -r, -d -r or -x itself. See: screens --help'
    W_NEEDARG='The option %s needs a value. See: screens --help'
    W_GONE='Session "%s" no longer exists. The list was refreshed.'
    ;;
esac

usage() {
  case "${LC_ALL:-${LC_MESSAGES:-${LANG:-}}}" in
    pl* | PL*)
      cat <<'EOF'
screens: wybierz sesję GNU screen strzałkami i wznów ją

Użycie: screens [opcje screen]
        screens --list
        screens --help

Menu pokazuje Twoje sesje screen: nazwę, numer procesu, stan i czas startu.
  ↑ ↓      wybór sesji
  Enter    wznowienie wybranej sesji
  n        nowa sesja (zapyta o nazwę)
  q, Esc   wyjście bez zmian

Odłączona sesja wznawia się przez screen -r.
Gdy sesja jest podłączona na innym terminalu, screens pyta, co zrobić:
  Odłącz ją tam i wznów tutaj        screen -d -r
  Pokaż ją na obu terminalach        screen -x
Niedziałającą sesję screens usuwa: screen -wipe, a gdy screen zostawi jej plik gniazda,
usuwa też ten plik.

Przy wznowieniu i przy nowej sesji screens przekazuje do screen opcje -a, -A, -U, -O,
-T <terminal>, -e <xy>, -h <wiersze>, -c <plik> i -s <powłoka>. -a włącza w każdym oknie
wszystkie możliwości terminala, -A dopasowuje rozmiar okien do tego terminala.

--list   wypisuje sesje bez menu (tak samo, gdy wejście lub wyjście nie jest terminalem)
-h       bez liczby pokazuje tę pomoc
EOF
      ;;
    *)
      cat <<'EOF'
screens: choose a GNU screen session with the arrow keys and resume it

Usage: screens [screen options]
       screens --list
       screens --help

The menu lists your screen sessions: name, process ID, state and start time.
  Up, Down   choose a session
  Enter      resume the chosen session
  n          start a new session (asks for a name)
  q, Esc     quit without changes

A detached session resumes with screen -r.
If a session is attached on another terminal, screens asks what to do:
  Detach it there and resume here    screen -d -r
  Show it on both terminals          screen -x
screens removes a dead session: screen -wipe, then its socket file if screen leaves it.

screens passes the screen options -a, -A, -U, -O, -T <term>, -e <xy>, -h <lines>, -c <file>
and -s <shell> to screen when it resumes or starts a session. -a turns on all of the
terminal's capabilities in each window; -A fits the windows to this terminal's size.

--list   prints the sessions without the menu (also when input or output is not a terminal)
-h       without a number shows this help
EOF
      ;;
  esac
}

# --- arguments: our two words, or screen options passed on ------------------------------------------------------
PASS=''
LIST=''
add() { PASS="$PASS '$(printf '%s' "$1" | sed "s/'/'\\\\''/g")'"; }
while [ $# -gt 0 ]; do
  case "$1" in
    -help | --help | -\?)
      usage
      exit 0
      ;;
    --version)
      echo "screens $VERSION"
      exit 0
      ;;
    -list | --list) LIST=1 ;;
    -a | -A | -U | -O) add "$1" ;;
    -h)
      # screen's -h takes the scrollback's lines; -h alone, or with no number, is a request for help
      case "${2:-}" in
        '' | *[!0-9]*)
          usage
          exit 0
          ;;
      esac
      add "$1"
      add "$2"
      shift
      ;;
    -T | -e | -c | -s)
      [ $# -ge 2 ] || {
        printf "$W_NEEDARG\n" "$1" >&2
        exit 2
      }
      add "$1"
      add "$2"
      shift
      ;;
    *)
      printf "$W_BADOPT\n" "$1" >&2
      exit 2
      ;;
  esac
  shift
done

command -v screen >/dev/null 2>&1 || {
  echo "$W_NOSCREEN" >&2
  exit 127
}

# --- the sessions -------------------------------------------------------------------------------------------------
# One line per session: pid<TAB>pid.name<TAB>state, state one of det, att, mdet, matt, dead.
sessions() {
  screen -ls 2>/dev/null | tr -d '\r' | awk -F '\t' '
    NF >= 3 && $2 ~ /^[0-9]+\./ {
      st = $NF
      if (st ~ /[Dd]ead/) s = "dead"
      else if (st ~ /Multi/ && st ~ /[Aa]ttached/) s = "matt"
      else if (st ~ /Multi/) s = "mdet"
      else if (st ~ /[Aa]ttached/) s = "att"
      else if (st ~ /[Dd]etached/) s = "det"
      else s = "dead"
      pid = $2; sub(/\..*/, "", pid)
      printf "%s\t%s\t%s\n", pid, $2, s
    }'
}

BTIME=$(awk '/^btime /{print $2}' /proc/stat 2>/dev/null)
# started PID: the process start time, from /proc (screen 5 prints no date); USER_HZ is 100 on Linux
started() {
  [ -n "$BTIME" ] && [ -r "/proc/$1/stat" ] || {
    echo '-'
    return
  }
  t=$(sed 's/.*) //' "/proc/$1/stat" 2>/dev/null | awk '{print $20}')
  [ -n "$t" ] || {
    echo '-'
    return
  }
  date -d "@$((BTIME + t / 100))" '+%Y-%m-%d %H:%M' 2>/dev/null || echo '-'
}

state_word() {
  case "$1" in
    det) echo "$W_DET" ;; att) echo "$W_ATT" ;; mdet) echo "$W_MULTI_DET" ;; matt) echo "$W_MULTI_ATT" ;; *) echo "$W_DEAD" ;;
  esac
}

print_list() {
  S=$(sessions)
  if [ -z "$S" ]; then
    echo "$W_NONE"
    return 0
  fi
  printf '%s\n' "$S" | while IFS='	' read -r pid full st; do
    printf '%-24s %7s  %-16s  %s\n' "${full#*.}" "$pid" "$(started "$pid")" "$(state_word "$st")"
  done
}

if [ -n "$LIST" ] || [ ! -t 0 ] || [ ! -t 1 ]; then
  print_list
  exit 0
fi

if [ -n "${STY:-}" ]; then
  printf "$W_INSIDE\n" "$STY" >&2
  exit 1
fi

# --- the terminal -------------------------------------------------------------------------------------------------
# QTS and QuTS hero have no stty; TurboShell's coreutils one is in the same bin folder as this script
STTY=$(command -v stty 2>/dev/null) || STTY=
if [ -z "$STTY" ]; then
  case "$0" in */*) [ -x "${0%/*}/stty" ] && STTY=${0%/*}/stty ;; esac
fi
[ -n "$STTY" ] || {
  echo "$W_NOSTTY" >&2
  exit 127
}
ESC=$(printf '\033')
SAVED=$("$STTY" -g)
restore() {
  "$STTY" "$SAVED" 2>/dev/null
  printf '\033[0m\033[?25h\033[?1049l'
}
trap 'restore' EXIT
trap 'restore; trap - EXIT; exit 130' INT TERM HUP

raw() { "$STTY" -icanon -echo min 1 time 0; }
printf '\033[?1049h\033[?25l'
raw

# key: up, down, enter, quit, n, or other
key() {
  k=$(dd bs=1 count=1 2>/dev/null)
  case "$k" in
    '') echo enter ;;
    "$ESC")
      "$STTY" min 0 time 1
      r=$(dd bs=1 count=2 2>/dev/null)
      raw
      case "$r" in
        '[A' | 'OA') echo up ;;
        '[B' | 'OB') echo down ;;
        '') echo quit ;;
        *) echo other ;;
      esac
      ;;
    k | K) echo up ;;
    j | J) echo down ;;
    q | Q) echo quit ;;
    n | N) echo n ;;
    *) echo other ;;
  esac
}

COLS=$("$STTY" size 2>/dev/null | awk '{print $2}')
[ -n "$COLS" ] && [ "$COLS" -gt 20 ] || COLS=80

# draw TITLE NOTE SELECTED ITEM...: the title, a note line, then the items, SELECTED (from 1) in reverse video, then
# the keys: the main menu's, or a question's when ASK is set
draw() {
  title=$1 note=$2 sel=$3
  shift 3
  keys=$W_KEYS
  [ -n "$ASK" ] && keys=$W_KEYS2
  printf '\033[H\033[2J\033[1m %s\033[0m\r\n\r\n' "$title"
  [ -n "$note" ] && printf ' %s\r\n\r\n' "$note"
  i=1
  for item in "$@"; do
    line=$(printf ' %s ' "$item" | cut -c1-$((COLS - 2)))
    if [ "$i" -eq "$sel" ]; then printf ' \033[7m%s\033[0m\r\n' "$line"; else printf ' %s\r\n' "$line"; fi
    i=$((i + 1))
  done
  printf '\r\n \033[2m%s\033[0m' "$keys"
}

# choose TITLE NOTE ITEM...: a menu; prints the number of the chosen item, 0 for quit
choose() {
  title=$1 note=$2
  shift 2
  n=$# sel=1
  while :; do
    draw "$title" "$note" "$sel" "$@" >/dev/tty
    case $(key) in
      up) [ "$sel" -gt 1 ] && sel=$((sel - 1)) ;;
      down) [ "$sel" -lt "$n" ] && sel=$((sel + 1)) ;;
      enter)
        echo "$sel"
        return
        ;;
      quit)
        echo 0
        return
        ;;
      n) [ -z "$ASK" ] && {
        echo n
        return
      } ;;
    esac
  done
}

# run ARGS...: leave the menu and become screen with the passed options
run() {
  restore
  trap - EXIT INT TERM HUP
  eval "set -- $PASS \"\$@\""
  exec screen "$@"
}

new_session() {
  "$STTY" "$SAVED"
  printf '\033[?25h\033[H\033[2J'
  while :; do
    printf '%s' "$W_NAME"
    IFS= read -r name || exit 0
    case "$name" in
      '') run ;;
      *[!A-Za-z0-9._-]*) echo "$W_BADNAME" ;;
      *) run -S "$name" ;;
    esac
  done
}

# wipe: screen -wipe, then the socket of each dead session whose process is gone. screen 5 wipes only a socket whose
# name ends in this host's name; a named session (-S) it reports as "Remote or dead" and leaves.
wipe() {
  screen -wipe >/dev/null 2>&1
  dir=$(screen -ls 2>/dev/null | tr -d '\r' | sed -n 's/^[0-9][0-9]* Sockets\{0,1\} in \(.*\)\.$/\1/p' | tail -n 1)
  [ -n "$dir" ] && [ -d "$dir" ] || return 0
  sessions | while IFS='	' read -r pid full st; do
    [ "$st" = dead ] && [ ! -d "/proc/$pid" ] && [ -S "$dir/$full" ] && rm -f -- "$dir/$full"
  done
}

ASK=''
NOTE=''
while :; do
  S=$(sessions)
  set --
  if [ -n "$S" ]; then
    while IFS='	' read -r pid full st; do
      set -- "$@" "$(printf '%-24s %7s  %-16s  %s' "${full#*.}" "$pid" "$(started "$pid")" "$(state_word "$st")")"
    done <<EOF
$S
EOF
  fi
  count=$#
  [ "$count" -eq 0 ] && NOTE=${NOTE:-$W_NONE}
  c=$(choose "$W_TITLE" "$NOTE" "$@" "+ $W_NEW" "  $W_QUIT")
  NOTE=''
  case "$c" in
    0) exit 0 ;;
    n) new_session ;;
  esac
  [ "$c" -eq $((count + 1)) ] && new_session
  [ "$c" -eq $((count + 2)) ] && exit 0
  line=$(printf '%s\n' "$S" | sed -n "${c}p")
  full=$(printf '%s' "$line" | cut -f2)
  st=$(printf '%s' "$line" | cut -f3)
  # the list may have changed while the menu was open
  now=$(sessions | awk -F '\t' -v f="$full" '$2 == f {print $3}')
  if [ -z "$now" ]; then
    NOTE=$(printf "$W_GONE" "${full#*.}")
    continue
  fi
  st=$now
  case "$st" in
    det | mdet) run -r "$full" ;;
    att | matt)
      a=$(ASK=1 choose "$W_TITLE" "$(printf "$W_ATT_Q" "${full#*.}")" "$W_DR" "$W_X" "$W_BACK")
      case "$a" in
        1) run -d -r "$full" ;;
        2) run -x "$full" ;;
      esac
      ;;
    dead)
      a=$(ASK=1 choose "$W_TITLE" "$(printf "$W_DEAD_Q" "${full#*.}")" "$W_WIPE" "$W_BACK")
      [ "$a" = 1 ] && wipe
      ;;
  esac
done
