#!/bin/bash
SOURCE="$0"
source /usr/lib/elive-tools/functions
EL_REPORTS="1"
#TEXTDOMAIN="" # disabled here on purpose because this tools is not used anymore after buster

# include sbin in our PATH since its needed sometimes, and there's nothing wrong by using it!
if [[ "$PATH" != *"/usr/sbin"* ]] ; then
    # needed for: laptop-detect
    export PATH="${PATH}:/usr/local/sbin:/usr/sbin:/sbin"
fi


# TODO: since we install our own drivers, can we remove the package libgl1-mesa-dri ? (because it wastes 100 MB from installation), will need some betatestings


#===  FUNCTION  ================================================================
#          NAME:  usage
#   DESCRIPTION:  Shows the usage help, don't exit
#===============================================================================
usage(){
    #
    # if -a : should return true in case of installed or false if install failed
    #           already installed? already running?
    # if -i : will ask the user which version to install (suggesting the best option to use)
    # if -f : only for debug purposes, but should install successfully too
    #
    echo -e "Usage: $(basename $BASH_SOURCE) [options]"
    echo -e "  -a: auto install"
    echo -e "  -d: detect only (return true or false if we have ati or not)"
    echo -e "  -l: live mode (don't pre-download packages, pre-ask if want to install, more interactive)"
    echo -e "  -f: force install (if no ati cards are found)"
    echo -e "  -q: quiet mode"
    echo -e "  -h: help usage"
    echo -e "  -c: check only (tell which version of the drivers we need)"
    echo -e "  -t: test driver only (if the driver is correctly installed and working)"
    echo -e "  -m: model (version of drivers) to use"
    echo -e "      - like:  current, legacy"
    echo -e "        - legacy versions:  from HD 2000 to HD 4000"
    echo -e "        - current versions: from HD 5000 to higher"
    #echo -e "  -s: simulate mode (simulate that you have the specified model hardware"
    echo -e "  -u: uninstall drivers"
    echo -e "  -v: verbose mode"
}

#===  FUNCTION  ================================================================
#          NAME:  check_driver
#   DESCRIPTION:  check if is already installed
#    PARAMETERS:  -
#       RETURNS:  true | false
#===============================================================================
check_driver(){
    # we should have enough with only this file, if is not installed it should have been removed!
    if ((is_wheezy)) ; then
        if ! [[ -s "/etc/X11/xorg.conf.d/20-nvidia.conf" ]] ; then
            return 1
        fi
    fi
    # but wee need also to make sure that is 'correctly' installed
    if ! modprobe fglrx ; then
        return 1
    fi
    # just another test
    if ! lsmod | grep -qs fglrx ; then
        return 1
    fi
}
#===  FUNCTION  ================================================================
#          NAME:  check_hardware
#   DESCRIPTION:  check the hardware if has or not the graphic card
#    PARAMETERS:  -
#       RETURNS:  -
#===============================================================================
check_hardware(){
    # pre {{{
    el_debug
    #el_security_function_loop || return 0

    # we don't need to check if we have the hardware if we want to uninstall the driver
    if ((is_mode_uninstall)) ; then
        return 0
    fi

    # }}}
    # detect if we have the hardware with ati {{{
    # pci-id with ati on first graphic card

    # check if hardware has ati
    # TODO: if has intel too, strongly suggests to use intel instead
    # TODO: if something like:  01:00.0 VGA compatible controller: Advanced Micro Devices [AMD] nee ATI RV370 5B60 [Radeon X300 (PCIE)]
    #         try to catch the PCIE instead which means "new"
    if lspci | grep -iE "\W+(VGA|3D|2D|Display)\W+.*\W+(AMD|ATI)\W+" | grep -qsE "(AMD|ATI)" ; then
        el_debug "ati card found in lspci"
        is_ati_card_found=1
    fi

    if echo "${_CMDLINE}" | LC_ALL=C grep -qsiE "simulate=fglrx" ; then
        is_ati_card_found=1
        # we also want/need to force the install because there's no real hardware here
        is_mode_force=1
    fi


    # force or exit?
    if ! ((is_ati_card_found)) ; then
        if ((is_mode_force)) ; then
            el_info "Force mode in a machine where is not detected ati card"
            is_ati_card_found=1
        else
            el_info "No ati graphic cards found on this machine"
            exit 1
        fi
    fi

    # in mode check we dont want to install, just to check
    if ((is_mode_detect)) ; then
        el_info "ATI card detected"
        exit 0
    fi

    # - detect if we have the hardware with ati }}}
}
#===  FUNCTION  ================================================================
#          NAME:  detect_driver_version
#   DESCRIPTION:  detect or ask which version of the driver to use
#    PARAMETERS:  -
#       RETURNS:  -
#===============================================================================
detect_driver_version(){
    # pre {{{
    local prev_dir file
    prev_dir="$(pwd)"

    el_debug

    # }}}
    # checks to determine version {{{
    # manual mode
    if el_check_variables "driver_version" 1>/dev/null 2>&1 ; then
        el_debug "Selected ${driver_version} version of drivers to use"
        _FGLRX_VERSION="$driver_version"
        return 0
    fi


    if [[ -z "$driver_version" ]] ; then
        driver_version="$( lspci | grep -iE "\W+(VGA|3D|2D|Display)\W+.*\W+(AMD|ATI)\W+" | grep -E "(AMD|ATI)" | sort -uV | sed -e 's|^.*Radeon HD||g' -e 's|^.*Radeon ||g' -e 's|^.*Rage||g' -e 's|Series.*$||g' -e 's/[^0-9]*//g' | grep -E "[[:digit:]]" | awk '{print $1}' | head -1 )"
        read -r driver_version <<< "$driver_version"

        if [[ -n "$driver_version" ]] ; then
            if [[ "${driver_version}" -gt "4000" ]] ; then
                driver_version="current"
            else
                driver_version="legacy"
            fi
        fi
    fi


    # nothing? use default
    if [[ -z "$driver_version" ]] ; then
        NOREPORTS=1 el_warning "Going to install the fglrx drivers but you didn't say which version, assuming 'current' then..."
        driver_version="current"
    fi

    # mark it
    if [[ -n "$driver_version" ]] ; then
        _FGLRX_VERSION="$driver_version"
    fi


    # }}}
    # - show result found {{{

    # if we only  want to check, we don't need to do anything more here, just exit
    if ((is_mode_check)) ; then
        echo -e "The detected ATI drivers for your machine is maybe: $_FGLRX_VERSION"
        exit
    fi

    # - show result found }}}
}
#===  FUNCTION  ================================================================
#          NAME:  interactive_ask_privative
#   DESCRIPTION:  ask to the user if wants to install the privative driver or not
#    PARAMETERS:  -
#       RETURNS:  -
#===============================================================================
interactive_ask_privative(){
    # pre {{{
    local ret
    el_debug


    # }}}
    # more than one type of card found {{{
    if [[ "$(lspci | grep -E "\W+(VGA|3D|2D|Display)\W+" | wc -l )" -gt "1" ]] && ! [[ "$(lspci | grep -E "\W+(VGA|3D|2D|Display)\W+" | grep -iE "\W+(VGA|3D|2D|Display)\W+.*\W+(AMD|ATI)\W+" | grep -E "(AMD|ATI)" | wc -l )" -gt "1" ]] && ! ((is_mode_auto)) ; then
        local message_multiple_cards
        message_multiple_cards="$( printf "$( eval_gettext "We have found more than one graphics card on your computer. If you choose to install proprietary drivers, we will proceed using your ATI graphics card." )" "" )"


        dialog --timeout 80 --clear --colors --backtitle "Elive Systems: Use Ctrl-L to redraw, Enter to confirm" \
            --title "Multiple Graphic Cards found" \
            --msgbox "$message_multiple_cards" \
            0 0
    fi
    # - more than one card }}}
    # ask if want to install the privative one or the free {{{
    if echo "${_CMDLINE}" | LC_ALL=C grep -qsE "onlyfree" ; then
        echo -e "Using free-drivers only because 'onlyfree' is set in your boot parameters" 1>&2
        ret=1
    else

        if ((is_mode_live)) ; then

            # warn if low memory that the process can fail!
            memory="$( cat /proc/meminfo | grep -i Memtotal | tail -1 | awk '{print $2}' )"
            if [[ "${memory}" -lt "640000" ]] && ! ((is_mode_auto)) ; then

                local message_low_memory
                message_low_memory="$( printf "$( eval_gettext "Your computer has low RAM, so installing big packages in live mode might fail, try installing Elive on your hard disk first and then install the packages again to prevent memory issues, after installing Elive, boot with the 'init 1' parameter to skip the graphical system and run the command '%s -a' to start the installation again." )" "$(basename $0)" )"

                dialog --timeout 80 --clear --colors --backtitle "Elive Systems: Use Ctrl-L to redraw, Enter to confirm" \
                    --title "Low Memory Computer" \
                    --msgbox "$message_low_memory" \
                    0 0
            fi


            # don't ask if mode auto, assume yes
            if ((is_mode_auto)) ; then
                ret=0
            else
                local message_title
                message_title="$( printf "$( eval_gettext "AMD/ATI Graphic Card" )" "" )"
                local message_message
                message_message="$( printf "$( eval_gettext "Do you want to install ATI's proprietary graphical drivers? Some computers need them, while others work better with the open drivers. Try both modes to know which one suits you best. If you cannot make them work correctly, or you have graphical issues, we suggest you use an Nvidia or Intel graphic card, which are more reliable." )" "" )"

                dialog --timeout 60 --clear --colors --backtitle "Elive Systems: Use Ctrl-L to redraw, Enter to confirm" \
                    --title "$message_title" \
                    --yesno "$message_message" \
                    0 0
                ret="$?"
            fi
        else
            # we are running this command manually so we don't want to ask if we want to do what we want to do :P
            ret="0"
        fi
    fi

    case "$ret" in
        0|255|123) # yes, timeout, cancel
            if ((is_mode_live)) ; then
                log_progress_msg "Installing proprietary ATI drivers"
                # checks if we can install it {{{
                if ! echo "${_CMDLINE}" | LC_ALL=C grep -qsE "blacklist=radeon" && lsmod | grep -qs '^radeon' ; then
                    local message_reboot_and_select_privative
                    message_reboot_and_select_privative="$( printf "$( eval_gettext "To install the proprietary drivers, you must reboot and select that specific option from the boot menu. Or you can also use any boot mode, but then you need to press the Tab key to append the next boot parameter:" ) modprobe.blacklist=radeon modprobe.blacklist=radeonhd" "" )"

                    dialog --timeout 80 --clear --colors --backtitle "Elive Systems: Use Ctrl-L to redraw, Enter to confirm" \
                        --title "Free-Driver Option" \
                        --msgbox "$message_reboot_and_select_privative" \
                        0 0

                    if ((is_mode_live)) ; then
                        reboot
                    fi

                fi
                # }}}
                # remember that this is not stable {{{
                local message_remember
                message_remember="$( printf "$( eval_gettext "If the selected driver doesn't work, try another option from the list or use the open-source drivers. If none of these work stably, consider purchasing a better-supported graphics card for your computer. Your computer, especially your filesystem, will thank you." )" "" )"

                dialog --timeout 60 --clear --colors --backtitle "Elive Systems: Use Ctrl-L to redraw, Enter to confirm" \
                    --title "If the install fails..." \
                    --msgbox "$message_remember" \
                    0 0

                # - remember that this is not stable }}}
            fi
            ;;
        1) # no
            if ((is_mode_live)) ; then
                if echo "${_CMDLINE}" | LC_ALL=C grep -qsE "blacklist=radeon" ; then
                    # tell the user to reboot with onlyfree option
                    local message_onlyfree
                    if ((is_wheezy)) ; then
                        message_onlyfree="$( printf "$( eval_gettext "To use the open-drivers, reboot and select the 'Only open-drivers' option. Due to compatibility reasons, the Radeon module is blacklisted on boot. To have the open-drivers work, reboot and select this option or remove Radeon from the blacklist in the boot parameters." )" "" )"
                    else
                        message_onlyfree="$( printf "$( eval_gettext "Reboot without selecting the proprietary drivers option, or remove the parameter '%s' from the boot options by pressing the Tab key (or \"E\" from UEFI boot). Booting without this driver is necessary for compatibility; this step is required to proceed." )" "modprobe.blacklist=radeon*" )"
                    fi

                    dialog --timeout 80 --clear --colors --backtitle "Elive Systems: Use Ctrl-L to redraw, Enter to confirm" \
                        --title "Free-Driver Option" \
                        --msgbox "$message_onlyfree" \
                        0 0
                else
                    log_progress_msg "Using the free-drivers..."
                fi
            fi

            # not needed to do anything, just exit
            el_debug "We don't need to do anything, continue using the free-drivers..."
            exit
            ;;
    esac

    # - ask if want to install the privative one or the free }}}
}
#===  FUNCTION  ================================================================
#          NAME:  interactive_ask_driver_version
#   DESCRIPTION:  ask to the user which driver to install
#    PARAMETERS:  -
#       RETURNS:  -
#===============================================================================
interactive_ask_driver_version(){
    # pre {{{
    local line entry _is_preselection_set _id _desc ret
    el_debug

    # }}}
    # List available versions and ask in a dialog {{{


    if ! ((is_mode_auto)) && ! ((is_mode_version_set)) ; then
        local message_select_driver
        message_select_driver="$( printf "$( eval_gettext "Select the version of the driver your graphics card needs." )" "" )"
        if [[ -n "$_FGLRX_VERSION" ]] ; then
            local message_select_driver_suggested
            message_select_driver_suggested="$( printf "$( eval_gettext "The version '%s' is probably the one that you need." )" "$_FGLRX_VERSION" )"
        fi

        dialog --timeout 240 --clear --colors --backtitle "Elive Systems: Use Ctrl-L to redraw, Enter to confirm" --menu "$message_select_driver""\n\n$message_select_driver_suggested" 0 0 0 \
            "free-driver" "$( eval_gettext "Recommended open-source driver" )" \
            "current" "$( eval_gettext "For newer cards, starting from the Radeon series 5000." )" \
            "legacy" "$( eval_gettext "For older cards, up to the Radeon 4000 series" )" \
            2>"/tmp/.$(basename $0)-ret"


        # user canceled? uninstall and exit
        if echo "$?" | grep -qsE "^(1|123|255|125)$" ; then
            uninstall_driver
            exit
        fi

        # get result
        ret="$( cat "/tmp/.$(basename $0)-ret" | head -1 )"
        rm -f "/tmp/.$(basename $0)-ret"

        # remove extra leading blank chars
        read -r ret <<< "$ret"

        # if users's cancel, we have no results at all
        if [[ -z "$ret" ]] ; then
            uninstall_driver
            exit
        fi

        log_progress_msg "Using the '$ret' ATI drivers version"
        # add a pause in case we selected a different than the expected one
        if [[ "${ret}" != "$_FGLRX_VERSION" ]] ; then
            sleep 2
            log_progress_msg "Note: the selected version ($ret) is not the same as the suggested one ($_FGLRX_VERSION)"
            sleep 4
        fi

        # update / force the version to use
        if [[ -n "$ret" ]] ; then
            _FGLRX_VERSION="$ret"
        fi

    fi


    # - List available versions and ask in a dialog }}}
    # select packages to install depending on which version we selected {{{
    memory="$( cat /proc/meminfo | grep -i Memtotal | tail -1 | awk '{print $2}' )"

    case $_FGLRX_VERSION in
        current)
            # warning, do not install xvba-va-driver -> conflicts
            if [[ "${memory}" -lt "640000" ]] ; then
                # install a basic fglrx setup if low memory
                _FGLRX_PACKAGES="fglrx-driver fglrx-modules-dkms libgl1-fglrx-glx"
            else
                _FGLRX_PACKAGES="fglrx-atieventsd fglrx-control fglrx-driver fglrx-modules-dkms libfglrx-amdxvba1 libgl1-fglrx-glx"
            fi

            # basic packages tested:
            ;;
        legacy)
            if [[ "${memory}" -lt "640000" ]] ; then
                _FGLRX_PACKAGES="fglrx-legacy-driver fglrx-legacy-modules-dkms libgl1-fglrx-legacy-glx"
            else
                _FGLRX_PACKAGES="fglrx-legacy-atieventsd fglrx-legacy-control fglrx-legacy-driver fglrx-legacy-modules-dkms libfglrx-legacy-amdxvba1 libgl1-fglrx-legacy-glx"
            fi
            ;;
        *)
            # free one? don't do anything, exit
            exit
            ;;
    esac

    el_debug "Selected list of packages to install:\n$( echo "${_FGLRX_PACKAGES}" | tr ' ' '\n' )"


    # - select packages to install depending on which version we selected }}}
}

#===  FUNCTION  ================================================================
#          NAME:  install_driver
#   DESCRIPTION:  prepare system and install the driver to use fglrx
#    PARAMETERS:  -
#       RETURNS:  -
#===============================================================================
install_driver(){
    # pre {{{
    el_debug

    if ! el_check_variables "_FGLRX_VERSION" ; then
        el_error "We don't know which version of fglrx to use"
        exit 1
    fi

    if ! el_check_variables "_FGLRX_PACKAGES" ; then
        el_error "We don't know which packages of fglrx to install"
        exit 1
    fi

    mkdir -p /etc/X11/xorg.conf.d


    # }}}

    # conf {{{
    # create conf first
    : > /etc/X11/xorg.conf.d/20-fglrx.conf

    echo 'Section "Device"' >> /etc/X11/xorg.conf.d/20-fglrx.conf
    echo '        Identifier     "Default screen"' >> /etc/X11/xorg.conf.d/20-fglrx.conf
    echo '        Driver         "fglrx"' >> /etc/X11/xorg.conf.d/20-fglrx.conf
    echo '        # append options here' >> /etc/X11/xorg.conf.d/20-fglrx.conf # do not remove
    echo 'EndSection' >> /etc/X11/xorg.conf.d/20-fglrx.conf

    # - conf }}}
    # Optimus inform to user {{{
    # OPTIMUS devices: if we are in laptop, and have more than one graphic card and both are not ati ones...
    if [[ "$(lspci | grep -E "\W+(VGA|3D|2D|Display)\W+" | wc -l )" -gt "1" ]] && ! [[ "$(lspci | grep -E "\W+(VGA|3D|2D|Display)\W+" | grep -iE "\W+(VGA|3D|2D|Display)\W+.*\W+(AMD|ATI)\W+" | grep -E "(AMD|ATI)" | wc -l )" -gt "1" ]] && ! ((is_mode_auto)) ; then

        if laptop-detect ; then
            local message_multiple_cards
            message_multiple_cards="$( printf "$( eval_gettext "An additional graphics card has been detected. Your laptop probably uses special ATI shared drivers, using the internal card to save battery power and switching to the ATI driver when more performance is necessary. You can use the ATI graphic card in Elive if you install FGLRX. Otherwise, the Intel card will be used. FGLRX will be used for now. If you have any problems with your graphical system, it is suggested to disable one of them in the BIOS settings. Use Google to find out how to set up your BIOS." )" "" )"
        else
            local message_multiple_cards
            message_multiple_cards="$( printf "$( eval_gettext "An additional graphics card has been detected, we will proceed by using FGLRX but if you have any problem running the graphical system we suggest you remove one of the graphic cards. If the other graphic card is included in the motherboard you should be able to disable it from the BIOS. Search in Google to know how to configure your BIOS." )" "" )"
        fi

        dialog --timeout 80 --clear --colors --backtitle "Elive Systems: Use Ctrl-L to redraw, Enter to confirm" \
            --title "Multiple Graphic Cards found" \
            --msgbox "$message_multiple_cards" \
            0 0
    fi
    # - Optimus inform to user }}}

    # unload modules {{{
    # note: we should have already enough memory because we should have already requested to add a swap in case that we don't have enough space
    if lsmod | grep -qsE "(radeon|radeonhd)" ; then
        rmmod -f radeon
        rmmod -f radeonhd

        if lsmod | grep -qsE "(radeon|radeonhd)" ; then
            el_error "\nE: radeon|radeonhd module is loaded and we cannot unload it"
            el_info "You should reboot and add the boot parameter 'modprobe.blacklist=radeon,radeonhd' to tell the kernel to not load it, or you can use the -f option (but it can make your screen unreadable, which is ok if you are running it from a ssh)"
        fi
    fi

    # just in case another one is used
    rmmod radeon 2>/dev/null
    rmmod radeonhd 2>/dev/null

    # - unload modules }}}
    # apt-get install {{{

    echo -e "\n\n\n\n\nInstalling... Please be patient...\n\n"
    sleep 2

    if ! TERM=screen-256color DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical DEBCONF_NONINTERACTIVE_SEEN=true DEBCONF_NOWARNINGS=true apt-get install -y $_FGLRX_PACKAGES ; then
        el_aptget_update

        if ! TERM=screen-256color DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical DEBCONF_NONINTERACTIVE_SEEN=true DEBCONF_NOWARNINGS=true apt-get install -y $_FGLRX_PACKAGES ; then
            el_aptget_update force

            if ! TERM=screen-256color DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical DEBCONF_NONINTERACTIVE_SEEN=true DEBCONF_NOWARNINGS=true apt-get install -y $_FGLRX_PACKAGES ; then
                while read -ru 3 package
                do
                    if ! TERM=screen-256color DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical DEBCONF_NONINTERACTIVE_SEEN=true DEBCONF_NOWARNINGS=true apt-get install -y $package ; then
                        sleep 5
                        echo -e "\nE: Installing fglrx packages failed, report the previous error messages to Elive" 1>&2
                        sleep 10
                    fi
                done 3<<< "$( echo "$_FGLRX_PACKAGES")"
            fi
        fi
    fi


    # add the packages to the installed system later too
    if echo "${_CMDLINE}" | LC_ALL=C grep -qsE "boot=live" ; then
        # first remove any possible previous entry for fglrx
        sed -i '/fglrx/d' /tmp/.packages-to-install 2>/dev/null
        sed -i '/fglrx/d' /tmp/.packages-to-hold    2>/dev/null

        for package in $_FGLRX_PACKAGES
        do
            echo "$package" >> /tmp/.packages-to-install
            # just like the kernel, keep them holded, we don't want surprises, if a system works it works
            echo "$package" >> /tmp/.packages-to-hold
        done
    fi

    LC_ALL="$EL_LC_EN" update-initramfs -k all -u -t 2>&1 | grep -vE '(^mkdir:|mdadm:|Generating /|live-boot)'
    rm -f /boot/*old-dkms 2>/dev/null


    # - apt-get install }}}
    # load module {{{
    # reload devices just in case
    service fglrx-atieventsd restart 1>/dev/null 2>&1

    # load driver
    if ! modprobe fglrx ; then
        sleep 4
        local message_unable_to_load

        # default message for not working drivers
        if ! lsmod | grep -qs fglrx ; then
            sleep 4
            NOREPORTS=1 el_error "Unable to load FGLRX module"

            message_unable_to_load="$( printf "$( eval_gettext "Elive was unable to load the FGLRX module. The reasons may be that compilation has failed or the device is busy or not found. We suggest a reboot and selecting a different kernel version. If the video card is very old you may have better luck with an older version of Elive or kernel. Check our forums to find more help." )" "" )"
        fi


        if modprobe fglrx 2>&1 | grep -qs "No supported display adapters" ; then
            sleep 4
            message_unable_to_load="$( printf "$( eval_gettext "Error: The compiled drivers do not appear to support your graphics card model. Try other versions or consider using the open-source driver if that doesn't work." )" "" )"

        fi

        # module simply was not compiled
        if ! find "/lib/modules/$(uname -r)" -type f -iname '*'fglrx'*' | grep -qs "fglrx.ko" ; then
            sleep 4
            message_unable_to_load="$( printf "$( eval_gettext "Error: The driver did not compile successfully. This is typically due to using a too recent or too old kernel. Reboot and select a different kernel version from the boot menu. Also, consider trying the open-source driver as it might work." )" "" )"
        fi


        # show the message if we have any
        if [[ -n "$message_unable_to_load" ]] && ! ((is_mode_auto)) ; then
            dialog --timeout 280 --clear --colors --backtitle "Elive Systems: Use Ctrl-L to redraw, Enter to confirm" \
                --title "Unable to load module" \
                --msgbox "$message_unable_to_load" \
                0 0
        fi



        # cleanups
        if ! ((is_mode_force)) || ((is_mode_live)) ; then
            uninstall_driver
            NOREPORTS=1 el_warning "Switched to the default drivers option"
            sleep 4
            exit 1
        fi
    fi

    # reload devices just in case
    service fglrx-atieventsd restart 1>/dev/null 2>&1

    # - load module }}}
    # inform {{{
    if ! ((is_mode_auto)) ; then
        local message_remember
        message_remember="$( printf "$( eval_gettext "Remember, if you have issues trying to run the graphical system, or if you experience instability issues of any kind, it can be due to these drivers. Using the open-source drivers should solve the problem, or you might need the closed-source drivers; only your own experience will tell." )" "" )"

        dialog --timeout 80 --clear --colors --backtitle "Elive Systems: Use Ctrl-L to redraw, Enter to confirm" \
            --title "Ready to be run" \
            --msgbox "$message_remember" \
            0 0

        el_info "Install complete"
    fi
    # - inform }}}
}

#===  FUNCTION  ================================================================
#          NAME:  uninstall_driver
#   DESCRIPTION:  uninstalls any possible fglrx drivers and make the system work back on radeon
#    PARAMETERS:  -
#       RETURNS:  -
#===============================================================================
uninstall_driver(){
    # pre {{{
    local line
    el_debug

    unset _FGLRX_PACKAGES

    # }}}

    # unload module {{{
    # unload module first
    if lsmod | grep -qs radeon ; then
        rmmod radeon
        rmmod radeonhd

        if lsmod | grep -qs radeon ; then
            if ((is_mode_force)) ; then
                rmmod -f radeon
                rmmod -f radeonhd
            else
                el_info "E: unable to unload the 'radeon|radeonhd' module, if you are running the graphical system you should exit from it first, and if is not the case and you want to force to proceed use the -f option"
                exit 1
            fi
        fi
    fi


    # - unload module }}}
    # confs {{{
    # remove any possible xorg conf (before uninstall packages)
    rm -f /etc/X11/xorg.conf.d/20-fglrx.conf 2>/dev/null


    # - confs }}}
    # packages {{{
    # remove all fglrx packages
    while read -ru 3 line
    do
        [[ -z "$line" ]] && continue

        # if matches
        if echo "$line" | grep -qsE "(fglrx|lib.*fglrx|glx.*fglrx|xserver.*fglrx|xvba-va-driver)" ; then
    if ! ((is_ati_card_found)) ; then
        log_progress_msg "Removing FGLRX proprietary ATI drivers, this machine doesn't has it"
    fi

            # which doesn't maches
            if ! echo "$line" | grep -qsE "(fglrx-detect|glx-diversions|fglrx-installer-cleanup)" ; then
                el_debug "Adding $line to the list of uninstall packages"
                _FGLRX_PACKAGES="$_FGLRX_PACKAGES $line"
            fi
        fi

    done 3<<< "$( { echo "xvba-va-driver" ; COLUMNS=1000 dpkg -l | grep fglrx | awk '{print $2}' ; } )"

    # remove extra leading blank chars
    read -r _FGLRX_PACKAGES <<< "$_FGLRX_PACKAGES"

    if [[ -n "$_FGLRX_PACKAGES" ]] ; then
        log_progress_msg "Removing FGLRX proprietary ATI drivers, this machine doesn't has it"

        if ((is_mode_auto)) ; then
            el_debug "apt-get remove --purge -y $_FGLRX_PACKAGES"
            TERM=screen-256color DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical DEBCONF_NONINTERACTIVE_SEEN=true DEBCONF_NOWARNINGS=true apt-get remove --purge -y $_FGLRX_PACKAGES
        else
            el_debug "apt-get remove --purge $_FGLRX_PACKAGES"
            TERM=screen-256color DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical DEBCONF_NONINTERACTIVE_SEEN=true DEBCONF_NOWARNINGS=true apt-get remove --purge $_FGLRX_PACKAGES
        fi
    else
        el_info "FGLRX packages already removed"
    fi


    # - packages }}}
    # end {{{
    # show final result
    if COLUMNS=1000 dpkg -l | awk '{print $2}' | grep fglrx | grep -vE "(fglrx-detect|glx-diversions|fglrx-installer-cleanup)" | grep -qs fglrx ; then
        echo -e ""
        el_error "We still having some fglrx packages not uninstalled: $( COLUMNS=1000 dpkg -l | grep fglrx | awk '{print $2}' | grep fglrx  1>&2 )"
    else
        el_debug "Driver FGLRX uninstalled successfully"
    fi

    # - end }}}
}


main(){
    # pre {{{
    #if [[ -z "${1}" ]] ; then
    #usage
    #exit 1
    #fi

    . /lib/lsb/init-functions

    _CMDLINE="$(cat /proc/cmdline)"

    el_dependencies_check "dialog|apt-cache"

    if cat /etc/debian_version | grep -qsE "^(7|wheezy)" ; then
        is_wheezy=1
    fi

    # }}}

    # Usage
    while getopts ":acdifm:lquvht" opt; do
        case $opt in
            a)
                is_mode_auto=1
                ;;
            c)
                is_mode_check=1
                ;;
            d)
                is_mode_detect=1
                ;;
            f)
                is_mode_force=1
                ;;
            #i)
                #is_mode_interactive=1
                #unset is_mode_auto
                #;;
            v)
                export EL_DEBUG=2

                ;;
            m)
                driver_version="$OPTARG"
                is_mode_version_set=1
                ;;
            l)
                is_mode_live=1
                ;;
            q)
                export EL_DEBUG=0

                ;;
            u)
                is_mode_uninstall=1
                ;;
            t)
                is_mode_test_installed=1
                ;;
            h)
                usage
                exit
                ;;
            \?)
                el_error "Invalid option: -$OPTARG"
                usage
                exit 1
                ;;
            :)
                el_error "Option -$OPTARG requires an argument."
                usage
                exit 1
                ;;
        esac
    done

    if grep -qsE "simulate=(ati|fglrx)" /proc/cmdline ; then
        is_mode_force=1
    fi


    check_hardware

    if ((is_mode_uninstall)) ; then
        uninstall_driver
        # nothing more to do so exit
        exit
    fi

    if ((is_mode_version_set)) ; then
        # uninstall possible drivers first
        uninstall_driver
    fi

    # just check if installed and working
    if ((is_mode_test_installed)) ; then
        if check_driver ; then
            exit 0
        else
            exit 1
        fi
    fi

    # do not ask to install driver if is already and correctly installed (like in persistence mode)
    if check_driver ; then
        if ! ((is_mode_force)) ; then
            el_debug "driver already installed, use -f to force installation"
            exit
        fi
    fi

    interactive_ask_privative
    detect_driver_version
    interactive_ask_driver_version
    install_driver


}

#
#  MAIN
#
main "$@"

# vim: set foldmethod=marker :
