#!/usr/bin/env bash
# N.B.: Use bash for $RANDOM
#
# hollywood: create a hollywood suitable consoles of tech geekery
#
# Copyright 2014 Dustin Kirkland <dustin.kirkland@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

PKG="hollywood"
VERSION="1.3.0"
cleanup() {
	trap - INT TERM HUP EXIT
	# Close the window the widgets live in; that ends every widget
	[ -n "$WIN" ] && tmux kill-window -t "$WIN" >/dev/null 2>&1
	# Before the session goes: this script runs inside it and dies with it
	[ -n "$STATE" ] && rm -rf "$STATE"
	if [ -n "$HOLLYWOOD_OWN_SESSION" ]; then
		# The key table belongs to this show; the session only if this script created it
		tmux unbind-key -a -T $PKG >/dev/null 2>&1
		tmux kill-session -t $PKG >/dev/null 2>&1
	fi
	exit 0
}

# Widgets that may be dealt: all but the ones closed by hand in this show
candidates() {
	ls "$WIDGET_DIR" | grep -vxF -f "$STATE/banned" | sort -R
}

# Start one widget in a new pane and remember which pane runs it
start_widget() {
	local id=
	id=$(tmux split-window "$1" -P -F '#{pane_id}' -t "$2" "nice -n 19 $WIDGET_DIR/$3" 2>/dev/null)
	[ -n "$id" ] || return 0
	echo "$id $3" >> "$STATE/panes"
	# the name on the pane's border, and since when it is shown
	tmux set-option -p -t "$id" @widget "$3" \; set-option -p -t "$id" @since "$(date +%s)" >/dev/null 2>&1
}

spin_up() {
	local w=
	local splits=
	local pane=
	local dir="v"
	local split=1
	sleep 0.5
	SPLITS=$(cat "$STATE/splits")
	for w in $(candidates); do
		# a widget that is on screen already is not dealt a second time
		tmux list-panes -t "$WIN" -F '#{pane_id}' 2>/dev/null | while read -r id; do
			awk -v p="$id" '$1 == p {w = $2} END {print w}' "$STATE/panes"
		done | grep -qxF "$w" && continue
		split=$(tmux list-panes -t "$WIN" 2>/dev/null | wc -l)
		[ "$split" -ge "$SPLITS" ] && break
		[ "$dir" = "-v" ] && dir="-h" || dir="-v"
		# Allow for failed widgets
		splits=$split
		[ "$splits" -ge 1 ] || break
		pane=$((RANDOM % splits))
		start_widget $dir "$WIN.$pane" "$w"
		sleep 0.2
	done
}

# The bar at the bottom: every control as a button that can be clicked, and
# what the show is doing right now.  Called once a second by the loop.
toolbar() {
	[ -n "$HOLLYWOOD_OWN_SESSION" ] || return 0
	local b="#[fg=colour252,bg=colour238]" e="#[default]#[norange] "
	local state= closed=
	closed=$(grep -c . "$STATE/banned" 2>/dev/null)
	if [ "$(tmux display-message -p -t "$WIN" '#{window_zoomed_flag}' 2>/dev/null)" = "1" ]; then
		state="#[fg=colour220]zoomed - z shows all"
	elif [ -e "$STATE/paused" ]; then
		state="#[fg=colour220]paused"
	else
		state="next $CHANGE in $1 s"
	fi
	local restore=
	[ "${closed:-0}" -gt 0 ] && restore="#[range=user|restore]$b r back ($closed) $e"
	tmux set-option -t $PKG status-format[0] "#[fg=colour114,bold] $PKG #[default] \
#[range=user|swap]$b s swap $e#[range=user|keep]$b k keep $e#[range=user|close]$b x close $e#[range=user|menu]$b a open $e$restore\
#[range=user|zoom]$b z zoom $e#[range=user|pause]$b p pause $e#[range=user|deal]$b n deal $e\
#[range=user|less]$b - $e$(tmux list-panes -t "$WIN" -F x 2>/dev/null | wc -l | tr -d ' ') panes #[range=user|more]$b + $e\
#[range=user|help]$b ? $e#[range=user|quit]$b q quit $e#[align=right]#[fg=colour244]$state " >/dev/null 2>&1
}

# Every key runs in the background (run-shell -b): a command that waits - a
# popup, a menu - would otherwise hold up the tmux server it is waiting for.
# Keys and mouse for the show.  They live in a key table of their own that only
# this session uses, so nothing changes in the user's other tmux sessions - and
# that is why a show started inside somebody's own session has no controls.
controls() {
	[ -n "$HOLLYWOOD_OWN_SESSION" ] || return 0
	local ctl="'$SHARE_DIR/ctl' '$STATE'"
	tmux set-option -t $PKG mouse on \; \
		set-option -t $PKG key-table $PKG \; \
		set-option -t $PKG status-style "bg=colour235,fg=colour246" \; \
		set-option -w -t "$WIN" pane-border-status top \; \
		set-option -w -t "$WIN" pane-border-format "#{?pane_active,#[fg=colour114 bold],#[fg=colour244]} #{@widget}#{?@keep, [kept],} " \; \
		set-option -w -t "$WIN" pane-border-style "fg=colour238" \; \
		set-option -w -t "$WIN" pane-active-border-style "fg=colour114" \; \
		bind-key -T $PKG MouseDown1Pane select-pane -t = \; \
		bind-key -T $PKG DoubleClick1Pane run-shell -b -t = "$ctl zoom '#{pane_id}'" \; \
		bind-key -T $PKG MouseDown3Pane run-shell -b -t = "$ctl panemenu '#{pane_id}'" \; \
		bind-key -T $PKG MouseDrag1Border resize-pane -M \; \
		bind-key -T $PKG MouseDown1Status run-shell -b "$ctl button '#{mouse_status_range}'" \; \
		bind-key -T $PKG x run-shell -b "$ctl close '#{pane_id}'" \; \
		bind-key -T $PKG s run-shell -b "$ctl swap '#{pane_id}'" \; \
		bind-key -T $PKG k run-shell -b "$ctl keep '#{pane_id}'" \; \
		bind-key -T $PKG z run-shell -b "$ctl zoom '#{pane_id}'" \; \
		bind-key -T $PKG a run-shell -b "$ctl menu" \; \
		bind-key -T $PKG r run-shell -b "$ctl restore" \; \
		bind-key -T $PKG n run-shell -b "$ctl deal" \; \
		bind-key -T $PKG p run-shell -b "$ctl pause" \; \
		bind-key -T $PKG Space run-shell -b "$ctl pause" \; \
		bind-key -T $PKG + run-shell -b "$ctl more" \; \
		bind-key -T $PKG - run-shell -b "$ctl less" \; \
		bind-key -T $PKG ? display-popup -w 54 -h 25 -T " $PKG " -E "$ctl helppage" \; \
		bind-key -T $PKG q run-shell -b "$ctl quit" >/dev/null 2>&1
}

WIDGET_DIR="$(cd "$(dirname "$0")/../lib/$PKG" && pwd)"
SHARE_DIR="$(cd "$(dirname "$0")/../share/$PKG" && pwd)"
# Determine the default number of splits based on CPU count
# Default to 2x the number of processors, but cap at available widgets
NPROC=$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 4)
MAX_WIDGETS=$(ls "$WIDGET_DIR" | wc -l)
DEFAULT_SPLITS=$((NPROC * 2))
# Cap at the number of available widgets
[ $DEFAULT_SPLITS -gt $MAX_WIDGETS ] && DEFAULT_SPLITS=$MAX_WIDGETS
SPLITS=$DEFAULT_SPLITS
DELAY=15
# what happens by itself every DELAY seconds: one pane gets another widget
# (swap), or - as upstream does it, with -r - the whole screen is built anew
CHANGE=swap
while [ ! -z "$1" ]; do
	case "$1" in
		-d|--delay)
			DELAY="$2"
			shift 2
		;;
		-s|--splits)
			SPLITS="$2"
			shift 2
		;;
		-r|--redeal)
			CHANGE=deal
			shift
		;;
		-V|--version)
			echo "$PKG $VERSION"
			exit 0
		;;
		-h|--help)
			exec man $PKG
		;;
		*)
			echo "usage: $PKG [-s SPLITS] [-d DELAY] [-r] [--version]" >&2
			exit 2
		;;
	esac
done

widget1=$(ls "$WIDGET_DIR/" | sort -R | head -n1)
arrangements="main-horizontal main-vertical tiled"

if [ -z "$TMUX" ]; then
	# Not in a tmux session: start one, with
	# byobu if it's found, else with plain tmux
	command -v byobu >/dev/null 2>&1
	if [ $? -eq 0 ]; then
		tmux_launcher=byobu
	else
		tmux_launcher=tmux
	fi
	$tmux_launcher new-session -d -s $PKG "bash"
	$tmux_launcher send-keys -t $PKG "HOLLYWOOD_OWN_SESSION=1 $0 -s $SPLITS -d $DELAY$([ $CHANGE = deal ] && echo ' -r'); exit"
	$tmux_launcher send-keys -t $PKG Enter
	exec $tmux_launcher attach-session -t $PKG
	exit 1
fi

# What the show remembers: the pane count, which pane runs which widget, the
# widgets closed by hand, and the flags the controls set
STATE=$(mktemp -d "${TMPDIR:-/tmp}/$PKG.XXXXXXXX") || exit 1
: > "$STATE/banned"
: > "$STATE/panes"
echo "$SPLITS" > "$STATE/splits"
echo "$MAX_WIDGETS" > "$STATE/max"
echo "$WIDGET_DIR" > "$STATE/widgets"

trap cleanup INT TERM HUP EXIT
WIN=$(tmux new-window -P -F '#{window_id}' -n $PKG "$WIDGET_DIR/$widget1") || exit 1
echo "$WIN" > "$STATE/window"
first=$(tmux list-panes -t "$WIN" -F '#{pane_id}' | head -n1)
echo "$first $widget1" >> "$STATE/panes"
tmux set-option -p -t "$first" @widget "$widget1" \; set-option -p -t "$first" @since "$(date +%s)" >/dev/null 2>&1
controls
toolbar "$DELAY"

spin_up

# Build the screen anew.  Panes the user keeps (k) stay; without any, one pane
# stays so that the window does.
deal() {
	local stay= id=
	stay=$(tmux list-panes -t "$WIN" -F '#{?@keep,1,0} #{pane_id}' 2>/dev/null | awk '$1 == 1 {print $2}')
	[ -n "$stay" ] || stay=$(tmux list-panes -t "$WIN" -F '#{pane_id}' 2>/dev/null | tail -n 1)
	for id in $(tmux list-panes -t "$WIN" -F '#{pane_id}' 2>/dev/null); do
		echo "$stay" | grep -qxF "$id" || tmux kill-pane -t "$id" 2>/dev/null
	done
	# forget the panes that are gone
	tmux list-panes -t "$WIN" -F '#{pane_id}' 2>/dev/null | while read -r id; do
		grep "^$id " "$STATE/panes" | tail -n 1
	done > "$STATE/panes.new"
	mv "$STATE/panes.new" "$STATE/panes"
	spin_up
}

zoomed() {
	[ "$(tmux display-message -p -t "$WIN" '#{window_zoomed_flag}' 2>/dev/null)" = "1" ]
}

i=0
while true; do
	if [ -e "$STATE/deal" ]; then
		# asked for by a key: now, and the clock starts again
		rm -f "$STATE/deal"
		deal
		i=0
	elif [ -e "$STATE/paused" ] || zoomed; then
		# the clock stands still: somebody is looking at one pane, or wants it quiet
		:
	else
		i=$((i+1))
		if [ "$i" -ge "$DELAY" ]; then
			# by default one pane changes and the rest of the screen stays as the
			# user arranged it; -r builds everything anew as upstream does
			if [ "$CHANGE" = deal ]; then
				deal
			else
				"$SHARE_DIR/ctl" "$STATE" swap
			fi
			i=0
		fi
	fi
	toolbar $((DELAY - i))
	if tmux list-panes -t "$WIN" -F x 2>/dev/null | grep -q x; then
		sleep 1
		continue
	fi
	exit 0
done
