#!/bin/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.

set -e

PKG="hollywood"
trap "pkill -f -9 lib/hollywood/ >/dev/null 2>&1; exit 0" EXIT HUP INT QUIT TERM

dir="-v"
widget_dir="$(dirname $0)/../lib/$PKG"
widget1=$(ls "$widget_dir/" | sort -R | head -n1)

if [ -n "$1" ]; then
	SPLITS="$1"
else
	SPLITS=$(ls "$widget_dir" | wc -l)
fi

arrangements="main-horizontal main-vertical tiled"

if [ -z "$TMUX" ]; then
	# Launch our byobu
	byobu new-session -d -s $PKG "/bin/bash"
	byobu send-keys -t $PKG "$0"
	byobu send-keys -t $PKG Enter
	exec byobu attach-session -t $PKG
	exit 1
fi

tmux new-window -n $PKG "$widget_dir/$widget1" \; \
	set-option -g pane-active-border-bg "default" \; \
	set-option -g pane-active-border-fg "default" >/dev/null 2>&1

split=1
sleep 0.5
for w in $(ls "$widget_dir" | sort -R); do
	[ "$w" = "$widget1" ] && continue
	[ "$dir" = "-v" ] && dir="-h" || dir="-v"
	panes=$(tmux lsp -t $PKG)

	#echo "Panes:"
	#echo "$panes"

	# Allow for failed widgets
	splits=$(echo "$panes" | wc -l)
	pane=$((RANDOM % $splits))

	#echo "Splitting: $pane $dir for $w"
	tmux split-window $dir -t ${PKG}.$pane "nice -n 19 $widget_dir/$w" >/dev/null 2>&1
	sleep 0.2
	split=$((split+1))
	if [ $split -ge $SPLITS ]; then
		break
	fi
done

while true; do
	case $(($RANDOM % 3)) in
		0) layout="main-horizontal" ;;
		1) layout="main-vertical" ;;
		2) layout="tiled" ;;
	esac
	tmux select-layout -t $PKG $layout >/dev/null 2>&1 || exit 0
	tmux swap-pane -s 0 -t $(($SPLITS*$RANDOM/32767)) >/dev/null 2>&1 || exit 0
	sleep 10
done

exit 0
