# Sourced with .

XCONF=${XCONF:-/etc/X11/xorg.conf}

write_screen() {
    num=${1:-0}
    #eval screen_hacks=\$screen_hacks_$num
    [ -z "$screen_hacks" ] && [ -z "$monitor_hacks" ] && return
    echo "Section \"Screen\"" >> ${XCONF}
    echo "    Identifier \"Screen${num}\"" >> ${XCONF}
    if [ -n "$monitor_hacks" ]; then
        # force the monitor definition if revelent monitor settings are
        # desired, otherwise X.org may just use built-in defaults for monitor
        # settings
        echo "Monitor \"Monitor${num}\"" >> ${XCONF}
    fi

    for i in ${screen_hacks}; do
        ${i} || true
    done >> ${XCONF}

    echo "EndSection" >> ${XCONF}
}

write_monitor() {
    num=${1:-0}
    #eval monitor_hacks=\$monitor_hacks_$num
    [ -z "$monitor_hacks" ] && return
    echo "Section \"Monitor\"" >> ${XCONF}
    echo "    Identifier \"Monitor${num}\"" >> ${XCONF}

    for i in ${monitor_hacks}; do
        ${i} || true
    done >> ${XCONF}

    echo "EndSection" >> ${XCONF}
}

write_device() {
    num=${1:-0}
    #eval device_hacks=\$device_hacks_$num
    [ -z "$device_hacks" ] && return
    echo "Section \"Device\"" >> ${XCONF}
    echo "    Identifier \"Device${num}\"" >> ${XCONF}

    for i in ${device_hacks}; do
        ${i} || true
    done >> ${XCONF}

    echo "EndSection" >> ${XCONF}
}

write_module() {
    [ -z "$module_hacks" ] && return
    echo "Section \"Module\"" >> ${XCONF}

    for i in ${module_hacks}; do
        ${i} || true
    done >> ${XCONF}

    echo "EndSection" >> ${XCONF}
}

# Only assemble a xorg.conf is CONFIGURE_X=True
if boolean_is_true "${CONFIGURE_X}"; then
    # Run custom command if supplied, otherwise use ours
    if [ -n "${CONFIGURE_X_COMMAND}" ] && [ -x "${CONFIGURE_X_COMMAND}" ]; then
        ${CONFIGURE_X_COMMAND}
    else
        # Clear pre-existing config, if it exists
        [ -w "${XCONF}" ] && :>${XCONF} 
    
        # For now, we will only do one screen, monitor, and device
        # under the assumption that multiple-head issues should
        # be handled exclusively by xrandr
    
        write_screen 0 	|| true
        write_monitor 0	|| true
        write_device 0 || true
        write_module || true
    fi
fi
