#!/bin/sh
# summary: Record the screen or an area, with optional sound.
# Screen recording for Starchaser. The screen recorder encodes on the graphics card, so recording costs
# almost no processor time; with basic graphics (no working graphics driver) it encodes on the processor instead.
# One recording at a time; the cockpit's edge pulses red while it runs.
#
#   starchaser record screen [--sound]    the screen the pointer is on (Hyprland's focused monitor)
#   starchaser record region [--sound]    drag out a box (slurp)
#   starchaser record stop                stop and save
#   starchaser record toggle [--sound]    stop if recording, else record the screen (Super+Shift+R)
#   starchaser record status              "recording" (then how long, the file's size) or "idle" (exit 0 / 1)
#
# Saved to ~/Videos/Recordings/YYYY-MM-DD_HH-MM-SS.mp4 (H.264, 60 fps, 30 on the processor; sound = what the computer plays).
PIDFILE="${XDG_RUNTIME_DIR:-/tmp}/starchaser-record.pid"
OUTFILE="${XDG_RUNTIME_DIR:-/tmp}/starchaser-record.file"
LOG="${XDG_RUNTIME_DIR:-/tmp}/starchaser-record.log"     # the recorder's own messages, to tell why it stopped
# A recorder that was just started and isn't known to be recording yet. The pidfile is what the Screen privacy light
# watches, so it is written only once the recorder has kept running: one that quits at once (basic graphics) never
# lights the Screen light or leaves "Last used by Screen recorder" behind.
STARTING="${XDG_RUNTIME_DIR:-/tmp}/starchaser-record.starting"
NOTICES="${XDG_RUNTIME_DIR:-/tmp}/starchaser-record.notices"     # .PID: the senders waiting on that recording's Stop
DIR="$HOME/Videos/Recordings"

recording_process_alive() {
    kill -0 "$1" 2>/dev/null || return 1
    # A process-exit event arrives before the parent necessarily reaps its child.
    # Zombies still accept kill -0, but they have already stopped recording.
    case "$(ps -o stat= -p "$1" 2>/dev/null)" in
        ""|*Z*|*X*) return 1 ;;
        *) return 0 ;;
    esac
}
# the recorder start() is still checking: its process id, while it lives and for at most 10 s (a start that was
# itself killed must not hide a recorder for good)
starting_pid() {
    since=$(stat -c %Y "$STARTING" 2>/dev/null) || return 1
    [ $(( $(date +%s) - since )) -le 10 ] || return 1
    sp=$(cat "$STARTING" 2>/dev/null)
    recording_process_alive "$sp" && echo "$sp"
}
# The truth is the live recorder process, not only the pidfile: a recording that lost its pidfile is still a
# recording. Sets PID (and fills OUTFILE from the recorder's command line when it is missing).
running() {   # (pgrep matches the 15-letter process name, so the name is cut short)
    PID=
    if [ -f "$PIDFILE" ] && recording_process_alive "$(cat "$PIDFILE")"; then PID=$(cat "$PIDFILE"); return 0; fi
    starting=$(starting_pid)
    # only a recorder this script started counts: it writes to $DIR under a date-and-time name. A recorder some other
    # program started (a replay buffer, another app) is not ours to show, adopt or stop.
    for p in $(pgrep -u "$(id -u)" -x gpu-screen-reco 2>/dev/null; pgrep -u "$(id -u)" -x wf-recorder 2>/dev/null); do
        [ "$p" = "$starting" ] && continue       # not a recording until start() says so
        # the file follows gpu-screen-recorder's -o or the processor recorder's -f (their other -o and -f are a
        # screen's name and a frame rate, which never look like a recording's path)
        o=$(tr '\0' '\n' < "/proc/$p/cmdline" 2>/dev/null | sed -n '/^-[of]$/{n;p;}' | while IFS= read -r v; do
            case "$v" in "$DIR"/[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]_[0-9][0-9]-[0-9][0-9]-[0-9][0-9].mp4)
                echo "$v"; break ;;
            esac
        done)
        if [ -n "$o" ]; then PID=$p; echo "$PID" > "$PIDFILE"; echo "$o" > "$OUTFILE"; return 0; fi
    done
    rm -f "$PIDFILE"; return 1
}
# the disk the recordings go to is nearly full: below the larger of 10 GB and 5% of it
disk_low() {
    # shellcheck disable=SC2046  # the two numbers split into $1 and $2 on purpose
    set -- $(df -B1 --output=avail,size "$DIR" 2>/dev/null | tail -n 1)
    [ -n "${2:-}" ] || return 1
    floor=$(( $2 / 20 )); [ "$floor" -lt 10737418240 ] && floor=10737418240
    [ "$1" -lt "$floor" ]
}
elapsed_s() { ps -o etimes= -p "$1" 2>/dev/null | tr -d ' '; }
size_mb() { f=$(cat "$OUTFILE" 2>/dev/null); if [ -f "$f" ]; then echo $(( $(stat -c %s "$f") / 1048576 )); else echo 0; fi; }
# a notice with a Stop button; the button stops only THIS recording (by process id), never a later one.
# $4 = --bell makes it a quiet bell entry (no pop-up, no chime)
stop_button_notice() {
    ( if [ "${4:-}" = --bell ]; then
          a=$(/bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser -i media-record -h boolean:x-starchaser-bell-only:true -A stop=Stop "$2" "$3")
      else
          a=$(/bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser -i media-record -A stop=Stop "$2" "$3")
      fi
      [ "$a" = stop ] && starchaser record stop-pid "$1" ) </dev/null >/dev/null 2>&1 &
    echo $! >> "$NOTICES.$1"
}
# The recording $1 has ended: its Stop notices have nothing left to stop, so their waiting senders go too. Each one
# waits for an answer for as long as the notice is in the bell's list, which kept a "starchaser record" command
# running long after the recording.
end_notices() {
    for w in $(cat "$NOTICES.$1" 2>/dev/null); do
        pkill -P "$w" 2>/dev/null; kill "$w" 2>/dev/null
    done
    rm -f "$NOTICES.$1"
}
# The failure notice opens the hardware checks with its Check graphics button. Nothing here waits for that button:
# the taskbar opens the Settings page the notice names (x-starchaser-settings) by itself, from the card or later from
# the bell's list. The sender is detached and gives up after a minute, so a notice left unanswered never keeps a
# recorder command (and its notify-send) running.
failure_notice() {
    setsid timeout 60 /bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser -u critical -A "open=Check graphics" -h string:x-starchaser-settings:hardware "Can't record" "$1" </dev/null >/dev/null 2>&1 &
}
cockpit() { qs -p "$HOME/.config/quickshell/cockpit" ipc call cockpit recorder "$1" >/dev/null 2>&1; }

stop() {
    running || { rm -f "$PIDFILE"; echo "Nothing is recording." >&2; exit 1; }
    pid=$PID; f=$(cat "$OUTFILE" 2>/dev/null)
    kill -INT "$pid"                                    # SIGINT: gsr finishes the file cleanly
    i=0; while kill -0 "$pid" 2>/dev/null && [ $i -lt 50 ]; do sleep 0.1; i=$((i + 1)); done
    if kill -0 "$pid" 2>/dev/null; then
        /bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser -u critical "Recording still running" "Couldn't stop the recorder. Try again."
        exit 1
    fi
    rm -f "$PIDFILE" "$OUTFILE"; cockpit false
    if [ -s "$f" ]; then
        # Result card: a thumbnail, Play, and share=Make smaller to share. Encoding runs after stop returns.
        if command -v starchaser >/dev/null; then
            setsid starchaser capture result recording "$f" </dev/null >/dev/null 2>&1 &
            return
        fi
        # the whole notification waits in the background: it stays in the notification list with its buttons long
        # after the popup leaves, and `stop` must return now, not when (or if) someone presses one
        ( a=$(/bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser -i video-x-generic "Recording saved" "$(basename "$f") in Videos/Recordings" \
                -A open=Play -A folder="Show in folder")
          case $a in open) xdg-open "$f" ;; folder) starchaser files "$DIR" ;; esac ) </dev/null >/dev/null 2>&1 &
    else
        /bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser -u critical "Recording failed" "Nothing was saved. The details are in $LOG."
    fi
}

# Start one recorder and wait a moment to see that it keeps running: 0 = recording (the pidfile is written now, so the
# Screen light comes on only for a real recording), 1 = it quit (its messages are in $LOG; an empty file it left is
# removed). $1 = the output file, the rest = the recorder's command.
launch() {
    out=$1; shift
    setsid "$@" >"$LOG" 2>&1 </dev/null &
    lp=$!
    echo "$lp" > "$STARTING"; echo "$out" > "$OUTFILE"
    sleep 0.6
    if recording_process_alive "$lp"; then
        echo "$lp" > "$PIDFILE.$$"; mv -f "$PIDFILE.$$" "$PIDFILE"; rm -f "$STARTING"
        PID=$lp; return 0
    fi
    rm -f "$STARTING" "$OUTFILE"
    [ -s "$out" ] || rm -f "$out"
    return 1
}
# the recorder's own messages show software graphics (a computer or virtual machine without working graphics
# drivers). Only the software renderers' own names count: the recorder mentions OpenGL and EGL on ordinary runs too,
# so those words would blame graphics for any failure.
basic_graphics() { grep -qiE 'llvmpipe|softpipe|swrast' "$LOG" 2>/dev/null; }

start() {     # $1 = screen | region, $2 = --sound or empty
    if running; then
        # the key in use now (a profile or your own change can move it), never written in here
        k=$(starchaser shortcuts key "Screenshots: Record the screen (start / stop)" 2>/dev/null)
        /bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser "Already recording" "Stop it from the menu > Capture${k:+, or press $k}."
        exit 1
    fi
    # a second press while the first recorder is still being checked: that one answers for both
    [ -n "$(starting_pid)" ] && exit 1
    command -v gpu-screen-recorder >/dev/null || { /bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser -u critical "Can't record" "The screen recorder isn't installed."
        echo "The screen recorder isn't installed." >&2; exit 1; }
    snd=$2; region=; mon=
    if [ "$1" = region ]; then
        region=$(slurp -f '%wx%h+%x+%y') || exit 0          # Esc while dragging: nothing to do
    else
        mon=$(hyprctl monitors -j | python3 -c 'import json,sys; print(next((m["name"] for m in json.load(sys.stdin) if m["focused"]), "focused"))')
    fi
    mkdir -p "$DIR"
    if disk_low; then   # say so now, not a moment after a "Recording your screen" notice
        /bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser -u critical -i drive-harddisk "Can't record: the disk is almost full" "Free up some space, then record again."
        echo "Can't record: the disk is almost full. Free up some space, then record again." >&2
        exit 1
    fi
    f="$DIR/$(date +%Y-%m-%d_%H-%M-%S).mp4"
    # The graphics card encodes when it can, and the recorder falls back to the processor by itself when the card
    # has no video encoder. On basic graphics the recorder can't capture at all, so a processor recorder that copies
    # the screen through the compositor (wf-recorder, H.264 in software) records instead: slower, but it works on
    # every computer.
    if [ -n "$region" ]; then set -- -w region -region "$region"; else set -- -w "$mon"; fi
    [ "$snd" = --sound ] && set -- "$@" -a default_output
    started=; basic=
    if launch "$f" gpu-screen-recorder "$@" -f 60 -k h264 -fallback-cpu-encoding yes -o "$f"; then
        started=1
    elif basic_graphics && basic=1 && command -v wf-recorder >/dev/null; then
        if [ -n "$region" ]; then
            # slurp gave WxH+X+Y; wf-recorder takes "X,Y WxH"
            wh=${region%%+*}; xy=${region#*+}
            set -- -g "${xy%%+*},${xy#*+} $wh"
        else
            set -- -o "$mon"
        fi
        if [ "$snd" = --sound ]; then
            # what the computer plays is the default output's monitor; plain --audio would be the microphone
            sink=$(pactl get-default-sink 2>/dev/null)
            [ -n "$sink" ] && set -- "$@" --audio="$sink.monitor"
        fi
        launch "$f" wf-recorder "$@" -c libx264 -p preset=veryfast -x yuv420p -r 30 -y -f "$f" && started=1
    fi
    if [ -n "$started" ]; then
        cockpit true
        what="Recording your screen"
        [ -n "$region" ] && what="Recording a region"
        [ "$snd" = --sound ] && what="$what, with sound"
        k=$(starchaser shortcuts key "Screenshots: Record the screen (start / stop)" 2>/dev/null)
        stop_button_notice "$PID" "$what" "Stop it with the Stop button${k:+ or press $k}."
        setsid "$0" watch "$PID" </dev/null >/dev/null 2>&1 &
    else
        # say why only when the recorder's own messages show it; anything else gets where the details are
        if [ -n "$basic" ]; then
            why="Screen recording needs working graphics drivers, and this computer is using basic graphics that the screen recorder can't use. Choose Check graphics to review the hardware and drivers. Basic virtual graphics may not support recording."
        else
            why="The screen recorder stopped right away. The details are saved in $LOG."
        fi
        failure_notice "$why"; echo "$why" >&2; exit 1
    fi
}

# Runs beside a recording until it ends: one quiet bell entry at 30 minutes and at 2 hours (never more), and a stop
# with a plain notice when the disk the recordings go to is nearly full (below the larger of 10 GB and 5%).
watch() {
    pid=$1; said30=0; said2h=0
    while kill -0 "$pid" 2>/dev/null; do
        t=$(elapsed_s "$pid"); t=${t:-0}
        if [ "$t" -ge 7200 ] && [ $said2h = 0 ]; then
            said2h=1; said30=1; stop_button_notice "$pid" "Still recording (2 h)" "The recording is $(size_mb) MB so far." --bell
        elif [ "$t" -ge 1800 ] && [ $said30 = 0 ]; then
            said30=1; stop_button_notice "$pid" "Still recording (30 min)" "The recording is $(size_mb) MB so far." --bell
        fi
        if disk_low; then
            "$0" stop-pid "$pid"; end_notices "$pid"
            /bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser -u critical -i drive-harddisk "Recording stopped: the disk is almost full" "The recording was saved in Videos/Recordings. Free up some space before recording again."
            exit 0
        fi
        sleep "${WATCH_INTERVAL:-10}"
    done
    end_notices "$pid"
}

# a misspelled option ("--soud") used to start a recording without sound, and a --help after a command started one
case "$1:${2:-}" in
    *:-h|*:--help) sed -n '3,13p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
esac
case "$1" in
    screen|region|toggle)
        if [ $# -gt 2 ] || { [ -n "${2:-}" ] && [ "$2" != --sound ]; }; then
            echo "starchaser record: $1 takes only --sound after it (got '${2:-$3}'). Run 'starchaser record --help' for more help." >&2
            exit 2
        fi ;;
    stop|status)
        if [ $# -gt 1 ]; then
            echo "starchaser record: $1 takes nothing after it (got '$2'). Run 'starchaser record --help' for more help." >&2
            exit 2
        fi ;;
esac
case "$1" in
    screen|region) start "$1" "$2" ;;
    stop) stop ;;
    stop-pid) running && [ "$PID" = "${2:-}" ] && stop ;;    # a notice's Stop button: only the recording it was for
    watch) watch "${2:?}" ;;
    toggle) if running; then stop; else start screen "$2"; fi ;;
    status)
        if running; then
            t=$(elapsed_s "$PID"); t=${t:-0}
            echo "recording"
            echo "$(( t / 3600 )) h $(( t % 3600 / 60 )) min, $(size_mb) MB, $(cat "$OUTFILE" 2>/dev/null)"
        else echo idle; exit 1; fi ;;
    -h|--help|help) sed -n '3,13p' "$0" | sed 's/^# \{0,1\}//' ;;
    "") echo "starchaser record: no command given. Run 'starchaser record --help' for more help." >&2; exit 2 ;;
    *) echo "starchaser record: unknown command '$1'. Run 'starchaser record --help' for more help." >&2; exit 2 ;;
esac
