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

# comment when not used
#xinput_demo(){
    #echo -e "
    #⎡ Virtual core pointer                    	id=2	[master pointer  (2)]
#⎜   ↳ Virtual core XTEST pointer              	id=4	[slave  pointer  (2)]
#⎜   ↳ Melfas LGD AIT Touch Controller         	id=9	[slave  pointer  (2)]
#⎜   ↳ Melfas LGD AIT Touch Controller Mouse   	id=10	[slave  pointer  (2)]
#⎜   ↳ SynPS/2 Synaptics TouchPad              	id=19	[slave  pointer  (2)]
#⎜   ↳ TPPS/2 IBM TrackPoint                   	id=20	[slave  pointer  (2)]
#⎜   ↳ INSTANT USB Keyboard Consumer Control   	id=12	[slave  pointer  (2)]
#⎜   ↳ Genius Wireless Device                  	id=15	[slave  pointer  (2)]
    #↳ AT Translated Set 2 keyboard            	id=18	[slave  keyboard (2)]
#⎜   ↳ Genius Wireless Device Consumer Control 	id=16	[slave  pointer  (2)]
#⎣ Virtual core keyboard                   	id=3	[master keyboard (2)]
    #↳ Virtual core XTEST keyboard             	id=5	[slave  keyboard (3)]
    #↳ Power Button                            	id=6	[slave  keyboard (3)]
    #↳ Video Bus                               	id=7	[slave  keyboard (3)]
    #↳ Sleep Button                            	id=8	[slave  keyboard (3)]
    #↳ ThinkPad Extra Buttons                  	id=21	[slave  keyboard (3)]
    #↳ INSTANT USB Keyboard                    	id=11	[slave  keyboard (3)]
    #↳ INSTANT USB Keyboard Consumer Control   	id=13	[slave  keyboard (3)]
    #↳ INSTANT USB Keyboard System Control     	id=14	[slave  keyboard (3)]
    #↳ Genius Wireless Device Consumer Control 	id=17	[slave  keyboard (3)]
    #↳ Genius Wireless Device System Control   	id=22	[slave  keyboard (3)]
    #↳ Genius Wireless Device                  	id=23	[slave  keyboard (3)]
    #↳ Tronsmart Element Mega (AVRCP)          	id=24	[slave  keyboard (3)]
#"
#}

main(){
    # pre {{{
    local input
    local dry_run=0

    # Parse options
    while [[ "$1" =~ ^- ]]; do
        case "$1" in
            -h|--help)
                echo -e "Usage: $(basename "$BASH_SOURCE") [options] [action]"
                echo -e "Toggle or explicitly set the state of input devices (reattach/float in xinput)."
                echo -e ""
                echo -e "Options:"
                echo -e "  -d, --dry-run     Show what actions would be taken without executing them"
                echo -e "  -h, --help        Show this help message"
                echo -e ""
                echo -e "Actions:"
                echo -e "  touchpad          Toggle touchpad state"
                echo -e "  touchpad-on       Enable touchpad"
                echo -e "  touchpad-off      Disable touchpad"
                echo -e ""
                echo -e "  mouse             Toggle mouse/pointing devices state"
                echo -e "  mouse-on          Enable mouse/pointing devices"
                echo -e "  mouse-off         Disable mouse/pointing devices"
                echo -e ""
                echo -e "  keyboard          Toggle keyboard state"
                echo -e "  keyboard-on       Enable keyboard"
                echo -e "  keyboard-off      Disable keyboard"
                exit 0
                ;;
            -d|--dry-run)
                dry_run=1
                shift
                ;;
            *)
                echo "Unknown option: $1" >&2
                exit 1
                ;;
        esac
    done

    if [[ -z "${1}" ]] ; then
        echo "Error: Action required. Use -h or --help for usage." >&2
        exit 1
    fi

    input="$1"

    # Helper function to run or dry-run commands
    run_cmd() {
        if ((dry_run)); then
            echo "[DRY-RUN] Would execute: $*"
        else
            "$@"
        fi
    }

    get_default_master() {
        local type="$1"
        local m
        if [[ "$type" == "keyboard" ]]; then
            m="$(xinput list | grep -Ei "Virtual core keyboard" | grep -oE "id=[0-9]+" | cut -d= -f2 | head -n1)"
            echo "${m:-3}"
        else
            m="$(xinput list | grep -Ei "Virtual core pointer" | grep -oE "id=[0-9]+" | cut -d= -f2 | head -n1)"
            echo "${m:-2}"
        fi
    }

    # }}}

    case "$input" in
        "touchpad-on")
            # get conf in order to know where to reattach deactivated keyboards
            el_config_get

            while read -ru 3 line
            do
                id="$( echo "$line" | tr ' ' '\n' | grep -E "^\s*id=" | awk '{print $1}' | sed -e 's|^id=||g' | tail -1 )"
                read -r id <<< "$id"

                master="$( echo "$line" | tr ' ' '\n' | grep -E "\(.*\)\]" | awk '{print $1}' | sed -e 's|^(||g' -e 's|).*$||g' | tail -1 )"
                read -r master <<< "$master"

                if echo "$id" | grep -qsE "^[[:digit:]]+$" ; then

                    if [[ -z "$master" ]] ; then
                        for i in "${conf_master_of_ids_touchpad[@]}" ; do
                            master="$( echo "$i" | awk -v id="$id" '{if ($2 == id) print $1}' )"
                            [[ -n "$master" ]] && break
                        done
                    fi
                    if [[ -z "$master" ]] ; then
                        master="$(get_default_master pointer)"
                    fi

                    # activate
                    el_debug "re-activating id '$id' from master '$master'"
                    run_cmd xinput reattach "$id" "$master"
                    fi
            done 3<<< "$( xinput list | grep -Ei "(Touchpad).*(slave\s+pointer|floating\s+slave)" 2>&1 )"
            ;;

        "touchpad-off")
            # get conf in order to know where to reattach deactivated keyboards
            el_config_get

            while read -ru 3 line
            do
                id="$( echo "$line" | tr ' ' '\n' | grep -E "^\s*id=" | awk '{print $1}' | sed -e 's|^id=||g' | tail -1 )"
                read -r id <<< "$id"

                master="$( echo "$line" | tr ' ' '\n' | grep -E "\(.*\)\]" | awk '{print $1}' | sed -e 's|^(||g' -e 's|).*$||g' | tail -1 )"
                read -r master <<< "$master"

                if echo "$id" | grep -qsE "^[[:digit:]]+$" ; then

                    # always create a new conf to delete old entries
                    if echo "$master" | grep -qsE "^[[:digit:]]+$" ; then
                        # deactivate
                        el_debug "deactivating id '$id' from master '$master'"
                        run_cmd xinput float "$id"

                        # important, save the master value in order to be used later if we want to reattach
                        el_array_member_add "$master $id" "${conf_master_of_ids_touchpad[@]}" ; conf_master_of_ids_touchpad=("${_out[@]}")
                        if ((dry_run)); then
                            echo "[DRY-RUN] Would save conf_master_of_ids_touchpad"
                        else
                            el_config_save "conf_master_of_ids_touchpad"
                        fi
                    fi
                fi
            done 3<<< "$( xinput list | grep -Ei "(Touchpad).*(slave\s+pointer|floating\s+slave)" 2>&1 )"

            ;;


        "touchpad")
            # get conf in order to know where to reattach deactivated keyboards
            el_config_get

            while read -ru 3 line
            do
                id="$( echo "$line" | tr ' ' '\n' | grep -E "^\s*id=" | awk '{print $1}' | sed -e 's|^id=||g' | tail -1 )"
                read -r id <<< "$id"

                master="$( echo "$line" | tr ' ' '\n' | grep -E "\(.*\)\]" | awk '{print $1}' | sed -e 's|^(||g' -e 's|).*$||g' | tail -1 )"
                read -r master <<< "$master"

                if echo "$id" | grep -qsE "^[[:digit:]]+$" ; then
                    if echo "$line" | grep -qsEi "floating\s+slave" ; then
                        if [[ -z "$master" ]] ; then
                             for i in "${conf_master_of_ids_touchpad[@]}" ; do
                                 master="$( echo "$i" | awk -v id="$id" '{if ($2 == id) print $1}' )"
                                 [[ -n "$master" ]] && break
                             done
                        fi
                        if [[ -z "$master" ]] ; then
                            master="$(get_default_master pointer)"
                        fi

                        # activate
                        el_debug "re-activating id '$id' from master '$master'"
                        run_cmd xinput reattach "$id" "$master"

                        # forget this conf
                        el_array_member_unset "$master $id" "${conf_master_of_ids_touchpad[@]}" ; conf_master_of_ids_touchpad=("${_out[@]}")
                        if ((dry_run)); then
                            echo "[DRY-RUN] Would save conf_master_of_ids_touchpad"
                        else
                            el_config_save "conf_master_of_ids_touchpad"
                        fi
                    else
                        # always create a new conf to delete old entries
                        if echo "$master" | grep -qsE "^[[:digit:]]+$" ; then
                            # deactivate
                            el_debug "deactivating id '$id' from master '$master'"
                            run_cmd xinput float "$id"

                            # important, save the master value in order to be used later if we want to reattach
                            el_array_member_add "$master $id" "${conf_master_of_ids_touchpad[@]}" ; conf_master_of_ids_touchpad=("${_out[@]}")
                            if ((dry_run)); then
                                echo "[DRY-RUN] Would save conf_master_of_ids_touchpad"
                            else
                                el_config_save "conf_master_of_ids_touchpad"
                            fi
                        fi
                    fi
                fi
            done 3<<< "$( xinput list | grep -Ei "(Touchpad).*(slave\s+pointer|floating\s+slave)" 2>&1 )"

            ;;

        "mouse-on")
            el_config_get
            while read -ru 3 line
            do
                id="$( echo "$line" | tr ' ' '\n' | grep -E "^\s*id=" | awk '{print $1}' | sed -e 's|^id=||g' | tail -1 )"
                read -r id <<< "$id"
                master="$( echo "$line" | tr ' ' '\n' | grep -E "\(.*\)\]" | awk '{print $1}' | sed -e 's|^(||g' -e 's|).*$||g' | tail -1 )"
                read -r master <<< "$master"
                if echo "$id" | grep -qsE "^[[:digit:]]+$" ; then
                    if [[ -z "$master" ]] ; then
                        for i in "${conf_master_of_ids_mouse[@]}" ; do
                            master="$( echo "$i" | awk -v id="$id" '{if ($2 == id) print $1}' )"
                            [[ -n "$master" ]] && break
                        done
                    fi
                    if [[ -z "$master" ]] ; then
                        master="$(get_default_master pointer)"
                    fi
                    el_debug "re-activating mouse id '$id' from master '$master'"
                    run_cmd xinput reattach "$id" "$master"
                fi
            done 3<<< "$( xinput list | grep -Ei "(TrackPoint|TPPS/2|Mouse|Genius|Wireless|Touch Controller).*(slave\s+pointer|floating\s+slave)" 2>&1 )"
            ;;

        "mouse-off")
            el_config_get
            while read -ru 3 line
            do
                id="$( echo "$line" | tr ' ' '\n' | grep -E "^\s*id=" | awk '{print $1}' | sed -e 's|^id=||g' | tail -1 )"
                read -r id <<< "$id"
                master="$( echo "$line" | tr ' ' '\n' | grep -E "\(.*\)\]" | awk '{print $1}' | sed -e 's|^(||g' -e 's|).*$||g' | tail -1 )"
                read -r master <<< "$master"
                if echo "$id" | grep -qsE "^[[:digit:]]+$" ; then
                    if echo "$master" | grep -qsE "^[[:digit:]]+$" ; then
                        el_debug "deactivating mouse id '$id' from master '$master'"
                        run_cmd xinput float "$id"
                        el_array_member_add "$master $id" "${conf_master_of_ids_mouse[@]}" ; conf_master_of_ids_mouse=("${_out[@]}")
                        if ((dry_run)); then
                            echo "[DRY-RUN] Would save conf_master_of_ids_mouse"
                        else
                            el_config_save "conf_master_of_ids_mouse"
                        fi
                    fi
                fi
            done 3<<< "$( xinput list | grep -Ei "(TrackPoint|TPPS/2|Mouse|Genius|Wireless|Touch Controller).*(slave\s+pointer|floating\s+slave)" 2>&1 )"
            ;;

        "mouse")
            # get conf in order to know where to reattach deactivated keyboards
            el_config_get

            while read -ru 3 line
            do
                id="$( echo "$line" | tr ' ' '\n' | grep -E "^\s*id=" | awk '{print $1}' | sed -e 's|^id=||g' | tail -1 )"
                read -r id <<< "$id"

                master="$( echo "$line" | tr ' ' '\n' | grep -E "\(.*\)\]" | awk '{print $1}' | sed -e 's|^(||g' -e 's|).*$||g' | tail -1 )"
                read -r master <<< "$master"

                if echo "$id" | grep -qsE "^[[:digit:]]+$" ; then
                    if echo "$line" | grep -qsEi "floating\s+slave" ; then
                        if [[ -z "$master" ]] ; then
                             for i in "${conf_master_of_ids_mouse[@]}" ; do
                                 master="$( echo "$i" | awk -v id="$id" '{if ($2 == id) print $1}' )"
                                 [[ -n "$master" ]] && break
                             done
                        fi
                        if [[ -z "$master" ]] ; then
                            master="$(get_default_master pointer)"
                        fi

                        # activate
                        el_debug "re-activating id '$id' from master '$master'"
                        run_cmd xinput reattach "$id" "$master"

                        # forget this conf
                        el_array_member_unset "$master $id" "${conf_master_of_ids_mouse[@]}" ; conf_master_of_ids_mouse=("${_out[@]}")
                        if ((dry_run)); then
                            echo "[DRY-RUN] Would save conf_master_of_ids_mouse"
                        else
                            el_config_save "conf_master_of_ids_mouse"
                        fi
                    else
                        # always create a new conf to delete old entries
                        if echo "$master" | grep -qsE "^[[:digit:]]+$" ; then
                            # deactivate
                            el_debug "deactivating id '$id' from master '$master'"
                            run_cmd xinput float "$id"

                            # important, save the master value in order to be used later if we want to reattach
                            el_array_member_add "$master $id" "${conf_master_of_ids_mouse[@]}" ; conf_master_of_ids_mouse=("${_out[@]}")
                            if ((dry_run)); then
                                echo "[DRY-RUN] Would save conf_master_of_ids_mouse"
                            else
                                el_config_save "conf_master_of_ids_mouse"
                            fi
                        fi
                    fi
                fi
            done 3<<< "$( xinput list | grep -Ei "(TrackPoint|TPPS/2|Mouse|Genius|Wireless|Touch Controller).*(slave\s+pointer|floating\s+slave)" 2>&1 )"

            ;;

        "keyboard-on")
            el_config_get
            while read -ru 3 line
            do
                id="$( echo "$line" | tr ' ' '\n' | grep -E "^\s*id=" | awk '{print $1}' | sed -e 's|^id=||g' | tail -1 )"
                read -r id <<< "$id"
                master="$( echo "$line" | tr ' ' '\n' | grep -E "\(.*\)\]" | awk '{print $1}' | sed -e 's|^(||g' -e 's|).*$||g' | tail -1 )"
                read -r master <<< "$master"
                if echo "$id" | grep -qsE "^[[:digit:]]+$" ; then
                    if [[ -z "$master" ]] ; then
                        for i in "${conf_master_of_ids_keyboard[@]}" ; do
                            master="$( echo "$i" | awk -v id="$id" '{if ($2 == id) print $1}' )"
                            [[ -n "$master" ]] && break
                        done
                    fi
                    if [[ -z "$master" ]] ; then
                        master="$(get_default_master keyboard)"
                    fi
                    el_debug "re-activating keyboard id '$id' from master '$master'"
                    run_cmd xinput reattach "$id" "$master"
                fi
            done 3<<< "$( xinput list | grep -Ei "(USB keyboard|AT Translated).*(slave\s+keyboard|floating\s+slave)" 2>&1 )"
            ;;

        "keyboard-off")
            el_config_get
            while read -ru 3 line
            do
                id="$( echo "$line" | tr ' ' '\n' | grep -E "^\s*id=" | awk '{print $1}' | sed -e 's|^id=||g' | tail -1 )"
                read -r id <<< "$id"
                master="$( echo "$line" | tr ' ' '\n' | grep -E "\(.*\)\]" | awk '{print $1}' | sed -e 's|^(||g' -e 's|).*$||g' | tail -1 )"
                read -r master <<< "$master"
                if echo "$id" | grep -qsE "^[[:digit:]]+$" ; then
                    if echo "$master" | grep -qsE "^[[:digit:]]+$" ; then
                        el_debug "deactivating keyboard id '$id' from master '$master'"
                        run_cmd xinput float "$id"
                        el_array_member_add "$master $id" "${conf_master_of_ids_keyboard[@]}" ; conf_master_of_ids_keyboard=("${_out[@]}")
                        if ((dry_run)); then
                            echo "[DRY-RUN] Would save conf_master_of_ids_keyboard"
                        else
                            el_config_save "conf_master_of_ids_keyboard"
                        fi
                    fi
                fi
            done 3<<< "$( xinput list | grep -Ei "(USB keyboard|AT Translated).*(slave\s+keyboard|floating\s+slave)" 2>&1 )"
            ;;

        "keyboard")
            # get conf in order to know where to reattach deactivated keyboards
            el_config_get

            while read -ru 3 line
            do
                id="$( echo "$line" | tr ' ' '\n' | grep -E "^\s*id=" | awk '{print $1}' | sed -e 's|^id=||g' | tail -1 )"
                read -r id <<< "$id"

                master="$( echo "$line" | tr ' ' '\n' | grep -E "\(.*\)\]" | awk '{print $1}' | sed -e 's|^(||g' -e 's|).*$||g' | tail -1 )"
                read -r master <<< "$master"

                if echo "$id" | grep -qsE "^[[:digit:]]+$" ; then
                    if echo "$line" | grep -qsEi "floating\s+slave" ; then
                        if [[ -z "$master" ]] ; then
                             for i in "${conf_master_of_ids_keyboard[@]}" ; do
                                 master="$( echo "$i" | awk -v id="$id" '{if ($2 == id) print $1}' )"
                                 [[ -n "$master" ]] && break
                             done
                        fi
                        if [[ -z "$master" ]] ; then
                            master="$(get_default_master keyboard)"
                        fi

                        # activate keyboard
                        el_debug "re-activating keyboard id '$id' from master '$master'"
                        run_cmd xinput reattach "$id" "$master"

                        # forget this conf
                        el_array_member_unset "$master $id" "${conf_master_of_ids_keyboard[@]}" ; conf_master_of_ids_keyboard=("${_out[@]}")
                        if ((dry_run)); then
                            echo "[DRY-RUN] Would save conf_master_of_ids_keyboard"
                        else
                            el_config_save "conf_master_of_ids_keyboard"
                        fi
                    else
                        # always create a new conf to delete old entries
                        if echo "$master" | grep -qsE "^[[:digit:]]+$" ; then
                            # deactivate keyboard
                            el_debug "deactivating keyboard id '$id' from master '$master'"
                            run_cmd xinput float "$id"

                            # important, save the master value in order to be used later if we want to reattach
                            el_array_member_add "$master $id" "${conf_master_of_ids_keyboard[@]}" ; conf_master_of_ids_keyboard=("${_out[@]}")
                            if ((dry_run)); then
                                echo "[DRY-RUN] Would save conf_master_of_ids_keyboard"
                            else
                                el_config_save "conf_master_of_ids_keyboard"
                            fi
                        fi
                    fi
                fi
            done 3<<< "$( xinput list | grep -Ei "(USB keyboard|AT Translated).*(slave\s+keyboard|floating\s+slave)" 2>&1 )"
            ;;
    esac

}

#
#  MAIN
#
main "$@"

# vim: set foldmethod=marker :
