#!/bin/sh

LIST="$(xrandr | sed '/ connected/!d;s/ .*$//')"
ULIST="$(xrandr | sed '/ disconnected/!d;s/ .*$//')"
MONITORS="$(printf '%s' "${LIST}" | tr '\n' ' ')"

for i in ${ULIST} ; do
    UNSET="${UNSET} --output ${i} --off"
done

CMD="$(FIRST=1 ; for i in ${MONITORS} ; do
    # shellcheck disable=SC2030
    CURR="$(printf '%s' "${LIST}" | sed "/${LAST:=empty}/d" | menu "Next monitor (to right):")"
    [ -z "${CURR}" ] && exit 1
    [ "${FIRST}" ] && printf 'xrandr --output %s' "${CURR}" && FIRST=
    # shellcheck disable=SC2031
    [ "${LAST}"  ] && printf ' --left-of %s' "${CURR}"
    LAST="${CURR}"
done)"

for i in ${MONITORS} ; do
    case ${CMD} in
        *${i}*) ;;
        *) UNSET="${UNSET} --output ${i} --off"
    esac
done

CMD="xrandr --auto && ${CMD} ${UNSET}"
[ "${CMD}" ] && eval "${CMD}" && printf '%s\n' "${CMD}"
BACKGROUND="$(grep 'hsetroot' ~/.config/X11/xinitrc | sed 's/ \&$//')"
[ "${BACKGROUND}" ] && eval "${BACKGROUND}" && printf '%s\n' "${CMD}"