#!/bin/bash

# Get connected monitors and their native resolutions
monitor_info=$(xrandr --query)

# Extract primary monitor name
primary_monitor_name=$(echo "$monitor_info" | grep " primary" | cut -d" " -f1)

# Extract secondary monitor name and native resolution
secondary_monitor_line=$(echo "$monitor_info" | grep -m1 -n -P " connected(?! primary)")
secondary_monitor_line_number=$(echo "$secondary_monitor_line" | cut -d":" -f1)
secondary_monitor_name=$(echo "$secondary_monitor_line" | cut -d":" -f2 | cut -d" " -f1)
if [ ! -z "$secondary_monitor_line_number" ]; then
    secondary_resolution=$(echo "$monitor_info" | sed -e "1,${secondary_monitor_line_number}d" | grep -m1 "+" | awk '{ print $1 }')
fi

if [ -z "$secondary_monitor_name" ] || [ -z "$secondary_resolution" ] || [ -z "$primary_monitor_name" ]; then
    zenity --error --text="Es konnten keine passenden Bildschirme gefunden werden. Sind Sie sich sicher, dass der Beamer eingeschaltet und verbunden ist?"
    exit 1
fi

# Find out which resolutions we want to recommend
if [ "$secondary_resolution" = "1920x1080" ]; then
    recommend_high_res="Ja"
    recommend_low_res="Nein"
    default_xga="FALSE"
    default_hd="TRUE"
else
    recommend_high_res="Nein"
    recommend_low_res="Ja"
    default_xga="TRUE"
    default_hd="FALSE"
fi

# Generate GUI to let the user select a resolution
mode=$(zenity --list --radiolist --title="Beamer Setup" --text="Beamer mit der Auflösung $secondary_resolution gefunden." \
--print-column=3 --width 500 --height 250 \
--column= --column="Name" --column="Auflösung" --column="Format" --column="Empfohlen" \
FALSE           "Full HD"   "1920x1080" "16:9"  "$recommend_high_res" \
"$default_hd"   "HD"        "1280x720"  "16:9"  "Ja" \
"$default_xga"  "XGA"       "1024x768"  "4:3"   "$recommend_low_res")

# Use xrandr to configure both displays
if [ ! -z "$mode" ]; then
    xrandr --output $primary_monitor_name --mode $mode
    xrandr --output $secondary_monitor_name --mode $mode --same-as $primary_monitor_name
fi

# Use pactl to set audio output to hdmi
profile="output:hdmi-stereo+input:analog-stereo"
sink_line=$(pactl list short sinks | grep -m1 alsa_output.pci-)
sink_nr=$(echo $sink_line | awk '{ print $1 }')
sink_name_hdmi=$(echo $sink_line | awk '{ print $2 }' | grep hdmi)
if [ ! -z "$sink_nr" ] && [ -z "$sink_name_hdmi" ]; then
    card_name=$(pactl list cards short | grep -m1 alsa_card.pci- | awk '{ print $2 }')
    pactl set-card-profile $card_name $profile
fi

if [ ! -z "$sink_nr" ]; then
    pactl set-default-sink $(pactl list short sinks | grep -m1 alsa_output.pci- | awk '{ print $1 }')
fi

# if there is no hdmi sink search for a card profile to change
if [ -z "$sink_nr" ]; then
    card_name=$(pactl list cards short | head -n 1 | awk '{ print $2 }')
    pactl set-card-profile $card_name $profile
fi
