#!/bin/bash
# Multi-Monitor - Multiple monitor detection xinerama script
# Script via TheeMahn <theemahn@ultimateedition.info>
#
# This script will detect ports and monitors enabling only monitors
# that are connected.
# title		:multi-monitor
# description	:detect monitors enabling only monitors that are connected.
# author	:Glenn "TheeMahn" Cady <theemahn@ultimateedition.info>
# date		:04/29/2014
# version	:1.7.3
# usage		:multi-monitor --help
# notes		:See change-log below for further information.
# bash_version	:4.2.8(1)-release
# ==============================================================================
#
# Change-log:
# 1.7.1-6 	Initial public release
#
# 1.7.1-7	Added support for mirroring monitors
#
# 1.7.1-8	Added boot support.
#		Added bash auto completion
#		Code cleanup using software I have written (code-cleanup). 
#
# 1.7.2		Added initial touch screen support.  Will provide commands, but
#		not implement touch screen calibration.
#		Added bash auto-completion
#		Added scan function
#
# 1.7.3		Added EyeCandy routines
#		Additional functionality vertical orientation.
# ==============================================================================
# Multi-monitor(c) 2014 Glenn Cady under GNU GPL v2.0+ by
# Glenn "TheeMahn" Cady <theemahn@ultimateedition.info>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

MULTIMONITOR="1.7.3"
BUILDDATE="04/29/2014"

# set colors so errors etc. stand out.

txtblk='\e[0;30m' # Black - Regular
txtred='\e[0;31m' # Red
txtgrn='\e[0;32m' # Green
txtylw='\e[0;33m' # Yellow
txtblu='\e[0;34m' # Blue
txtpur='\e[0;35m' # Purple
txtcyn='\e[0;36m' # Cyan
txtwht='\e[0;37m' # White
bldblk='\e[1;30m' # Black - Bold
bldred='\e[1;31m' # Red
bldgrn='\e[1;32m' # Green
bldylw='\e[1;33m' # Yellow
bldblu='\e[1;34m' # Blue
bldpur='\e[1;35m' # Purple
bldcyn='\e[1;36m' # Cyan
bldwht='\e[1;37m' # White
unkblk='\e[4;30m' # Black - Underline
undred='\e[4;31m' # Red
undgrn='\e[4;32m' # Green
undylw='\e[4;33m' # Yellow
undblu='\e[4;34m' # Blue
undpur='\e[4;35m' # Purple
undcyn='\e[4;36m' # Cyan
undwht='\e[4;37m' # White
bakblk='\e[40m'   # Black - Background
bakred='\e[41m'   # Red
badgrn='\e[42m'   # Green
bakylw='\e[43m'   # Yellow
bakblu='\e[44m'   # Blue
bakpur='\e[45m'   # Purple
bakcyn='\e[46m'   # Cyan
bakwht='\e[47m'   # White
txtrst='\e[0m'    # Text Reset

# Retrieve number of lines & columns the screen supports.
LINEZ=$(tput lines)
COLUMNZ=$(tput cols)
SPLIT=0
GUI=$(echo $DISPLAY)

# check to see if notify is installed & if sound is supported.
NOTIFY=$(which notify-send)
SOUND=$(which canberra-gtk-play)

# Declare integer to span eyecandy routine
declare -i RR
RR=0
declare -i TT
TT=0

function Columnize () {
	#echo $COLUMNZ
	MAINS=$(echo "scale=2; $COLUMNZ-30" | bc)
	MAINS=${MAINS%.*}
	#echo $MAINS
	MAINS=$(expr $MAINS - 2)
	MAINS=$(expr $MAINS / 4)
	#echo $MAINS
	if ! [[ $1 ]]; then
		#"#" "DEV" "VENDOR" "LABEL" "TYPE" "SIZE"
		printf "%-0s %-1s %-1s %-20s %-26s %-7s %-1s\n" "▒" "#" "DEV" "VENDOR" "LABEL" "TYPE" "SIZE" 
	else
		#MAINS=$(expr $MAINS / 2)
		printf "%-0s %-1s %-1s %-20s %-26s %-7s %-1s\n" "▒" $1 $2 $3 $4 $5 $6 
	fi
}

# Function for outputing to X-11 screen a notification of completion and playing sound.
# The sound file is from the "Optional" ultimate-edition-sound-theme
function Notification () {
	X=$( pidof X )
	if [[ -f "/usr/share/sounds/Ultimate Edition Sound Scheme/stereo/itisdone.wav" ]]; then
		WAVE=1
	fi
	if [[ $X && $NOTIFY ]]; then
		a=$(notify-send "ThumbOS" "$1" -i /usr/share/ultimate_edition/logo.png -t 5000)
	else
		echo $1
	fi
	if [[ $SOUND && $WAVE ]]; then
		a=$(canberra-gtk-play -i itisdone 2>/dev/null)
	fi
}

#Usage: EyeCandy Message
function EyeCandy() {
	# Verify a message has been sent to this function otherwise do squat.
	# Example: EyeCandy ('Repostorm $REPOVERSION is entering extraction mode.')
	# ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
	# ▒ Repostorm 1.7.7 is entering extraction mode. ▒
	# ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
	STP="$1"
	if [[ $STP ]]; then
		STRLEN=${#STP}
		STRLEN=$(expr $STRLEN + 3)
		RR=0; while [ $RR -le $STRLEN ]; do echo -n "▒"; RR=RR+1; done; echo;
		echo -e "▒ "$STP" ▒"
		RR=0; while [ $RR -le $STRLEN ]; do echo -n "▒"; RR=RR+1; done; echo;
	fi
}

# Draws a bar across the screen based on screensize detected (columnz)
function FullBar() {
	RR=1; while [ $RR -lt $COLUMNZ ]; do echo -n "▒"; RR=RR+1; done; echo;
}

# Center data passed to function on screen
function Center () {
	STP=$1
	if [[ $STP ]]; then
		STRLEN=${#STP}
		CENTER=$(expr $STRLEN / 2)
		TCENTER=$(expr $COLUMNZ / 2)
		DISTANCE=$(expr $TCENTER - $CENTER)
		DISTANCE=$(expr $DISTANCE - 2)
		RR=0; while [ $RR -le $DISTANCE ]; do echo -n "▒"; RR=RR+1; done;
		echo -n " $STP "
		TT=0; while [ $TT -le $DISTANCE ]; do echo -n "▒"; TT=TT+1; done;
		CALC=$(expr $RR + $TT + $STRLEN + 2)
		if [[ $CALC -lt $COLUMNZ ]]; then
			while [ $CALC -lt $COLUMNZ ]; do echo -n "▒"; CALC=CALC+1; done; echo;
		fi
	fi
		# Dubugging:
		# echo "STRING LEN: $STRLEN CENTER: $CENTER TOTAL CNTER: $TCENTER RR=$RR TT=$TT COLUMNZ: $COLUMNZ CALC: $CALC DISTANCE: $DISTANCE"
}

# Debugging function to monitor passed arguments.
function CommandLineIntrepreter(){
	echo -e "${bldgrn}Number of switches passed: $#"
	for var in "$@"
	do
		array_counter=$(($array_counter + 1))
		echo "Switch $array_counter: $var"
	done
}

function Scan {
	HEADER
	if ! [[ $GUI ]]; then
		echo -e "${bldred}Error: NO X11 Subsystem found, exiting..."
		exit 0;
	fi

	MONITORS=`xrandr | grep ' connected' -c`
	PORTS=`xrandr | grep 'connected' -c`
	TOUCHSCREEN=$(xinput --list | grep -i 'touch' | cut -d ' ' -f5-99 | sed 's/\[.*//g')
	ID=$(echo $TOUCHSCREEN | cut -d'=' -f2)
	echo -e "${bldgrn}$PORTS Ports detected and $MONITORS Monitors detected."
	echo -e "${bldgrn}Enabling $MONITORS monitors(s) and setting default resolution(s).${txtrst}"
	if [[ $TOUCHSCREEN ]]; then
		echo -e "\n${bldgrn}Touchscreen device detected: $TOUCHSCREEN"
		DEVICE=$(echo $TOUCHSCREEN | sed 's/ id=.*//g')
		echo -e "${bldgrn}DEVICE:$DEVICE"
		echo -e "${bldgrn}ID: $ID${txtrst}"
		
	fi
	echo ""
	echo "Port(s) connected: "
	xrandr | grep ' connected' | cut -d' ' -f1
	echo ""
	echo "Default resolution(s):"
	xrandr | grep '*+' | grep 'x'
	# begin detection & generate command to be executed.
	OUTPUTS=`xrandr | grep ' connected' | cut -d' ' -f1`
	PRIMARY=`xrandr | grep -m 1 ' connected' | cut -d' ' -f1`
	EXECUTE=""

	for CURRENT in $OUTPUTS
	do
		EXECUTE+="--output $CURRENT --auto "
	done
	if [[ $2 ]]; then
		if [[ $2 != "--above" && $2 != "--below" ]]; then
			echo -e "${bldred}Error: Invalid switch $3"
		else
			EXECUTE+="$2 of $PRIMARY"
		fi
	else
		EXECUTE+="--right-of $PRIMARY"
	fi

	echo "Command to be executed:"
	echo "xrandr $EXECUTE"

	if [[ $TOUCHSCREEN ]]; then
		echo -e "${bldred}TO ENABLE TOUCHSCREEN CALIBRATION COMMANDS:${txtrst}"
		echo "xsetwacom set \"$DEVICE\" MapToOutput VGA-0"
		echo "xsetwacom set "$ID" MapToOutput VGA-0"
	fi

	if [[ $1 != '-s' && $1 != '--scan' ]]; then
		echo -e ${bldgrn}"If you can read this we were successful.${txtrst}"
		echo -e "${bldgrn}If you would like to make changes permenant use boot switch.${txtrst}"
		xrandr $EXECUTE
	fi
}

function Boot {
	HEADER
	if [[ $2 == "" ]]; then
		echo "Command sympnosis: multi-monitor -b <on/off>"
		exit 0
	fi
	if [[ $2 == "on" ]]; then
		echo "Installing bootscript for multiple monitors."
		sudo cp /usr/share/ultimate_edition/multi-monitor.desktop /etc/xdg/autostart/
		exit 0
	fi

	if [[ $2 == "off" ]]; then
		echo "Removing bootscript for multiple monitors."
		sudo rm /etc/xdg/autostart/multi-monitor.desktop
	fi
}

function Mirror {
	HEADER
	MONITORS=`xrandr | grep ' connected' -c`
	PORTS=`xrandr | grep 'connected' -c`
	TOUCHSCREEN=$(xinput --list | grep -i 'touch' | cut -d ' ' -f5-99 | sed 's/\[.*//g')
	ID=$(echo $TOUCHSCREEN | cut -d'=' -f2)
	echo -e "${bldgrn}$PORTS Ports detected and $MONITORS Monitors detected."
	echo -e "${bldgrn}Enabling $MONITORS monitors(s) and setting default resolution(s).${txtrst}"
	if [[ $TOUCHSCREEN ]]; then
		echo -e "${bldgrn}Touchscreen detected: $TOUCHSCREEN"
		DEVICE=$(echo $TOUCHSCREEN | sed 's/ id=.*//g')
		echo -e "${bldgrn}DEVICE:$DEVICE"
		echo -e "${bldgrn}ID: $ID${txtrst}"
		
	fi
	echo ""
	echo "Port(s) connected: "
	xrandr | grep ' connected' | cut -d' ' -f1
	echo ""
	echo "Default resolution(s):"
	xrandr | grep '*+' | grep 'x'

# begin detection & generate command to be executed.
	OUTPUTS=`xrandr | grep ' connected' | cut -d' ' -f1`
	PRIMARY=`xrandr | grep -m 1 ' connected' | cut -d' ' -f1`
	EXECUTE="--output "

	for CURRENT in $OUTPUTS
	do
		EXECUTE+="$CURRENT --auto --same-as "
	done
	EXECUTE=$(echo $EXECUTE | sed -r 's/(.*)--auto.*/\1/')
	echo "Command to be executed: xrandr $EXECUTE"
#xrandr --output HDMI-0 --auto --mode 1920x1200 --same-as DVI-0
	echo "If you can read this we were successful."
	echo "If you would like to make changes permenent use boot switch."
# the below command will be implemented after feedback of bugs if any.
	xrandr $EXECUTE
	if [[ $TOUCHSCREEN ]]; then
		echo -e "${bldred}TO ENABLE TOUCHSCREEN CALIBRATION COMMANDS:${txtrst}"
		echo "xsetwacom set \"$DEVICE\" MapToOutput VGA-0"
		echo "xsetwacom set "$ID" MapToOutput VGA-0"
	fi
}

# provide info to user
function HEADER {
	EyeCandy "Multi-monitor Version: $MULTIMONITOR, Build date: $BUILDDATE."
	echo -e "${bldgrn}GNU multi-monitor home page: <http://www.ultimateedition.info/>."
	echo "E-mail bug reports to: <theemahn@ultimateedition.info>."
	echo -e "Be sure to include the word \"multi-monitor\" somewhere in the Subject: field.${txtrst}"
}

function Help() {
	HEADER
	if [[ $1 == "" ]];
	then
		PRAM="ALL"
	else
		PRAM=$1

	fi
	case $PRAM in
		ALL)
echo -e "
${bldwht}Usage: multi-monitor -<-COMMAND>${txtrst}
	possible [COMMAND]...
	-b	--boot			Set multi-monitor to load on bootup
	-d	--dual			Set xinerama for monitors
	-m	--mirror		Set mirror mode for monitors
	-s	--scan			Scans for monitors
	-h	--help			This help message
	-v	--version		Dump version info

${bldgrn}multi-monitor --help [COMMAND] for further information.${txtrst}";;
		ALL|b|boot)
			echo -e "
${bldwht}Usage boot;${txtrst}
${txtgrn}multi-monitor -b <on/off>${txtrst}
  Installs a startup script [on] to engage multi-monitor on boot up or
  removes [off] startup script.";;
		ALL|d|dual)
			echo -e "
${bldwht}Usage dual;${txtrst}
${txtgrn}multi-monitor -d${txtrst}
  Detects ports and monitors enabling only monitors that are conected
  and sets xinerama view spanning connected monitors.";;
		ALL|m|mirror)
			echo -e "
${bldwht}Usage mirror;${txtrst}
${txtgrn}multi-monitor -m${txtrst}
  Detect ports and monitors enabling only monitors that are conected
  and sets mirror view.";;
		ALL|v|version)
			echo -e "
${bldwht}Usage version;${txtrst}
${txtgrn}multi-monitor -v${txtrst}
  Displays multi-monitors version number and exits.";;
		ALL|h|help|\?)
			echo -e "
${bldwht}Useage Help [COMMAND];${txtrst}
${txtgrn}multi-monitor -h [COMMAND]${txtrst}
  Displays this message. Futher information multi-monitor help [COMMAND]
  or refer to the manpages.

man multi-monitor"
esac
exit 0
}

function Version {
HEADER
exit 0
}

case "$1" in
	-h|--help|-\?) Help $2; exit 0;;
	-v|--version) Version; exit 0;;
	-s|--scan) Scan $*; exit 0;;
	-d|--dual) Scan $*; exit 0;;
	-m|--mirror) Mirror $*; exit 0;;
	-b|--boot) Boot $*; exit 0;;
	*) Help; exit 0;;
esac
