#!/bin/bash

#. Configuration File -={
#. Tokens are dellimited by spaces
#. Each tokens defines one screen
#. Each token itself contains 3 subtokens:
#.     1. Relative Position: [M]ain (mandatory), [L]eft-of, [R]right-of, [A]bove, [B]elow
#.     2. Xrandr Screen ID
#.     3. Screen rotation: normal, left, right or inverted
#. Example:
#.     R:VGA1:normal M:HDMI2:normal
CONF=${1:-~/.xranderize}
#. }=-

e=0
if [ -e ${CONF} ]; then
    DEVICES=( $(xrandr|awk '$2~/^connected$/{print $1}') )

    declare -A placement=( [M]= [L]= [R]= [A]= [B]= )
    declare -A rotation=(  [M]=normal [L]=normal [R]=normal [A]=normal [B]=normal )

    match=0
    configured=( $(grep -E '^[^#]' ${CONF}) )

    if [ ${#DEVICES[@]} -ge 1 ]; then
        for actual in ${DEVICES[@]}; do
            for token in ${configured[@]}; do
                IFS=: read pos dev rot <<< "${token}"
                if [ "${actual}" == "${dev}" ]; then
                    for p in ${!placement[@]}; do
                        if [ "$p" == "${pos}" ]; then
                            placement[$p]="${dev}"
                            rotation[$p]="${rot}"
                            ((match++))
                            break
                        fi
                    done
                fi
            done
        done

        if [ -n "${placement[M]}" ]; then
            if [ ${#configured[@]} -eq ${match} ]; then
                xrandr --output ${placement[M]} --auto --primary
                for rid in L R A B; do
                    if [ -n "${placement[${rid}]}" ]; then
                        #xrandr --output ${placement[${rid}]} --off
                        xrandr --output  ${placement[${rid}]} --auto
                        case ${rid} in
                            L) xrandr --output ${placement[${rid}]} --left-of  ${placement[M]} --rotation ${rotation[${rid}]};;
                            R) xrandr --output ${placement[${rid}]} --right-of ${placement[M]} --rotation ${rotation[${rid}]};;
                            A) xrandr --output ${placement[${rid}]} --above    ${placement[M]} --rotation ${rotation[${rid}]};;
                            B) xrandr --output ${placement[${rid}]} --below    ${placement[M]} --rotation ${rotation[${rid}]};;
                        esac
                    fi
                done
            else
                echo "Error: Mismatch between detected and requested screens"
                e=1
            fi
        else
            echo "Error: Main screen has not been declared in ${CONF}"
            e=1
        fi
    fi
else
    echo "Error: Missing ${CONF}"
    e=1
fi

exit $e
