#!/bin/bash
SOURCE="$0"
source /usr/lib/elive-tools/functions
EL_REPORTS="1"
el_make_environment
. gettext.sh
TEXTDOMAIN="elive-tools"
export TEXTDOMAIN

# Lock system (good one) {{{
lockfile="/tmp/.$(basename $0)-${USER}.lock"

exit_ok(){
    rm -f "$lockfile"
}
exit_error(){
    rm -f "$lockfile"
}

if [[ -r "$lockfile" ]] ; then
    PROCCESS="$(cat $lockfile)"
else
    PROCCESS=" "
fi
if (ps up $PROCCESS) 1>/dev/null 2>&1 ; then
    echo -e "E: $(basename "$0" ) already running"
    exit
else
    echo $$ > "$lockfile"
fi

# traps needs to be after the lock verification, in order to not remove it when we are already running
trap "exit_ok" EXIT
trap "exit_error" 1 3 5 6 14 15 ERR TERM

# SET the lock file
echo "$$" > "$lockfile"


# end lock system }}}

# TODO: remove modes: auto, pre, quiet, if they are useless in the final code

#===  FUNCTION  ================================================================
#          NAME:  usage
#   DESCRIPTION:  shows usage help
#    PARAMETERS:  -
#       RETURNS:  -
#===============================================================================
usage(){
    echo -e "
    Usage: $(basename $0) args:

-l  Load: Uses your last multiscreens configuration
-c  Configure: Reconfigure multiscreens
-a  Auto: Do not ask any question
-q  Quiet: Be silent
-p  Prev-desktop: this marks a state to know that we are before/previous to desktop started
"
}

# wrapper to avoid GUI's when not wanted (blocks e16)
guitool(){
    if ((is_mode_auto)) ; then
        el_warning "trying to use a GUI widget while in mode_auto, ignoring it, fix required in '${FUNCNAME[1]}' for lines '${BASH_LINENO[*]}'"
    else
        zenity --window-icon=/usr/share/icons/gnome/256x256/apps/logo-elive.png "$@"
    fi
}

# generates a usable menu output with more info for select screen
screens_connected_names_menu_gen(){
    local screen line menu

menu="$(
while read -ru 3 line
do
    [[ -z "$line" ]] && continue

    screen="$( LC_ALL=C xrandr -q | grep -E "^$line\s+connected\s+" | sed -e 's|^.*connected ||g' -e 's|+.*$||g' )"
    [[ -z "$screen" ]] && screen="Screen"
    if ! echo "$screen" | grep -Fqs "x" ; then
        screen="unknown"
    fi

    if [[ -n "$screen" ]] && [[ -n "$line" ]] ; then
        echo "$line"
        echo "$screen"
    fi

done 3<<< "$( echo "$screens_connected_names" | psort -- -p "^LVDS" -p "^HDMI"  )"
)"

echo "$menu"
}

reload_desktop_gadgets(){
    # reload conky
    if pidof -q conky ; then
        killall conky
        ( conky & )
    fi
}

#===  FUNCTION  ================================================================
#          NAME:  module_ecomorph_unload
#   DESCRIPTION:  disables the ecomorph emodule before to load multiscreens because it bugs
#    PARAMETERS:  -
#       RETURNS:  -
#===============================================================================
module_ecomorph_unload(){
    # pre {{{
    local module address

    if [[ ! -n "$E_START" ]] ; then
        return 0
    fi

    #module="$1"
    module="ecomorph"
    el_check_variables "module"

    screens_connected_names="$( LC_ALL="$EL_LC_EN" xrandr --query | grep -F " connected" | sed -e "s/\([A-Z0-9]\+\) connected.*/\1/" )"
    if [[ -n "$screens_connected_names" ]] ; then
        screens_connected_number="$( echo "$screens_connected_names" | wc -l )"
    else
        screens_connected_number="0"
    fi

    # }}}

    # only bugs using more than one screen, so do not not unload if not needed
    if [[ "$screens_connected_number" -eq 1 ]] ; then
        return 0
    fi

    if ! ((is_mode_previous_desktop)) ; then
        # check dbus
        if ! enlightenment_remote -ping 1>/dev/null ; then
            if [[ -s "$HOME/.cache/dbus-session-address-last.txt" ]] ; then
                address="$( cat "$HOME/.cache/dbus-session-address-last.txt" | tail -1 )"
                export DBUS_SESSION_BUS_ADDRESS="$address"
            fi
        fi

        if enlightenment_remote -ping 1>/dev/null ; then
            if enlightenment_remote -module-list | grep --color=never "^${module} -- Enabled" ; then

                enlightenment_remote -module-disable "$module"
                sleep 8
                if enlightenment_remote -module-list | grep --color=never "^${module} -- Enabled" ; then
                    enlightenment_remote -module-disable "$module"
                    sleep 9
                    el_error "ecomorph module was unloaded but stills here"
                fi

                timeout 40 $guitool --info --text="$( eval_gettext "The module Ecomorph has been deactivated because it doesn't work well with multiple screens. If you want to help getting this feature to work, we have the source code on Github at:" ) github.com/elive"
            fi

        else
            el_error "unable to use enlightenment_remote in $SOURCE"
        fi
    fi

}

#===  FUNCTION  ================================================================
#          NAME:  configure_multiscreens
#   DESCRIPTION:  configures multiscreen
#    PARAMETERS:  -
#       RETURNS:  -
#===============================================================================
configure_multiscreens(){
    # FIXME: disable the randr module from enlightenment? (what if we exit from games? try this in tower by loading/unloading the module)
    # maybe we can add a watcher here to know about that? no... we need to know that the game exited!
    # TODO: remove the xrandr module from E sources? not so important since we don't use it... also it doesn't shows on modules list as a pluggable module
    # TODO: when elive-skel is used or e17-confs restarted, delete the screens configurations too
    # TODO: e17-restart should use elive-skel instead of a force delete?
    # TODO: betatest games restoring states
    # TODO: betatest ecomorph dealing
    # TODO: betatest: with system -> reboots, is my DIMM always reduced? is not the e17-conf already meant to not do that??
    # TODO: the pre-desktop mode is a bit ugly (code speaking, error-prone), maybe we should just have an own function for it
    # TODO: add a keyboard hotkey to switch between screens (in e17-conf), and include it in the hotkeys PDF
        # note: doesnt works on virtualmachine but works on real hardware (so yes), but only in a limited way (what about more screens?), maybe our setup should be: ctrl + alt + number (0 to scren 0, 1 to screen 1, etc...), that sounds more coherent than "ctrl + alt + shift + arrows!"
    # pre {{{


    # install dependencies
    if ! el_dependencies_check "arandr" 1>/dev/null 2>&1 ; then
        el_dependencies_install "arandr"

        if ! el_dependencies_check "arandr" 1>/dev/null 2>&1 ; then
            $guitool --error --text="Arandr tool is required, install it first"
            exit 1
        fi
    fi


    # }}}

    module_ecomorph_unload

    # explain {{{
    # explain the user how to configure it

    local message_title_resolutions
    message_title_resolutions="$( printf "$( eval_gettext "Displays and resolutions" )" "" )"
    #local message_welcome
    #message_welcome="$( printf "$( eval_gettext "Use this tool to configure your screens and resolutions. If you want that Elive autoload your configuration when starting the desktop you need to select the option to save its configuration." )" "" )"

    #el_notify normal display "$message_title_resolutions" "$message_welcome"

    if ((is_mode_previous_desktop)) ; then
        # big explaination too
        timeout 120 $guitool --info --text="$( eval_gettext "IMPORTANT: You're just before the window manager starts, so you won't see window buttons or other features yet, which can be confusing, FOLLOW these instructions CAREFULLY: Set up your screens the way you want, click apply to test it by moving your mouse around, then save your configuration (this is important), and finally exit the application through the menu or by pressing CTRL+Q." )"
    fi

    # e16
    if [[ -n "$EROOT" ]] ; then
        if ! el_flag check multiscreens-e16-welcome ; then
            $guitool --info --text="$( eval_gettext "The E16 desktop might struggle with multiple screens unlike newer Enlightenment versions do, causing gadgets or windows to shift to unexpected places." )"
            el_flag add multiscreens-e16-welcome
        fi
    fi

    # - explain }}}
    # configure {{{
    # gui for the user
    el_debug "running gui configurator"

    # tell the user to save the conf
    local message_save_required_to_autostart
    message_save_required_to_autostart="$( printf "$( eval_gettext "Important: if you want to load your custom resolution on every desktop startup, you need to save it with the 'Save As' option. Otherwise, your settings will not be available on each startup." )" "" )"

    el_notify normal "preferences-desktop-display" "$message_title_resolutions" "$message_save_required_to_autostart"

    arandr

    if [[ -d "$HOME/.screenlayout" ]] ; then
        conf="$( find "$HOME/.screenlayout/" -type f -printf "%T@ %p\n" | sort -n | tail -n 1 )"
        file="$( echo "$conf" | cut -d' ' -f 2- | tail -n 1 )"
    fi

    # check and fix
    if [[ -z "$conf" ]] ; then
        if timeout 180 $guitool --question --text="$( eval_gettext "You don't have any saved settings, so Elive can't load your screen configurations, do you want to try again? You need to choose the 'Save As' option." )" ; then

            # configure
            arandr

            # load new conf
            if [[ -d "$HOME/.screenlayout" ]] ; then
                # FIXME: this gets the last conf, but doesn't means that is ours one, we should use a backup/recover state for the directory with trap flags
                    # use "bkp" tool? more easy
                conf="$( find "$HOME/.screenlayout/" -type f -printf "%T@ %p\n" | sort -n | tail -n 1 )"
                file="$( echo "$conf" | cut -d' ' -f 2- | tail -n 1 )"
            fi
        fi
    fi

    reload_desktop_gadgets

    if [[ -z "$conf" ]] ; then
        el_debug "user don't wanted to save any configuration, so forget our state and exit"
        # cleanups, because we don't know what to do with different screens - so it will ask again about configuring screens (generate new conf)
        conf_multiscreens_last=""
        conf_multiscreens_last_autoload_wanted=""
        el_config_save "conf_multiscreens_last"
        el_config_save "conf_multiscreens_last_autoload_wanted"

        return 0
    fi

    # - configure }}}
    # primary screen select {{{
    # set the primary screen
    #if ! grep -qs " --primary" "$file" ; then
        #el_debug "no primary conf found, asking for it"

        # remove it first
        sed -i -e "s| --primary||g" "$file" 2>/dev/null || true


        screens_connected_names="$( LC_ALL="$EL_LC_EN" xrandr --query | grep -F " connected" | sed -e "s/\([A-Z0-9]\+\) connected.*/\1/" )"
        if [[ -n "$screens_connected_names" ]] ; then
            screens_connected_number="$( echo "$screens_connected_names" | wc -l )"
        else
            screens_connected_number="0"
        fi

        if [[ "$screens_connected_number" = 1 ]] ; then
            primary="$( echo $screens_connected_names )"
        else

            while true
            do
                if [[ -n "$primary" ]] && echo "$screens_connected_names" | grep -qs "^${primary}$" ; then
                    break
                else
                    if [[ "$primary" = "cancel" ]] || [[ -z "$screens_connected_names" ]] ; then
                        unset primary
                        break
                    fi
                    # TODO: include more info in the selector about the screens, like their resolution and size dimensions
                    primary="$( screens_connected_names_menu_gen | $guitool --list --text="$( eval_gettext "Select your primary screen" )" --column="Identifier" --column="Resolution" || echo cancel )"
                fi
            done
        fi

        # set it
        if [[ -z "$primary" ]] ; then
            primary="$( echo "$screens_connected_names" | psort -- -p "^LVDS" -p "^HDMI" | head -1 )"
        fi
        sed -i -e "s|output ${primary} |output ${primary} --primary |g" "$file"
        # update timestamps since we modify the file
        conf="$( find "$HOME/.screenlayout/" -type f -printf "%T@ %p\n" | sort -n | tail -n 1 )"

        el_debug "user selected $primary as primary screen, updating configuration to use always it"
    #fi

    # - primary screen select }}}
    # use and ask if save {{{
    if [[ -x "$file" ]] ; then
        # load the new conf
        el_info "running: $(cat "$file" | grep "^xrand" )"
        module_ecomorph_unload

        (
        if "$file" ; then
            # we have configured primary, so we need to reload desktop
            # we always need to restart E to use the correct confs for the bar and gadgets
            # update: seems like if we restart enlightenment, the multiscreens setup is broken (no idea why this happens), setting the screens to be like mirror mode (jfbourdeau machine)
            # note: never restart E because we also run this tool from the E restart, so it could end into a loop
            true
            # re-load the bar to the correct new desktop
            if [[ -n "$E_START" ]] ; then
                if enlightenment_remote -module-list 2>/dev/null | grep --color=never "^engage -- Enabled" ; then
                    enlightenment_remote -module-disable "engage"
                    enlightenment_remote -module-enable "engage"
                fi
            fi
        else
            if ! (($is_mode_previous_desktop)) ; then
                $guitool --warning --text="$( eval_gettext "Failed to load your screen configuration. Try reconfiguring your screens or using different options." )\n\nError message: $( . "$file" 2>&1 )\n\nFrom configuration: $file"
            fi
        fi
        )

        if [[ -n "$E_START" ]] ; then
            timeout 40 $guitool --info --text="$( eval_gettext "Note: There is a unique feature in Elive that doesn't let you move a window out of the limits of your screen, when working with multiple screens it may be better to disable this feature. You can find this option in Settings -> Windows -> Window display -> Screen Limits" )"
        fi

        sleep 1

        if timeout 25 $guitool --question --text="$( eval_gettext "Do you want to save this configuration for use when starting your graphical system?" )" ; then

            conf_multiscreens_last_autoload_wanted="yes"
            el_debug "user wanted to save permanently this configuration"

            if ((is_mode_configure)) ; then
                timeout 90 $guitool --info --text="$( eval_gettext "Note: if the desktop doesn't behave as expected, try to restart to a new desktop configuration" )"
            fi
        else
            conf_multiscreens_last_autoload_wanted="no"
            el_debug "user not wanted to re-use this configuration"
        fi

        # save confs
        conf_multiscreens_last="$conf"
        el_config_save "conf_multiscreens_last"

        conf_multiscreens_last_screens_list="$( echo "$screens_connected_names" | sort | tr '\n' ' ' | sed -e 's| $||g' )"
        el_config_save "conf_multiscreens_last_screens_list"

        el_config_save "conf_multiscreens_last_autoload_wanted"

    else
        el_debug "we dont have any valid configuration, so forget the autoloading"
        conf_multiscreens_last=""
        conf_multiscreens_last_autoload_wanted=""
        el_config_save "conf_multiscreens_last"
        el_config_save "conf_multiscreens_last_autoload_wanted"
    fi

    # - use and ask if save }}}
}

load_multiscreens_configuration(){
    # pre {{{
    # install dependencies
    if ! el_dependencies_check "xrandr" 1>/dev/null 2>&1 ; then
        el_dependencies_install "x11-server-utils"

        if ! el_dependencies_check "xrandr" 1>/dev/null 2>&1 ; then
            $guitool --error --text="xrandr tool is required, install it first"
            exit 1
        fi
    fi

    # - pre }}}

    # check for arandr configurations
    if [[ -d "$HOME/.screenlayout" ]] ; then
        conf="$( find "$HOME/.screenlayout/" -type f -printf "%T@ %p\n" | sort -n | tail -n 1 )"
        file="$( echo "$conf" | cut -d' ' -f 2- | tail -n 1 )"
    fi

    # TODO: implement: use a per-profile list of loading configurations array (ID + max resolution etc)
    # only if we have valid configurations
    if [[ -s "$file" ]] && [[ -x "$file" ]] && grep -qs "^xrandr" "$file" ; then

        # just load it if wanted {{{
        if [[ "$conf_multiscreens_last_autoload_wanted" = "yes" ]] ; then

            # only if we have the same screens connected
            if [[ "$conf_multiscreens_last_screens_list" = "$( echo "$screens_connected_names" | sort | tr '\n' ' ' | sed -e 's| $||' )" ]] ; then

                if [[ -n "$conf_multiscreens_last" ]] && [[ "$conf" = "$conf_multiscreens_last" ]] ; then
                    # load
                    module_ecomorph_unload
                    # disable debug when finished to betatest: we just want to load, less bottleneck
                    #el_info "running: $(cat "$file" | grep "^xrand" )"
                    (
                    if "$file" ; then
                        # we always need to restart E to use the correct confs for the bar and gadgets
                        # wait that the desktop is loaded to not break something first
                        # update: seems like if we restart enlightenment, the multiscreens setup is broken (no idea why this happens), setting the screens to be like mirror mode (jfbourdeau machine)
                        true
                        # reload conky
                        if pidof -q conky ; then
                            killall conky
                            conky &
                        fi
                    else
                        if ! (($is_mode_previous_desktop)) ; then
                            $guitool --warning --text="$( eval_gettext "Failed to load your screen configuration. Try reconfiguring your screens or using different options." )\n\nError message: $( . "$file" 2>&1 )\n\nFrom configuration: $file"
                        fi
                    fi
                    )
                    # nothing more to do
                    return 0
                fi
            else
                true
                # we have different screens connected, hum?
                #if [[ "$screens_connected_number" -gt 1 ]] ; then
                    ## TODO: implement:
                    #$guitool --warning --text="You have different screens connected than in your last configuration, this feature is not yet implemented in Elive, you can collaborate improving this tool from ${0}, donate, making the project more known to have more resources, etc..."
                #fi

                # cleanups, because we don't know what to do with different screens - so it will ask again about configuring screens (generate new conf)
                # update: we don't want to delete any conf if the screens connected has changed
                #if [[ "$screens_connected_number" -gt 1 ]] ; then
                    #conf_multiscreens_last=""
                    #conf_multiscreens_last_autoload_wanted=""
                    #el_config_save "conf_multiscreens_last"
                    #el_config_save "conf_multiscreens_last_autoload_wanted"
                    #el_debug "we have different screens connected from the last setup, so forget our last configuration (we will ask then for a new one)"
                #fi
            fi
        fi

        # }}}

        # we dont want to interact more from this point, so just exit
        if ((is_mode_previous_desktop)) ; then
            exit
        fi


        # different than last time, ask
        if [[ -n "$conf" ]] && [[ -n "$conf_multiscreens_last" ]] && [[ "$conf" != "$conf_multiscreens_last" ]] ; then
            el_debug "different configuration from the last time, ask what to do"
            # needed for wait that E is loaded, positioning widgets
            if ((is_mode_delayed)) ; then
                sleep 5
            fi
            if timeout 120 $guitool --question --text="$( eval_gettext "You have a new screen configuration. Would you like to load it?" )" ; then

                # check and set primary screen {{{
                if ! grep -qs " --primary" "$file" ; then
                    while true
                    do
                        if [[ -n "$primary" ]] && echo "$screens_connected_names" | grep -qs "^${primary}$" ; then
                            break
                        else
                            if [[ "$primary" = "cancel" ]] ; then
                                unset primary
                                break
                            fi

                            # get info from xrandr
                            screens_connected_names="$( LC_ALL="$EL_LC_EN" xrandr --query | grep -F " connected" | sed -e "s/\([A-Z0-9]\+\) connected.*/\1/" )"
                            if [[ -n "$screens_connected_names" ]] ; then
                                screens_connected_number="$( echo "$screens_connected_names" | wc -l )"
                            else
                                screens_connected_number="0"
                            fi

                            if [[ "$screens_connected_number" = 1 ]] ; then
                                primary="$( echo $screens_connected_names )"
                            else
                                primary="$( screens_connected_names_menu_gen | $guitool --list --text="$( eval_gettext "Select your primary screen" )" --column="Identifier" || echo cancel )"
                            fi
                        fi
                    done

                    # set it
                    if [[ -z "$primary" ]] ; then
                        primary="$( echo "$screens_connected_names" | psort -- -p "^LVDS" -p "^HDMI" | head -1 )"
                    fi
                    sed -i -e "s|output ${primary} |output ${primary} --primary |g" "$file"
                    # update timestamps since we modify the file
                    conf="$( find "$HOME/.screenlayout/" -type f -printf "%T@ %p\n" | sort -n | tail -n 1 )"
                fi

                # }}}
                # load and save {{{
                # load
                module_ecomorph_unload

                el_info "running: $(cat "$file" | grep "^xrand" )"
                (
                if "$file" ; then
                    # we always need to restart E to use the correct confs for the bar and gadgets
                    # update: seems like if we restart enlightenment, the multiscreens setup is broken (no idea why this happens), setting the screens to be like mirror mode (jfbourdeau machine)
                    true
                else
                    $guitool --warning --text="$( eval_gettext "Failed to load your screen configuration. Try reconfiguring your screens or using different options." )\n\nError message: $( . "$file" 2>&1 )\n\nFrom configuration: $file"
                fi
                )

                # ask for confirmation
                if timeout 180 $guitool --question --text="$( eval_gettext "Move your mouse across the screens to verify their positions. Would you like this setup to load every time you start Elive?" )" ; then
                    el_debug "user wants to re-use the conf"
                    conf_multiscreens_last_autoload_wanted="yes"
                else
                    el_debug "user dont want to re-use the conf"
                    conf_multiscreens_last_autoload_wanted="no"
                fi
                el_config_save "conf_multiscreens_last_autoload_wanted"

                # }}}
            else
                el_debug "user dont want to use the new conf found"
                conf_multiscreens_last_autoload_wanted="no"
                el_config_save "conf_multiscreens_last_autoload_wanted"
            fi

            # always save our last used conf position (because we already asked)
            conf_multiscreens_last="$conf"
            el_config_save "conf_multiscreens_last"

            conf_multiscreens_last_screens_list="$( echo "$screens_connected_names" | sort | tr '\n' ' ' | sed -e 's| $||g' )"
            el_config_save "conf_multiscreens_last_screens_list"
        fi

    else
        # if we don't have a valid configuration, ask for a new one
        if ! [[ "$conf_multiscreens_last_autoload_wanted" = "no" ]] && ! ((is_mode_auto)) ; then
            if [[ "$screens_connected_number" -gt 1 ]] ; then
                el_debug "we dont have anything to load, but we found multiple screens connected, to ask the user if wants to configure them"

                # needed for wait that E is loaded, positioning widgets
                if ((is_mode_delayed)) ; then
                    sleep 15
                fi

                if timeout 30 $guitool --question --text="$( eval_gettext "You have multiple screens connected, do you want to automatically configure them?" )" ; then

                    # configure
                    configure_multiscreens
                else
                    el_debug "user dont want to configure screens"

                    conf_multiscreens_last_autoload_wanted="no"
                    el_config_save "conf_multiscreens_last_autoload_wanted"
                fi
            else
                # when the device is a tablet, with orientation set vertically, always rotate it to the right (like Lenovo Tablet 2)
                if ((is_mode_previous_desktop)) ; then
                    resolution="$( el_resolution_get )"
                    resolution_h="${resolution%x*}"
                    resolution_v="${resolution#*x}"
                    if [[ "$resolution_v" -gt "$resolution_h" ]] ; then
                        ( xrandr -o right & )
                        LC_ALL=C sleep 0.2
                        # on these cases we need to restart e16 to update the WM sizes (dpi?) because they look wrong
                        touch /tmp/.e16-reload-needed-$USER
                    fi
                fi
            fi

            # TODO: when elive-skel is used or e17-confs restarted, delete the screens configurations too
            # TODO: e17-confs requires a configurator for multiscreens, in other words, a pager for every extra screen
            # TODO: e17-restart should use elive-skel instead of a force delete?

            # if we have now a new conf
            # FIXME: this code seems not needed anymore, remove it
            #if [[ -n "$conf" ]] ; then
                #if [[ -x "$file" ]] ; then

                    ## load and ask
                    #el_debug "running: $(cat "$file" | grep "^xrand" )"
                    #( . "$file" )

                    ## done
                    #timeout 60 $guitool --info --text="$( eval_gettext "Perfect, Elive will use this configuration from now when your desktop starts, if you want to stop loading it just delete the configurations from their directory:" )"

                    #conf_multiscreens_last="$conf"
                    #el_config_save "conf_multiscreens_last"
                #else
                    #el_error "configuration file not found or not executable: $file"
                #fi
            #else
                #conf_multiscreens_last_autoload_wanted="no"
                #el_config_save "conf_multiscreens_last_autoload_wanted"

                ## empty configuration, so that if in the future we found a new one we will ask if load it
                #conf_multiscreens_last=""
                #el_config_save "conf_multiscreens_last"
            #fi
        fi
    fi

}

main(){
    # pre {{{
    # pre confs
    if [[ -z "${1}" ]] ; then
        is_mode_configure=1
        el_debug "no options given, so we should want to configure it then"
    fi

    # }}}

    # load configurations
    el_config_get

    while getopts ":adqcflph" opt; do
        case "$opt" in
            a)
                is_mode_auto=1
                ;;
            d)
                is_mode_delayed=1
                ;;
            q)
                # less use of debug functions:
                export EL_DEBUG=0
                is_mode_quiet=1
                ;;

            c)
                el_debug "configure mode"
                is_mode_configure=1
                ;;
            f)
                el_debug "force mode"
                is_mode_force=1
                ;;
            l)
                el_debug "load mode"
                is_mode_load=1
                ;;
            p)
                is_mode_previous_desktop=1
                # set default language to english if we didn't started the desktop yet
                if grep -Fqs "boot=live" /proc/cmdline ; then
                    export LC_ALL=C
                fi
                ;;
            \?)
                usage
                NOREPORTS=1 el_error "Invalid option: -$OPTARG"
                exit 1
                ;;
            :)
                usage
                NOREPORTS=1 el_error "Option -$OPTARG requires an argument."
                exit 1
                ;;
            h)
                usage
                exit
                ;;
            # temporal demo code for multiargs:
            #a)
                #el_array_member_add "$OPTARG" "${attachments[@]}" ; attachments=("${_out[@]}")
                #if ! ((is_mode_quiet)) ; then
                    #el_explain 2 "attached file: $OPTARG"
                #fi
                #;;
        esac
    done


    # get info from xrandr
    screens_connected_names="$( LC_ALL="$EL_LC_EN" xrandr --query | grep -F " connected" | sed -e "s/\([A-Z0-9]\+\) connected.*/\1/" )"
    #activeOutput="$( LC_ALL="$EL_LC_EN" xrandr | grep -E " connected (primary )?[1-9]+" | sed -e "s/\([A-Z0-9]\+\) connected.*/\1/")" # im not sure what this does but dont looks to work, not always the screen is set as primary, hum
    if [[ -n "$screens_connected_names" ]] ; then
        screens_connected_number="$( echo "$screens_connected_names" | wc -l )"
    else
        screens_connected_number="0"
    fi

    # how much screens we have?
    case "$screens_connected_number" in
        0)
            if ((is_mode_auto)) || ((is_mode_previous_desktop)) ; then
                exit
            fi

            # inform
            if xrandr --query | grep -Fqs " disconnected" ; then
                $guitool --error --text="$( eval_gettext "Your screen appears to be disconnected, turn it ON first and try again." )"
            else
                # report
                el_error "no screens connected? \n$( xrandr --query 2>&1 )"

                $guitool --error --text="$( eval_gettext "You don't have any screens connected." )"
            fi
            ;;
        1)
            # unless we want to configure resolutions, everything is fine
            #if ((is_mode_auto)) || ((is_mode_previous_desktop)) ; then
                #exit
            #fi
            # UPDATE: the user may have a wanted specific resolution to use, so always be able to load configurations for a single screen too
            true
            ;;
        *)
            # more than one screen
            true
            ;;
    esac


    # we only want to load conf, not configure it
    if ((is_mode_load)) ; then
        load_multiscreens_configuration
    fi

    if ((is_mode_configure)) ; then
        configure_multiscreens
    fi

}

#
#  MAIN
#
main "$@"

# vim: set foldmethod=marker :
