#!/bin/sh

RED='\033[0;31m'
NC='\033[0m' # No Color
BOLD='\016[1m'
NORMAL='\016[0m'

rate1="60"
rate2="60"

ModifyMonitorsResolutionPrecise() {
	monfile="/home/pcscale/.config/monitors.xml"
	if [ -f $monfile ]; then
		cp -f $monfile $monfile.bak

		xmlstarlet ed -P -u "//monitors/configuration/output[@name='$1']/width" -v "$2" -u "//monitors/configuration/output[@name='$1']/height" -v "$3" -u "//monitors/configuration/output[@name='$1']/x" -v "$4" -u "//monitors/configuration/output[@name='$1']/y" -v "$5" -u "//monitors/configuration/output[@name='$1']/primary" -v "yes" -u "//monitors/configuration/output[@name='$1']/rotation" -v "$6" $monfile > /tmp/monitors.xml
		cp -f /tmp/monitors.xml $monfile 

		if [ "$7" != "-" ]; then
			xmlstarlet ed -P -u "//monitors/configuration/output[@name='$7']/width" -v "$8" -u "//monitors/configuration/output[@name='$7']/height" -v "$9" -u "//monitors/configuration/output[@name='$7']/x" -v "$10" -u "//monitors/configuration/output[@name='$7']/y" -v "${11}" -u "//monitors/configuration/output[@name='$7']/primary" -v "no" -u "//monitors/configuration/output[@name='$7']/rotation" -v "$12" $monfile > /tmp/monitors.xml
			cp -f /tmp/monitors.xml $monfile
		fi 
		chown pcscale:pcscale $monfile
		rm -f /tmp/monitors.xml
	else
		echo "$monfile not found!"
	fi
}

# - Add primary
# xmlstarlet ed -i "/monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$1']/.." -t elem -n "primary" -v "yes"  monitors.xml
# - Remove primary
# xmlstarlet ed -d "/monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$1']/../../primary" monitors.xml
# - remove transform node
# xmlstarlet ed -d "/monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$1']/../../transform
# - copia un node transform desde un fitxer		
# xmlstarlet ed -i "/monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$1']/.." -t elem -n "transform" -v "$(xmlstarlet sel -t -c '//transform/*' transform.xml)" monitors.xml | xmlstarlet unesc		
ModifyMonitorsResolutionBionic() {
	monfile="/home/pcscale/.config/monitors.xml"
	tmpfile="/tmp/monitors.xml"
	tmpfile2="/tmp/monitors2.xml"
	trffile="/tmp/transform.xml"
	if [ -f $monfile ]; then
		cp -f $monfile ${monfile}.bak
		
		# Generate tmp file (transform node)
		echo "<transform>" > $trffile
		echo "  <rotation>right</rotation>" >> $trffile
		echo "  <flipped>no</flipped>" >> $trffile
		echo "</transform>" >> $trffile

		# primary monitor
		echo Primary
		xmlstarlet ed -O -P \
			-u "//monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$1']/../mode/width" -v "$2" \
			-u "//monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$1']/../mode/height" -v "$3" \
			-u "//monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$1']/../mode/rate" -v "$rate1" \
			-u "//monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$1']/../../x" -v "$4" \
			-u "//monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$1']/../../y" -v "$5" $monfile > $tmpfile

		if [ "$6" = "normal" ]; then
			echo "---delete transform node on primary"
			xmlstarlet ed -d "/monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$1']/../../transform" $tmpfile > $tmpfile2
			mv -f $tmpfile2 $tmpfile
		else
			path="/monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$1']/../../transform"
			found=$(xmlstarlet sel -T -t -v "$path" $monfile)
			#echo -----$found----
			if [ -z "$found" ]; then
				echo "---create transform node on primary"
				xmlstarlet ed -O -i "/monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$1']/.." -t elem -n "transform" -v "$(xmlstarlet sel -t -c '//transform/*' $trffile)" $tmpfile | xmlstarlet unesc > $tmpfile2
				mv -f $tmpfile2 $tmpfile
			fi
			xmlstarlet ed -O -P -u "//monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$1']/../../transform/rotation" -v "$6" $tmpfile > $tmpfile2
			mv -f $tmpfile2 $tmpfile
		fi
		cp -f $tmpfile $monfile 

		# secondary monitor
		echo Secondary
		if [ "$7" != "-" ]; then
			xmlstarlet ed -O -P \
				-u "//monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$7']/../mode/width" -v "$8" \
				-u "//monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$7']/../mode/height" -v "$9" \
				-u "//monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$7']/../mode/rate" -v "$rate2" \
				-u "//monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$7']/../../x" -v "${10}" \
				-u "//monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$7']/../../y" -v "${11}" $monfile > $tmpfile
			
			if [ "${12}" = "normal" ]; then
				echo "---delete transform node on secondary"
				xmlstarlet ed -O -d "/monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$7']/../../transform" $tmpfile > $tmpfile2
				mv -f $tmpfile2 $tmpfile
			else
				path="/monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$7']/../../transform"
				found=$(xmlstarlet sel -T -t -v "$path" $monfile)
				#echo -----$found----
				if [ -z "$found" ]; then
				echo "---create transform node on secondary"
					xmlstarlet ed -O -i "/monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$7']/.." -t elem -n "transform" -v "$(xmlstarlet sel -t -c '//transform/*' transform.xml)" $tmpfile | xmlstarlet unesc > $tmpfile2
					mv -f $tmpfile2 $tmpfile
				fi
				xmlstarlet ed -O -P -u "//monitors/configuration/logicalmonitor/monitor/monitorspec[connector='$7']/../../transform/rotation" -v "${12}" $tmpfile > $tmpfile2
				mv -f $tmpfile2 $tmpfile
			fi
			cp -f $tmpfile $monfile
		fi 
		chown pcscale:pcscale $monfile
		rm -f $tmpfile
		rm -f $tmpfile2
		rm -f $trffile
	else
		echo "$monfile not found!"
	fi
}

ModifyX11MonitorsResolution() {
	sfile="/home/pcscale/resolution.conf"
	conf_file="/usr/share/X11/xorg.conf.d/52-front_resolution.conf"
	echo Section \"Monitor\" > $sfile
    echo '\t'Identifier \"$1\" >> $sfile
    echo '\t'Option \"PreferredMode\" \"$2x$3\" >> $sfile
	echo EndSection >> $sfile
	sudo pcs-exec mv -f $sfile $conf_file
	conf_file="/usr/share/X11/xorg.conf.d/52-back_resolution.conf"
	echo Section \"Monitor\" > $sfile
    echo '\t'Identifier \"$4\" >>$sfile
    echo '\t'Option \"PreferredMode\" \"$5x$6\" >> $sfile
	echo EndSection >> $sfile
	sudo pcs-exec mv $sfile $conf_file
}

CreatePCSResolution() {
	target_old="/usr/local/bin/pcs-resolution"
	target="/home/pcscale/.xprofile"
#	echo "#!/bin/bash" > $target
#	echo " " >> $target	
	echo "xrandr | grep 800x480" > $target
	echo 'if [ $? -ne 0 ]; then' >> $target
	echo '\txrandr --newmode "800x480"   29.50  800 824 896 992  480 483 493 500 -hsync +vsync' >> $target
	echo '\t'"xrandr --addmode $1 800x480" >> $target
	echo "fi"  >> $target	
	echo "xrandr --output $1 --mode $2x$3" >> $target
	echo " "  >> $target	

	sudo pcs-exec rm -f $target_old

#	sudo pcs-exec chown root:root $target
#	sudo pcs-exec chmod +x $target
#	sudo pcs-exec mv $target /usr/local/bin
}

ShowParameters() {
	printf "\n\nIncorrect parameters. This is the correct syntax:\n"
	printf "\tpcs-set-video p1 p2 p3 p4 p5 p6\n"
	printf " Where:\n"
	printf "  p1=Front screen with [1024, 800, ...]\n"
	printf "  p2=Front screen height [768, 600, 480, ...]\n"
	printf "  p3=Front screen rotation [normal, left, right, upside_down]\n"
	printf "  p4=Back screen with [1024, 800, ...]\n"
	printf "  p5=Back screen height [768, 600, 480, ...]\n"
	printf "  p6=Back screen rotation [normal, left, right, upside_down]\n"
	printf "\n"
	exit 1
}

FilterParams() {
	if [ $1 -eq 1024 ] || [ $1 -eq 800 ] || [ $1 -eq 600 ]; then
		w1="$1"
	else
		printf "Bad parameter 1: $1.\n"
		exit 1
	fi
	if [ $2 -eq 768 ] || [ $2 -eq 600 ] || [ $2 -eq 480 ] || [ $2 -eq 800 ]; then
		h1="$2"
	else
		printf "Bad parameter 2: $2.\n"
		exit 1
	fi
	if [ $4 -eq 1024 ] || [ $4 -eq 800 ] || [ $4 -eq 1280 ]; then
		w2="$4"
	else
		printf "Bad parameter 4: $4.\n"
		exit 1
	fi
	if [ $5 -eq 768 ] || [ $5 -eq 480 ] || [ $5 -eq 600 ] || [ $5 -eq 768 ]; then
		h2="$5"
	else
		printf "Bad parameter 5: $5.\n"
		exit 1	
	fi
	
	if [ "$3" = "normal" ] || [ "$3" = "left" ] || [ "$3" = "right" ] || [ "$3" = "upside_down" ]; then
		r1="$3"
	else
		printf "Bad parameter 3: $3.\n"
		exit 1
	fi
	if [ "$6" = "normal" ] || [ "$6" = "left" ] || [ "$6" = "right" ] || [ "$6" = "upside_down" ]; then
		r2="$6"
	else
		printf "Bad parameter 6: $6.\n"
		exit 1	
	fi
}

ShowOptions_() {
	SH="\033[4m"
	EH="\033[24m"
	
	printf "\nAvailable options:\n"

	printf "\n ${SH}"
	printf "Normal |  Front display  9\"  |   180º"
	printf "${EH}" 
	printf "\t\t${SH}"
	printf "Normal |  Front display 12\"  |   180º"
	printf "${EH}\n" 
	printf "  <1>   -  Back display   9\"  -   <4> \t\t <7>   -  Back display   9\"  -   <10>\n" 
	printf "  <2>   -  Back display  12\"  -   <5> \t\t <8>   -  Back display  12\"  -   <11>\n" 
	printf "  <3>   -  Back display  15\"  -   <6> \t\t <9>   -  Back display  15\"  -   <12>\n" 

	#	printf "\n ${SH}"
	#	printf "Normal |  Front display 12\"  |   180º"
	#printf "${EH}" 
	#printf "   7    -  Back display   9\" - 10\n" 
	#printf "   8    -  Back display  12\" - 11\n" 
	#printf "   9    -  Back display  15\" - 12\n" 
		
	printf "\n ${SH}"
	printf "Normal |  Front display 15\"          "
	printf "${EH}" 
	printf "\t\t${SH}"
	printf "Normal |  Front display 10\"  |   180º"
	printf "${EH}\n" 
	printf "   13   -  Back display 9\"         17   -  Back display 9\"      \n" 
	printf "   14   -  Back display 12\"     \n" 
	printf "   15   -  Back display 15\"     \n" 
	printf "   16   -  No back display          18   -  No back display       \n" 
				

	#printf "${SH}"
	#printf "Normal |  Front display 10\"  |   180º"
	#printf "${EH}" 
	#printf "   17   -  Back display 9\"      \n" 
	#printf "   18   -  No back display       \n" 

	printf "\n\n"								
}

ShowOptions_2() {
	SH="\033[4m"
	EH="\033[24m"
	
	printf "\nAvailable options:\n\n"
	printf " ${SH}Back |  Front  9\"        9\"/180º   12\"       12\"/90º   15\"       10\" ${EH}\n"
	printf "  9\"  |        <1>       <4>       <7>       <10>      <13>      <17>\n"
	printf " 12\"  |        <2>       <5>       <8>       <11>      <14>          \n"
	printf " 15\"  |        <3>       <6>       <9>       <12>      <15>          \n"
	printf " No   |                                                <16>      <18>\n"
	printf "\n"								
}

ShowOptions() {
	SH="\033[4m"
	EH="\033[24m"
	
	printf "\nAvailable options:\n\n"
	printf "  Front  9\"        9\"/180º   12\"       12\"/90º   15\"       10\"   |  Back\n"
	printf "  ---------------------------------------------------------------|-------\n"
	printf "        <1>       <4>       <7>       <10>      <13>      <17>   |   9\"\n"
	printf "        <2>       <5>       <8>       <11>      <14>             |  12\"\n"
	printf "        <3>       <6>       <9>       <12>      <15>             |  15\"\n"
	printf "                                                <16>      <18>   |  No\n"
	printf "\n"								
}

#if [ $6 ]; then
#	if [ $7 ]; then
#		ShowParameters
#	fi
#else
#	ShowParameters
#fi

# Detect OS version 
dist=$(lsb_release -si)
ver=$(lsb_release -sr)
nam=$(lsb_release -sc)
kernel=$(uname -r | awk -F '-' '{print $1}')

clear

# Detect hardware
cpu=$(pcs-cpu)
if [ $? -ne 0 ]; then
	printf "Generic CPU detected. No changes allowed.\n"
	exit 1
fi

# Detect display controllers
num_mon=2
video_front=$(xrandr | grep -w connected | grep -w primary | awk '{print $1}')
video_rear=$(xrandr | grep -w connected | grep VGA | awk '{print $1}')
if [ "_$video_front" = "_" ]; then
	video_front="$video_rear"
	video_rear=""
fi 
if [ "_$video_front" = "_" ] && [ "_$video_rear" = "_" ]; then
	printf "No monitors detected.\n"
	exit 1
fi		
if [ "$video_front" = "$video_rear" ]; then
	video_rear=""
fi		
if [ "_$video_rear" = "_" ]; then
	num_mon=1
	printf "Detected $dist $nam $ver on $cpu CPU machine with $num_mon monitor: \n"
	printf "  Front: $video_front\n"
else
	printf "Detected $dist $nam $ver on $cpu CPU machine with $num_mon monitors: \n"
	printf "  Front: $video_front\n"
	printf "  Back : $video_rear\n"
fi
ShowOptions
option=0
read -r -p "Choice option <1...18>: " option
if [ $num_mon -eq 1 ]; then
	if [ "_$option" != "_16" ] && [ "_$option" != "_18" ]; then
		option="99"
	fi
fi
case $option in
	"1")  w1="800"  h1="480" r1="normal"      w2="800"  h2="480" r2="normal";;
	"2")  w1="800"  h1="480" r1="normal"      w2="800"  h2="600" r2="normal" rate2="60.316539764404297";;
	"3")  w1="800"  h1="480" r1="normal"      w2="1024" h2="768" r2="normal" rate2="60.003841400146484";;
	"4")  w1="800"  h1="480" r1="upside_down" w2="800"  h2="480" r2="normal";;
	"5")  w1="800"  h1="480" r1="upside_down" w2="800"  h2="600" r2="normal" rate2="60.316539764404297";;
	"6")  w1="800"  h1="480" r1="upside_down" w2="1024" h2="768" r2="normal" rate2="60.003841400146484";;
	"7")  w1="800"  h1="600" r1="normal"      w2="800"  h2="480" r2="normal" rate1="59.861404418945312";;
	"8")  w1="800"  h1="600" r1="normal"      w2="800"  h2="600" r2="normal" rate1="59.861404418945312" rate2="60.316539764404297";;
	"9")  w1="800"  h1="600" r1="normal"      w2="1024" h2="768" r2="normal" rate1="59.861404418945312";;
	"10") w1="800"  h1="600" r1="right"       w2="800"  h2="480" r2="normal" rate1="59.861404418945312";;
	"11") w1="800"  h1="600" r1="right"       w2="800"  h2="600" r2="normal" rate1="59.861404418945312" rate2="60.316539764404297";;
	"12") w1="800"  h1="600" r1="right"       w2="1024" h2="768" r2="normal" rate1="59.861404418945312" rate2="60.003841400146484";;
	"13") w1="1024" h1="768" r1="normal"      w2="800"  h2="480" r2="normal";;
	"14") w1="1024" h1="768" r1="normal"      w2="800"  h2="600" r2="normal" rate2="60.316539764404297";;
	"15") w1="1024" h1="768" r1="normal"      w2="1024" h2="768" r2="normal" rate2="60.003841400146484";;
	"16") w1="1024" h1="768" r1="normal"      w2="1024" h2="768" r2="normal" rate2="60.003841400146484" video_rear="-";;
	"17") w1="1024" h1="768" r1="upside_down" w2="800"  h2="480" r2="normal";;
	"18") w1="1024" h1="768" r1="upside_down" w2="1024" h2="768" r2="normal" rate2="60.003841400146484" video_rear="-";;
	*)	
		printf "Bad choice. Good bye!\n" 
		exit 1;;
esac
printf "  $w1 $h1 $r1 $rate1    $w2 $h2 $r2 $rate2"  

#echo -en "\e[40;38;5;82m Hello \e[30;48;5;82m World \e[0m"
#echo -en "WARNING!!!"
#echo "This procedure can change the system video configuration."
#echo "The system may stop working properly unless you know what you are doing."
#echo ' '
printf "\n${RED}WARNING!!!${NC}\n"
read -r -p "This will change the video configuration. Continue anyway? <y/N> " response
#read -r -p "This procedure change the system video configuration. Do you want to continue anyway? <y/N> " response
if [ "$response" != "y" ] && [ "$response" != "Y" ]; then
	echo ' '
	exit 0
fi


if [ "$cpu" = "N2600" ] && [ "$kernel" = "3.13.0" ]; then # Force no rotation
	r1="normal"
	r2="normal"
fi

if [ "$cpu" != Generic ]; then # Do nothing on not scale machines
	if [ "$nam" = "bionic" ]; then
		if [ "$r1" = "right" ]; then
			ModifyMonitorsResolutionBionic $video_front $w1 $h1 0 0 $r1 $video_rear $w2 $h2 $h1 0 $r2
		else
			ModifyMonitorsResolutionBionic $video_front $w1 $h1 0 0 $r1 $video_rear $w2 $h2 $w1 0 $r2
		fi
		CreatePCSResolution $video_rear $w2 $h2
	elif [ "$nam" = "precise" ]; then
		ModifyMonitorsResolutionPrecise $video_front $w1 $h1 0 0 $r1 $video_rear $w2 $h2 $w1 0 $r2
	fi
	printf "\nThe system must be restarted for changes take effect.\n"
else
	printf "This machine is not a scale.\nTest parameters: <$video_front $w1 $h1 0 0 $r1 $video_rear $w2 $h2 $w1 0 $r2>\n"
fi
