#!/bin/bash

# Copyright (c) 2010-2015, Sebastian Siebert (mail@sebastian-siebert.de)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
# 
# THIS SOFTWARE IS PROVIDED BY SEBASTIAN SIEBERT ''AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL SEBASTIAN SIEBERT BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# Changelog:

# Version 5.59 - update the packaging script for support up Kernel 4.3
#                and first support for openSUSE Leap 42.1
# Version 5.58 - add support for AMD Catalyst 15.9
#              - update the packaging script for support up Kernel 4.2
# Version 5.57 - update the packaging script for support up Kernel 4.2
# Version 5.56 - update the packaging script about GPL-incompatible pci_ignore_hotplug
# Version 5.55 - add support for AMD Catalyst 15.7
#              - update the packaging script for support up Kernel 4.1
# Version 5.54 - add support for AMD Catalyst 15.5
#              - update the packaging script for support up Kernel 4.1
# Version 5.53 - update the packaging script for support up Kernel 4.0
# Version 5.52 - add support for the newest beta driver from Ubuntu Repository
#              - update the packaging script
#              - add option to fix the issue of the fglrx driver with gdm
#                (look at the help page with option -h)
# Version 5.51 - fix URL redirect issue
# Version 5.50 - update the packaging script for support up Kernel 3.19
# Version 5.49 - add support for AMD Catalyst 14.12
#              - update the packaging script for support up Kernel 3.18 and
#                add support for openSUSE 13.2 and openSUSE Tumbleweed
# Version 5.48 - add support for openSUSE Tumbleweed
# Version 5.47 - hacking AMD Catalyst 14.9 with binary blob from Ubuntu Repository
#                for supporting openSUSE 13.2 with newer X-Server 1.16
#              - update the packaging script for support up Kernel 3.18 and
#                in terms of the new X-Server structure without update directory
# Version 5.46 - add support for AMD Catalyst 14.9
#              - update the packaging script for support up Kernel 3.17
# Version 5.45 - add support for AMD Catalyst 14.6 Beta V1.0
# Version 5.44 - add support for AMD Catalyst 14.4 rev. 2
# Version 5.43 - add support for AMD Catalyst 14.4
# Version 5.42 - add support for AMD Catalyst 14.3 beta V1.0
#              - update the packaging script for support up Kernel 3.14
# Version 5.41 - add support for AMD Catalyst 14.2 beta V1.3
# Version 5.40 - add support for AMD Catalyst 14.1 beta V1.3
# Version 5.39 - add support for AMD Catalyst 13.11 beta V9.95
#              - update the packaging script for support up Kernel 3.13
# Version 5.38 - update the SHA1 checksum of the zipped AMD Catalyst 13.12
# Version 5.37 - update the packaging script
#                - private Qt-libaries should not be provided (Thanks to Oliver Schmidt)
# Version 5.36 - add support for AMD Catalyst 13.12 (final driver)
#              - update the packaging script that fixed many bugs. Thx AMD for bugs.
#              - add support for Kernel 3.12 and Kernel 3.13
# Version 5.35 - add support for AMD Catalyst 13.11 beta V9.4 (public beta driver)
# Version 5.34 - add support for AMD Catalyst 13.11 beta V6 (public beta driver)
#                - update packaging script to fix several issues:
#                  - Compiling error on kernel 3.12
#                  - Symlink to 32-bit OpenGL libraries was broken on 64-bit system
# Version 5.33 - add support for AMD Catalyst 13.11 beta V1 (public beta driver)
# Version 5.32 - add support for AMD Catalyst 13.10 beta 2 (public beta driver)
#              - fixed autodetection with openSUSE 13.1
# Version 5.31 - add support for AMD Catalyst 13.8 beta 2 (public beta driver)
# Version 5.30 - update packaging script for compiling error with renamed
#                efi_enabled variable on openSUSE 12.2
# Version 5.29 - update packaging script to detect the correct openSUSE version
#                - add openSUSE 13.1
# Version 5.28 - add support for AMD Catalyst 13.8 beta 1 (public beta driver)
#                - fixed termporarily uki access error
#                - remove the beta watermark
# Version 5.27 - reintegrate the patch for kernel >= 3.10 (Patch from kolasa (GitHub)
#                special thanks to Paolo Marzari, who has pointed to the patch
# Version 5.26 - update the packaging script
#                - this fixed compiling error by missing declaration and functions
#                  for Kernel >= 3.10
# Version 5.25 - update the packaging script
#                - this fixed the symlink error in the switchlibGL script
# Version 5.24 - add support for AMD Catalyst 13.4
# Version 5.23 - update the sha1 checksum of the AMD installer (again)
# Version 5.22 - update the sha1 checksum of the AMD installer
# Version 5.21 - fixed openSUSE detection about required rpm-build package
#                on openSUSE 12.3
# Versino 5.20 - add support for AMD Catalyst 13.1 + update the packaging script
# Version 5.19 - update packaging script for Kernel 3.7.0 support
# Versino 5.18 - add option --kernel for selected kernel devel package as
#                required or set none for no requirements of kernel devel packages
# Version 5.17 - add support for AMD Catalyst 12.10
# Version 5.16 - update packaging script because remove unneeded patch
# Version 5.15 - add support for AMD Catalyst 12.8 + update the packaging script
#                for additional Kernel 3.5.0 support
# Version 5.14 - update the packaging script for Kernel 3.5.0 support
# Version 5.13 - fixed needed rpm-build package for openSUSE 12.2
# Version 5.12 - add support for AMD Catalyst 12.6 + update the packaging script
# Version 5.11 - renew the patch in the packaging script for i586 and i586 PAE
# Version 5.10 - renew the patch in the packaging script (see 5.8 + 5.9)
# Version 5.9  - update the packaging script to prevents module loading error:
#                fglrx: Unknown symbol old_rsp (err 0)
# Version 5.8  - update the packaging script to prevents Kernel 3.4.0 build issue.
# Version 5.7  - update the download url to the driver (CDN is disabled now)
# Version 5.6  - add support for AMD Catalyst 12.4
# Version 5.5  - fixed an issue with a mess of kernel versions. zypper and the
#                Kernel RPM spec are responsible for this behaviour.
# Version 5.4  - add support for AMD Catalyst 12.3
#                - add updated packaging script
# Version 5.3  - update packaging script
#                - add a patch for has_fpu build issue (kernel 3.3+)
# Version 5.2  - update packaging script
#                - add a patch for TS_USEDFPU build issue (kernel 3.2.8+)
# Version 5.1  - add support for AMD Catalyst 12.2
#              - update packaging script
# Version 5.0  - rename ATI Catalyst to AMD Catalyst (change name of variables)
#              - add support for AMD Catalyst 12.1
#              - add more system information to the system and diagnostic report
#              - update packaging script:
#                - support autodetection for Balsam Professional
# Version 4.26 - add support for AMD Catalyst 11.12
#              - if you want to upload a system report via ./makerpm-ati... -ur
#                the script asks you to see the system report before upload.
#                After that you should confirm to send the system report
#                to sprunge.to otherwise the upload is canceled. (thanks to Stefan)
# Version 4.25 - add support for AMD Catalyst 11.11 + update for packaging script
# Version 4.24 - add support for AMD Catalyst 11.10
# Version 4.23 - add support for AMD Catalyst 11.9
# Version 4.22 - add support for AMD Catalyst 11.8 + update for packaging script
#                add a patch to build package only in an vm build server and
#                disable the hardware detection (-nohw or --no-hardware-detect)
#                (Thanks for the patch, Bruno Friedmann alias tigerfoot)
# Version 4.21 - add support for ATI Catalyst 11.7
#              - remove the support of openSUSE 11.2
# Version 4.20 - fixed new sha1 checksum for ati installer (thanks to Ronny)
#              - collect more information for ati report:
#                - current symlink of libGL and libglx
#                - package version of KDE, GNOME, X-Server, Mesa
#                - overview of repositories (zypper lr -d)
# Version 4.19 - fixed detecting graphics card (thanks to elhennig, Kalle and Klaus)
#              - fixed new sha1 checksum for ati installer (thanks to Paul)
# Version 4.18 - add support for ATI Catalyst 11.6
# Version 4.17 - fixed new sha1 checksum for ati installer
# Version 4.16 - update packaging script:
#                - add a patch for Kernel 2.6.39
#                - fix fglrx version numbering in ati-packager.sh script to
#                  solve an issue with package manager
# Version 4.15 - fix a little bug about wrong temporary directory
#                (thanks to Carl-Christian)
# Version 4.14 - add support for ATI Catalyst 11.5 + update for packaging script
# Version 4.13 - add support for ATI Catalyst 11.4
# Version 4.12 - fix handling with spaces in the name of directory (cut issue)
#                (second time thanks to Dennis) ;-)
# Version 4.11 - fix handling with spaces in the name of directory
#                (thanks to Dennis)
# Version 4.10 - add support for ATI Catalyst 11.3
#              - fix installation with spaces in the name of directory
# Version 4.9  - fix an issue in the consoles with another background color
#                (thanks to Obi-Wahn)
# Version 4.8  - add /var/log/Xorg.0.log.old to log file
# Version 4.7  - add support for ATI Catalyst 11.2
# Version 4.6  - add support for ATI Catalyst 11.1
#              - add activating init rebuild script after update
# Version 4.5  - fixed new checksum of ATI Installer 10.12
# Version 4.4  - fixed new sha1 for ati-packaging-script.tar.bz2 because
#                add two aticonfig commands to remove keys as follows:
#                - LDC/ReleaseVersion
#                - LDC/Catalyst_Version
# Version 4.3  - fixed new sha1 for ati-packaging-script.tar.bz2 because
#                improve speed up the compilation on multi-core machines
#              - add verbose modus for zypper
# Version 4.2  - fixed new sha1 for ati-packaging-script.tar.bz2 because
#                there is a new patch available (compat_alloc_user_space issue)
# Version 4.1  - fixed exit issue in fglrx-kernel-build.sh (thanks to Franz)
#              - add a patch for fglrx kernel module to fix the build under
#                >= Kernel 2.6.36
# Version 4.0  - add support for ATI Catalyst 10.12
#              - replace packaging script by me
#              - remove rebuild script because a newer script will be installed
#              - remove checking of development tools
#              - remove openSUSE auto detection because the packaging script
#                supports it already.
# Version 3.11 - add support for ATI Catalyst 10.11
# Version 3.10 - the rebuild script fglrxrebuild.sh must not be downloaded
#              - before the fglrx driver removed, it is necessary to run
#                the system in runlevel 3. Check the right runlevel on the
#                script-sided now.
#              - if uninstall the fglrx driver, it displays a message that
#                the rebuild script was also removed
# Version 3.9  - fixed new checksum of ATI Installer 10.10 (thanks to Conax)
# Version 3.8  - add support for ATI Catalyst 10.10
#              - clean up the script
# Version 3.7  - update ATI file list
#              - add to remove the atieventsd service before remove all
#                available ATI files (thanks to Nino)
# Version 3.6  - add a fglrx rebuild script to boot time. This will create a new
#                fglrx kernel module, if a new kernel is installed. (If you want
#                to use this feature, run the script with the option "-irs")
#              - the patch is applied for all supported openSUSE 11.x
# Version 3.5  - add a patch for fglrx kernel module to fix the build under
#                openSUSE 11.3 - Kernel 2.6.34.7 (64-bit)
# Version 3.4  - add support for ATI Catalyst 10.9
#                add installed kernel rpm to the report file "ati-report.txt"
# Version 3.3  - add option --uninstall to remove ATI Catalyst and clean up
#                completely all possible ATI files and directories
#              - clean up the script
# Version 3.2  - add support for ATI Catalyst 10.8
#              - add option --report to generate a report file "ati-report.txt"
#              - add to check installed package like kernel-syms
#              - if the fglrx package is already installed, you can install over
#                it or rebuild the fglrx kernel module.
#                (thanks to Martin Meyer for the idea)
#              - clean up the script
# Version 3.1  - fixed other graphics card in the first place
# Version 3.0  - add support for ATI Catalyst 10.7
# Version 3.0 Beta2
#              - fixed changing to current directory to install/update the
#               fglrx-RPM (thanks to Manfred)
#              - add options -kms {yes,no}, -old2ddriver {yes,no}
# Version 3.0 Beta
#              - add support for openSUSE 11.3
#              - add a patch to build a Xorg 7.5 package
#              - add a patch to fixed missing include in the source of fglrx
# Version 2.9  - add support for ATI Catalyst 10.6
# Version 2.8  - add support for ATI Catalyst 10.5
# Version 2.7  - fixed new checksum of ATI Installer 10.4 (thanks to akI)
# Version 2.6  - add support for ATI Catalyst 10.4
# Version 2.5  - add check for supported graphics card
# Version 2.4  - add support for ATI Catalyst 10.3
#              - add support for installation of the patched X-Server
#                because of fglrx screen depth issue
#              - clean up the script
# Version 2.3  - add option --xinerama=on to aticonfig for dual-modus
# Version 2.2  - add support for ATI Catalyst 10.2
# Version 2.1  - fix configure only
# Version 2.0  - add support for ATI Catalyst 10.1
#              - add options (-b,-c,-d,-i,-h,-V)
#              - add download the ATI Installer
#              - add configure automatically the X-Server (sax2,aticonfig)
#              - add install or update automatically the RPM-package
#              - improve execution speed
#              - more robustness
# Version 1.1  - add tool "patch" for the ATI-Installation (thanks to Matthias)
# Version 1.0  - inital development

# Webpage:
# http://www.sebastian-siebert.de/2015/06/15/opensuse-proprietaeren-grafik-treiber-amd-catalyst-15-5-als-rpm-installieren/

AMDVERSION="15.9"
ZIPFILE="amd-catalyst-15.9-linux-installer-15.201.1151-x86.x86_64.zip"
ZIPFILESHA1="1372e80be26f7f537ca555a084d7799eed4aefee"
#AMDINSTALLER="amd-driver-installer-14.10.1006-x86.x86_64.run"
AMDINSTALLERSHA1="635302d40abf38736c92ef655fc484c499a30218"
AMDDOWNLOADURL="http://www2.ati.com/drivers/linux/${ZIPFILE}"
SCRIPTVERSION="5.59"
XORGCONF="/etc/X11/xorg.conf"
PACKAGERELEASE="2"
PACKAGINGSCRIPT="https://www.sebastian-siebert.de/downloads/amd-${AMDVERSION}-packaging-script.tar.bz2"
PACKAGINGSCRIPTSHA1="118b4daf9025aeb2f4c94413ac21d9a48384b65b"
PACKAGINGSCRIPTENABLE="yes"
PACKAGINGVERSION="15.201.1151"
AMDREPACKING="fglrx-installer_15.200.orig.tar.gz"
AMDREPACKINGURL="https://launchpad.net/ubuntu/+archive/primary/+files/${AMDREPACKING}"
AMDREPACKINGSHA1="723fa01252b03e4649513db37ed3955af9d84114"
AMDREPACKINGVERSION="15.20.1013"
AMDREPACKINGENABLE="no"

function OutputUsage() {
    echo "Usage : $(basename $0) [options...]"
    echo "Options:"
    echo "  -b/--build                    build only the RPM-Package (default)"
    echo "  -c/--configure <type>         configure only the X-Server."
    echo "                                (IMPORTANT: Use it only if you have problem with the default configuration of X-Server)"
    echo "                                Follow monitor types are available:"
    echo "                                  single = configure X-Server for single monitor."
    echo "                                  dual   = configure X-Server for dual monitors."
    echo "  -d/--downloadonly             download only the AMD-Installer"
    echo "  -i/--install                  build and install/update the RPM-Package"
    echo "  -igf/--install-gdm-fix        install a fix for the gdm issue with fglrx driver"
    echo "  -k/--kernel <kernel-flavor>   define explicitly the needed Kernel flavor devel package(s)."
    echo "                                Following values are available (Default: syms): default, desktop, pae, xen, syms, none"
    echo "                                Important note: The values <syms> and <none> is only a exclusive value."
    echo "                                Example parameter: --kernel default,desktop"
    echo "  -/--kms <yes|no>              enable or disable Kernel-Mode-Setting"
    echo "  -nohw/--no-hardware-detect    Don't count on hardware detection (vm building)"
    echo "  -/--old2ddriver <yes|no>      enable or disable the older 2D-Driver"
    echo "  -r/--report                   generate a report from this system"
    echo "  -u/--uninstall                remove AMD Catalyst and clean up completely all possible AMD files and directories"
    echo "  -ugf/--uninstall-gdm-fix      uninstall a fix for the gdm issue with fglrx driver"
    echo "  -ur/--uploadreport            same as --report, additionally the report will be uploaded to sprunge.us"
    echo "  -h/--help                     this help text"
    echo "  -V/--version                  show version number"

    exit 1
}

# set default configuration
BUILDONLY="true"
MONITORTYPE=""
DOWNLOADONLY="false"
INSTALL="false"
UNINSTALL="false"
KERNEL=""
KMS=""
OLD2DDRIVER=""
REPORT="false"
UPLOADREPORT="false"
VM="no"
ERROROPTION=""
FACTORY=""
INSTALLFIXGDMISSUE="false"
UNINSTALLFIXGDMISSUE="false"

if [ $# -ne 0 ]; then
    BUILDONLY="false"
fi

check_invalid_options() {
    # $1 = option
    if [ "${BUILDONLY}" = "true" -a "buildonly" != "$1" -a "kernel" != "$1" ]; then
        ERROROPTION="--buildonly"
    elif [ "${DOWNLOADONLY}" = "true" -a "downloadonly" != "$1" ]; then
        ERROROPTION="--downloadonly"
    elif [ "${INSTALL}" = "true" -a "install" != "$1" -a "kernel" != "$1" ]; then
        ERROROPTION="--install"
    elif [ "${UNINSTALL}" = "true" -a "uninstall" != "$1" ]; then
        ERROROPTION="--uninstall"
    elif [ -n "${MONITORTYPE}" -a "configure" != "$1" ]; then
        ERROROPTION="--configure"
    elif [ -n "${KMS}" -a "kms" != "$1" ]; then
        ERROROPTION="--kms"
    elif [ -n "${OLD2DDRIVER}" -a "old2ddriver" != "$1" ]; then
        ERROROPTION="--old2ddriver"
    elif [ "${REPORT}" = "true" -a "report" != "$1" ]; then
        ERROROPTION="--report"
    elif [ "${UPLOADREPORT}" = "true" -a "uploadreport" != "$1" ]; then
        ERROROPTION="--uploadreport"
    fi

    if [ -n "${ERROROPTION}" ]; then
        echo "Error: Option \"--$1\" can not use with \"${ERROROPTION}\""
        exit 1;
    fi
}

while [ "$#" -gt "0" ]; do
    case $1 in
        -b|--buildonly)
            check_invalid_options "buildonly"
            BUILDONLY="true"
            echo "only build"
            shift 1
        ;;
        -c|--configure)
            check_invalid_options "configure"
            if [ "$2" != "single" -a "$2" != "dual" ]; then
                echo "Error: Value \"$2\" is unknown. Please set only \"single\" or \"dual\"."
                exit 1
            fi
            MONITORTYPE="$2"
            echo -e "configure with \"${MONITORTYPE}\""
            shift 2
        ;;
        -d|--downloadonly)
            check_invalid_options "downloadonly"
            DOWNLOADONLY="true"
            echo "only download"
            shift 1
        ;;
        -f|--factory)
            FACTORY="true"
            BUILDONLY="true"
            echo "Factory build is enabled"
            shift 1
        ;;
        -i|--install)
            if [ "${KERNEL}" != "false" -a "${BUILDONLY}" = "true" -a "${INSTALL}" = "false" ]; then
                BUILDONLY="false"
            elif [ "${FACTORY}" != "false" -a "${BUILDONLY}" = "true" -a "${INSTALL}" = "false" ]; then
                BUILDONLY="false"
            fi
            check_invalid_options "install"
            INSTALL="true"
            echo "build and install"
            shift 1
        ;;
        -igf|--install-gdm-fix)
            INSTALLFIXGDMISSUE="true"
            shift 1
        ;;
        -k|--kernel)
            check_invalid_options "kernel"
            if [ -z "$2" ]; then
                echo "Error: No kernel flavor value has been set"
                break
            fi
            IFS_BACKUP=${IFS}
            IFS=","
            KERNEL_DEVEL=""
            for KERNEL_SELECTION in $2
            do
                if [ "${KERNEL_SELECTION}" = "default" ]; then
                    if [ "${KERNEL}" = "syms" -o "${KERNEL}" = "none" ]; then
                        echo "Error: Exclusive value \"${KERNEL}\" has been set and can not used with \"${KERNEL_SELECTION}\". See the help with -h option."
                        exit
                    fi
                    echo "Kernel devel package \"default\" is enabled"
                    KERNEL_DEVEL="${KERNEL_DEVEL} kernel-default kernel-default-devel"
                    KERNEL="true"
                elif [ "${KERNEL_SELECTION}" = "desktop" ]; then
                    if [ "${KERNEL}" = "syms" -o "${KERNEL}" = "none" ]; then
                        echo "Error: Exclusive value \"${KERNEL}\" has been set and can not used with \"${KERNEL_SELECTION}\". See the help with -h option."
                        exit
                    fi
                    echo "Kernel devel package \"desktop\" is enabled"
                    KERNEL_DEVEL="${KERNEL_DEVEL} kernel-desktop kernel-desktop-devel"
                    KERNEL="true"
                elif [ "${KERNEL_SELECTION}" = "pae" ]; then
                    if [ "${KERNEL}" = "syms" -o "${KERNEL}" = "none" ]; then
                        echo "Error: Exclusive value \"${KERNEL}\" has been set and can not used with \"${KERNEL_SELECTION}\". See the help with -h option."
                        exit
                    fi
                    echo "Kernel devel package \"pae\" is enabled"
                    KERNEL_DEVEL="${KERNEL_DEVEL} kernel-pae kernel-pae-devel"
                    KERNEL="true"
                elif [ "${KERNEL_SELECTION}" = "xen" ]; then
                    if [ "${KERNEL}" = "syms" -o "${KERNEL}" = "none" ]; then
                        echo "Error: Exclusive value \"${KERNEL}\" has been set and can not used with \"${KERNEL_SELECTION}\". See the help with -h option."
                        exit
                    fi
                    echo "Kernel devel package \"xen\" is enabled"
                    KERNEL_DEVEL="${KERNEL_DEVEL} kernel-xen kernel-xen-devel"
                    KERNEL="true"
                elif [ "${KERNEL_SELECTION}" = "syms" ]; then
                    if [ -n "${KERNEL_DEVEL}" -o "${KERNEL}" = "none" ]; then
                        echo "Error: Value \"syms\" is only a exclusive value. See the help with -h option."
                        exit
                    fi
                    echo "Default Kernel devel packages is enabled"
                    KERNEL_DEVEL=""
                    KERNEL="syms"
                elif [ "${KERNEL_SELECTION}" = "none" ]; then
                    if [ -n "${KERNEL_DEVEL}" -o "${KERNEL}" = "syms" ]; then
                        echo "Error: Value \"none\" is only a exclusive value. See the help with -h option."
                        exit
                    fi
                    echo "Requirement of Kernel devel packages is disabled"
                    KERNEL_DEVEL=""
                    KERNEL="none"
                else
                    echo "Error: Value \"${KERNEL_SELECTION}\" is unknown. See the help with -h option."
                    exit
                fi
            done
            IFS=${IFS_BACKUP}
            if [ -n "${KERNEL_DEVEL}" ]; then
                KERNEL_DEVEL="kernel-devel kernel-source ${KERNEL_DEVEL}"
            fi
            if [ "${KERNEL}" != "false" -a "${BUILDONLY}" = "false" -a "${INSTALL}" = "false" ]; then
                BUILDONLY="true"
            fi
            shift 2
        ;;
        -kms|--kms)
            check_invalid_options "kms"
            if [ "$2" != "yes" -a "$2" != "no" ]; then
                echo "Error: Value \"$2\" is unknown. Please set only \"yes\" or \"no\"."
                exit 1
            fi
            KMS="$2"
            shift 2
        ;;
        -nohw|--no-hardware-check)
            echo "Building package in VM disable hardware check"
            if [ "${INSTALL}" = "false" -a "${BUILDONLY}" = "false" ]; then
                BUILDONLY="true"
            fi
            VM="yes"
            shift 1
        ;;
        -old2ddriver|--old2ddriver)
            check_invalid_options "old2ddriver"
            if [ "$2" != "yes" -a "$2" != "no" ]; then
                echo "Error: Value \"$2\" is unknown. Please set only \"yes\" or \"no\"."
                exit 1
            fi
            OLD2DDRIVER="$2"
            shift 2
        ;;
        -r|--report)
            check_invalid_options "report"
            REPORT="true"
            shift 1
        ;;
        -u|--uninstall)
            check_invalid_options "uninstall"
            UNINSTALL="true"
            shift 1
        ;;
        -ugf|--uninstall-gdm-fix)
            UNINSTALLFIXGDMISSUE="true"
            shift 1
        ;;
        -ur|--uploadreport)
            check_invalid_options "uploadreport"
            REPORT="true"
            UPLOADREPORT="true"
            shift 1
        ;;
        -h|--help)
            OutputUsage
            exit 0
        ;;
        -V|--version)
            echo -e "$(basename $0) - Version ${SCRIPTVERSION}\n"
            echo "Copyright (c) 2010-`date +'%Y'`, Sebastian Siebert (mail@sebastian-siebert.de)"
            echo "All rights reserved."
            echo "This script is under the modified BSD License (2-clause license)"
            exit 0
        ;;
        -*|--*)
            echo "Error: Option \"$1\" is unknown"
            echo "try '$(basename $0) -h' or '$(basename $0) --help' for more information"
            exit 1
        ;;
     esac
done

# Check the size of the console
set -- $(stty size 2> /dev/null || echo 0 0)
LINES=$1
COLUMNS=$2
if [ ${LINES} -eq 0 ]; then
    LINES=24
fi
if [ ${COLUMNS} -eq 0 ]; then
    COLUMNS=80
fi

print_okay() {
    echo -e "\033[${COLUMNS}C\033[15D[\e[1;32m OK \e[0m]"
}
print_failure() {
    echo -e "\033[${COLUMNS}C\033[15D[\e[1;31m FAILURE \e[0m]"
}
print_missing() {
    echo -e "\033[${COLUMNS}C\033[15D[\e[1;33m MISSING \e[0m]"
}
print_aborted() {
    echo -e "\033[${COLUMNS}C\033[15D[\e[1;33m ABORTED \e[0m]"
}
print_fixed() {
    echo -e "\033[${COLUMNS}C\033[15D[\e[1;33m FIXED \e[0m]"
}

print_pkg_available() {
    echo -e "[\e[1;32m AVAILABLE \e[0m]"
}
print_pkg_missing() {
    echo -e "[\e[1;31m MISSING \e[0m]"
}

check_install() {
    PROGRAM=$1
    echo -n -e "   check ${PROGRAM} ... "
    rpm -q "${PROGRAM}" >/dev/null
    if [ $? -eq 0 ]; then
        print_pkg_available
    else
        print_pkg_missing
        echo -n -e "\n   missing \"${PROGRAM}\"-package: try to run \"zypper install ${PROGRAM}\" now\n"
        zypper -v -n in ${PROGRAM}
        if [ $? -ne 0 ]; then
            echo -n "   Error: zypper could not install the package \"${PROGRAM}\" ..."
            print_failure
            exit 1
        fi
    fi
}

box_full() {
    printf '*%.0s' $(seq 1 67)
    echo ""
}

box_content() {
    echo -n "*"
    if [ $# -eq 0 ]; then
        printf ' %.0s' $(seq 1 65)
    elif [ $# -eq 1 ]; then
        RIGHT="$1"
        printf ' %.0s' $(seq 1 17)
        echo -n "${RIGHT}"
        printf ' %.0s' $(seq 1 $[48-${#RIGHT}])
    elif [ $# -eq 2 ]; then
        LEFT="$1"
        RIGHT="$2"
        printf ' %.0s' $(seq 1 3)
        echo -n "${LEFT}"
        printf ' %.0s' $(seq 1 $[14-${#LEFT}])
        echo -n "${RIGHT}"
        printf ' %.0s' $(seq 1 $[48-${#RIGHT}])
    fi
    echo "*"
}

box_full
box_content
box_content "Script:" "$(basename $0)"
box_content "Version:" "${SCRIPTVERSION}"
box_content "Written by:" "Sebastian Siebert (mail@sebastian-siebert.de)"
box_content
box_content "Description:" "This script helps you to create a rpm package"
box_content "from the proprietary AMD installer"
box_content
box_content "License:" "This script is under the"
box_content "modified BSD License (2-clause license)"
box_content
box_full

echo -n "Check for running this script as root ..."
if [ "$(whoami)" != "root" ]; then
    echo -n -e "\n   Error: This script needs to run as root!"
    print_failure
    exit 1
fi
print_okay

if [ "${INSTALLFIXGDMISSUE}" = "true" ]; then
#    if [ "$(uname -m)" = "i686" ]; then
#        fglrx_drv_file=/usr/lib/xorg/modules/drivers/fglrx_drv.so
#        libglx_file=/usr/lib/xorg/modules/extensions/fglrx/fglrx-libglx.so
#    fi
#    if [ "$(uname -m)" = "x86_64" ]; then
#        fglrx_drv_file=/usr/lib64/xorg/modules/drivers/fglrx_drv.so
#        libglx_file=/usr/lib64/xorg/modules/extensions/fglrx/fglrx-libglx.so
#    fi
#
#    fglrx_drv_offset=`strings -td ${fglrx_drv_file} | grep '/proc/%i/fd/0' | sed 's/^ *//' | cut -d' ' -f1`
#    libglx_offset=`strings -td ${libglx_file} | grep '/proc/%i/fd/0' | sed 's/^ *//' | cut -d' ' -f1`
#
#    if [ -n "${fglrx_drv_offset}" -a -n "${libglx_offset}" ]; then
#        echo "Modify the fglrx driver to fix the gdm issue ..."
#        Xorg -version > /amd_xversion 2>&1
#        echo -ne '/amd_xversion' | dd conv=notrunc of=${fglrx_drv_file} bs=1 count=13 seek=${fglrx_drv_offset}
#        echo -ne '/amd_xversion' | dd conv=notrunc of=${libglx_file} bs=1 count=13 seek=${libglx_offset}
#
#        fglrx_gdm_fix_profile="/etc/profile.d/fglrx_gdm_fix.sh"
#        echo "#" > ${fglrx_gdm_fix_profile}
#        echo "# Fix an issue with gdm and AMD Catalyst Driver" >> ${fglrx_gdm_fix_profile}
#        echo "#" >> ${fglrx_gdm_fix_profile}
#        echo "" >> ${fglrx_gdm_fix_profile}
#        echo ". /etc/sysconfig/displaymanager" >> ${fglrx_gdm_fix_profile}
#        echo "" >> ${fglrx_gdm_fix_profile}
#        echo "if [ \"\${DISPLAYMANAGER}\" = \"gdm\" ]; then" >> ${fglrx_gdm_fix_profile}
#        echo "" >> ${fglrx_gdm_fix_profile}
#        echo "  export COGL_DRIVER=gl" >> ${fglrx_gdm_fix_profile}
#        echo "  export COGL_OVERRIDE_GL_VERSION=1.4" >> ${fglrx_gdm_fix_profile}
#        echo "  export COGL_RENDERER=GLX" >> ${fglrx_gdm_fix_profile}
#        echo "" >> ${fglrx_gdm_fix_profile}
#        echo "fi" >> ${fglrx_gdm_fix_profile}
#        print_okay
#    else
#        echo -n "fglrx driver is already modified, nothing to do."
#        print_aborted
#    fi

    echo "Modify the permission for /usr/bin/X to fix the gdm issue ..."
    chmod ug+s /usr/bin/X >/dev/null
    if [ $? -ne 0 ]; then
        print_failure
        exit 1
    fi
    print_okay
    exit 0
fi

if [ "${UNINSTALLFIXGDMISSUE}" = "true" ]; then
#    if [ "$(uname -m)" = "i686" ]; then
#        fglrx_drv_file=/usr/lib/xorg/modules/drivers/fglrx_drv.so
#        libglx_file=/usr/lib/xorg/modules/extensions/fglrx/fglrx-libglx.so
#    fi
#    if [ "$(uname -m)" = "x86_64" ]; then
#        fglrx_drv_file=/usr/lib64/xorg/modules/drivers/fglrx_drv.so
#        libglx_file=/usr/lib64/xorg/modules/extensions/fglrx/fglrx-libglx.so
#    fi
#
#    fglrx_drv_offset=`strings -td ${fglrx_drv_file} | grep '/amd_xversion' | sed 's/^ *//' | cut -d' ' -f1`
#    libglx_offset=`strings -td ${libglx_file} | grep '/amd_xversion' | sed 's/^ *//' | cut -d' ' -f1`
#
#    if [ -n "${fglrx_drv_offset}" -a -n "${libglx_offset}" ]; then
#        echo "Revert the modification on the fglrx driver ..."
#        rm -f /amd_xversion
#        rm /etc/profile.d/fglrx_gdm_fix.sh
#        echo -ne '/proc/%i/fd/0' | dd conv=notrunc of=${fglrx_drv_file} bs=1 count=13 seek=${fglrx_drv_offset}
#        echo -ne '/proc/%i/fd/0' | dd conv=notrunc of=${libglx_file} bs=1 count=13 seek=${libglx_offset}
#        print_okay
#    else
#        echo -n "Modification of fglrx driver is already reverted, nothing to do."
#        print_aborted
#    fi

    echo "Revert the permission for /usr/bin/X ..."
    chmod ug-s /usr/bin/X >/dev/null
    if [ $? -ne 0 ]; then
        print_failure
        exit 1
    fi
    print_okay
    exit 0
fi

if [ -n "${MONITORTYPE}" ]; then
    echo "Check for correct runlevel to configure X-Server ..."
    RUNLEVEL="`runlevel|cut -f2 -d' '`"
    echo -n "   Current runlevel: ${RUNLEVEL}"
    if [ ${RUNLEVEL} -eq 5 ]; then
        echo -n -e "\n   Error: The system is in wrong runlevel. Please switch to runlevel 3."
        print_failure
        exit 1
    fi
    print_okay

    echo -n "Check for loaded fglrx kernel module ..."
    MODULELOADED="`lsmod | grep fglrx`"
    if [ -z "${MODULELOADED}" ]; then
        echo -n -e "\n   Error: The kernel module \"fglrx\" does not loaded ..."
        print_failure
        echo "   Try to probe the fglrx module ..."
        modprobe --first-time fglrx
        if [ $? -ne 0 ]; then
            print_failure
            exit 1
        fi
    fi
    print_okay

    echo "Check for existing configuration file ${XORGCONF} and back it up ..."
    if [ -f ${XORGCONF} ]; then
        for ITERATION in $(seq 1 255)
        do
            BACKUPFILE="${XORGCONF}.old.${ITERATION}"
            if [ ! -f ${BACKUPFILE} ]; then
                echo -n "Move ${XORGCONF} to ${BACKUPFILE} ..."
                mv ${XORGCONF} ${BACKUPFILE}
                if [ $? -ne 0 ]; then
                    print_failure
                    exit 1
                fi
                break
            fi
        done
    fi
    print_okay

    echo "Run aticonfig to modified configuration file ${XORGCONF} for fglrx driver in \"${MONITORTYPE}\" mode ..."
    if [ "${MONITORTYPE}" = "single" ]; then
        aticonfig --initial --input=${XORGCONF}
        if [ $? -ne 0 ]; then
            print_failure
            exit 1
        fi
    elif [ "${MONITORTYPE}" = "dual" ]; then
        aticonfig --initial=dual-head --xinerama=on --input=${XORGCONF}
        if [ $? -ne 0 ]; then
            print_failure
            exit 1
        fi
    fi
    print_okay
    exit 0
fi

if [ -n "${KMS}" ]; then
    echo -n "Set /etc/sysconfig/kernel the KMS configuration: NO_KMS_IN_INITRD=\"${KMS}\" ..."
    if [ "${KMS}" = "yes" ]; then
        sed -i 's/^NO_KMS_IN_INITRD.*/NO_KMS_IN_INITRD="no"/g' /etc/sysconfig/kernel
        # openSUSE 12.1 has a new KMS variable
        sed -i 's/^KMS_IN_INITRD.*/KMS_IN_INITRD="yes"/g' /etc/sysconfig/kernel
    elif [ "${KMS}" = "no" ]; then
        sed -i 's/^NO_KMS_IN_INITRD.*/NO_KMS_IN_INITRD="yes"/g' /etc/sysconfig/kernel
        # openSUSE 12.1 has a new KMS variable
        sed -i 's/^KMS_IN_INITRD.*/KMS_IN_INITRD="no"/g' /etc/sysconfig/kernel
    fi
    print_okay

    echo "Create a new inital ramdisk ..."
    /sbin/mkinitrd
    if [ $? -ne 0 ]; then
        print_failure
        exit 1
    fi
    print_okay
    exit 0
fi

if [ -n "${OLD2DDRIVER}" ]; then
    if [ "${OLD2DDRIVER}" = "yes" ]; then
        echo "Enable the older 2D-Driver ..."
        aticonfig --set-pcs-str=DDX,ForceXAA,TRUE
    elif [ "${OLD2DDRIVER}" = "no" ]; then
        echo "Disable the older 2D-Driver ..."
        aticonfig --del-pcs=DDX,ForceXAA
    fi
    print_okay
    exit 0
fi

if [ "${REPORT}" = "true" ]; then

    REPORTFILE="amd-report.txt"

    echo "Generating a report file \"${REPORTFILE}\" in the directory `pwd` ..."

    if [ -f ${REPORTFILE} ]; then
        rm ${REPORTFILE}
    fi

    touch ${REPORTFILE}

report_header() {
    echo "------------------------------------------------" >>${REPORTFILE}
    echo "   System and diagnostic report" >>${REPORTFILE}
    echo "------------------------------------------------" >>${REPORTFILE}
    echo "   Generated by $(basename $0)" >>${REPORTFILE}
    echo "      on `date "+%Y-%m-%d %T"`" >>${REPORTFILE}
    echo "" >>${REPORTFILE}
    echo "   The script was written by Sebastian Siebert" >>${REPORTFILE}
    echo "   and is under the modified BSD License" >>${REPORTFILE}
    echo "   (2-clause license)" >>${REPORTFILE}
    echo "" >>${REPORTFILE}
    echo "   Website: http://www.sebastian-siebert.de" >>${REPORTFILE}
    echo "------------------------------------------------" >>${REPORTFILE}
    echo -n -e "\n\n\n" >>${REPORTFILE}
}

report_echo() {
    echo "   OUTPUT (echo): $1"
    echo "# OUTPUT (echo): $1" >>${REPORTFILE}
    shift 1
    echo "------------------------------------------------" >>${REPORTFILE}
    for ECHO_SINGLELINE in $@
    do
        echo ${ECHO_SINGLELINE} >>${REPORTFILE}
    done
    echo "================================================" >>${REPORTFILE}
    echo -n -e "\n\n\n" >>${REPORTFILE}
}

report_output() {
    echo "   OUTPUT: $@"
    echo "# OUTPUT: $@" >>${REPORTFILE}
    echo "------------------------------------------------" >>${REPORTFILE}
    eval "$@ 2>&1" >>${REPORTFILE}
    echo "================================================" >>${REPORTFILE}
    echo -n -e "\n\n\n" >>${REPORTFILE}
}

report_file() {
    echo "   FILE: $1"
    echo "# FILE:      $1" >>${REPORTFILE}
    echo "# ATTRIBUTE: `ls -l $1 2>/dev/null`" >>${REPORTFILE}
    echo "------------------------------------------------" >>${REPORTFILE}
    echo "`cat $1 2>&1`" >>${REPORTFILE}
    echo "================================================" >>${REPORTFILE}
    echo -n -e "\n\n\n" >>${REPORTFILE}
}

report_files() {
    REPORT_DIR="`ls $@`"
    for REPORT_DIR_FILE in ${REPORT_DIR}; do
        report_file ${REPORT_DIR_FILE}
    done
}

    report_header
    report_output "`which uname` -a"
    report_output "`which lsb_release` -a"
    report_file /proc/version
    report_output "`which gcc` --version"
    report_output "`which fglrxinfo`"
    report_output "`which ldd` `which fglrxinfo`"
    report_output "`which env`"
    report_file /proc/cpuinfo
    report_file /proc/meminfo
    report_output "`which lspci` -nn"
    report_file /proc/pci
    report_files /proc/ati/*/*
    report_files /etc/X11/xorg.conf.d/*
    report_file /etc/X11/xorg.conf
    report_files /var/log/Xorg.*.log
    report_files /var/log/Xorg.*.log.old
    report_output "`which dmesg`"
    report_output "`which lsmod` | `which grep` fglrx"
    report_output "`which lsmod`"
    report_file /etc/ati/amdpcsdb
    report_file /etc/ati/amdpcsdb.default
    report_output "`which hwinfo` --monitor"
    report_output "`which hwinfo` --gfxcard"
    if [ "`uname -m`" = "x86_64" ]; then
        report_output "/usr/lib64/fglrx/switchlibGL query"
        report_output "/usr/lib64/fglrx/switchlibglx query"
    else
        report_output "/usr/lib/fglrx/switchlibGL query"
        report_output "/usr/lib/fglrx/switchlibglx query"
    fi
    report_file /etc/ld.so.conf.d/fglrx.conf
    report_output "`which ldconfig` -p | `which grep` libGL.so"
    # save rpm list into temp otherwise we have a performance issue
    RPMLISTFILE=`mktemp --tmpdir=/tmp "amd-rpm-list.XXXXXX"`
    rpm -qa | sort >${RPMLISTFILE}
    report_echo "Package: fglrx" `grep -i fglrx ${RPMLISTFILE}`
    report_echo "Package: kernel" `grep -i kernel ${RPMLISTFILE}`
    report_echo "Package: libkde4" `grep -i libkde4 ${RPMLISTFILE}`
    report_echo "Package: libgnome" `grep -i libgnome ${RPMLISTFILE}`
    report_echo "Package: xorg-x11-server" `grep -i xorg-x11-server ${RPMLISTFILE}`
    report_echo "Package: Mesa" `grep -i Mesa ${RPMLISTFILE}`
    rm -f ${RPMLISTFILE}
    report_output "`which zypper` lr -d"
    report_file /boot/grub/menu.lst
    report_file /boot/grub2/grub.cfg
    report_file /etc/sysconfig/kernel
    report_files /home/*/.kde4/share/config/kwinrc

    echo -n -e "\nThe system report 'amd-report.txt' was generated."
    print_okay

    if [ "${UPLOADREPORT}" = "true" ]; then
        read -p "Do you want to read the system report 'amd-report.txt' now? yes/no [y/n]: " USERKEY

        if [ "${USERKEY}" = "y" -o "${USERKEY}" = "yes" ]; then
            less -e ${REPORTFILE}
        else
            echo "Skip the reading of the system report..."
        fi

        read -p "Are you sure to upload the above-named system report to sprunge.us? yes/no [y/n]: " USERKEY

        if [ "${USERKEY}" = "y" -o "${USERKEY}" = "yes" ]; then
            REPORTURL="`cat amd-report.txt | curl -F 'sprunge=<-' http://sprunge.us -s 2>&1`"
            echo -n -e "\n\nThe report was uploaded to sprunge.us.\n   The link is: ${REPORTURL}\n"
            print_okay
        else
            echo -n -e "\nThe system report file was not uploaded."
            print_aborted
        fi


#        REPORTFILECONTENT="`cat ${REPORTFILE}`"
#        REPORTUSER="openSUSE User"

#        REPORTURL="`curl -v -F "code=${REPORTFILECONTENT}" \
#                            -F "title=${REPORTFILE}" \
#                            -F "expire=30" \
#                            -F "name=${REPORTUSER}" \
#                            -F "submit=submit" \
#                            -F "lang=text" \
#                            http://susepaste.org 2>&1`"
#                            http://susepaste.org 2>&1 | sed -n 's/<\ Location:\ //p'`"
    fi

    exit 0
fi

if [ "${UNINSTALL}" = "true" ]; then
    echo "Check for correct runlevel to remove AMD Catalyst ${AMDVERSION} ..."
    RUNLEVEL="`runlevel|cut -f2 -d' '`"
    echo -n "   Current runlevel: ${RUNLEVEL}"
    if [ ${RUNLEVEL} -eq 5 ]; then
        echo -n -e "\n   Error: The system is in wrong runlevel. Please switch to runlevel 3."
        print_failure
        exit 1
    fi
    print_okay

    echo "Remove the AMD Catalyst from this system ..."
    FGLRX_PACKAGES="`rpm -qa | grep fglrx`"
    PACKAGE_COUNTER="$(echo ${FGLRX_PACKAGES} | wc -w)"
    if [ -n "${FGLRX_PACKAGES}" ]; then
        if [ "${PACKAGE_COUNTER}" -gt "1" ]; then
            echo "   Following packages will be removed:"
        else
            echo "   Following package will be removed:"
        fi
        for FGLRX_PACKAGE in ${FGLRX_PACKAGES}
        do
            rpm -q --qf "   =>   Name:         %{name}
        Summary:      %{summary}
        Version:      %{version}
        Release:      %{release}
        Architecture: %{arch}
        Size:         %{size} bytes
        Installed on: %{installtime:date}\n\n" ${FGLRX_PACKAGE}
        done

        if [ "${PACKAGE_COUNTER}" -gt "1" ]; then
            read -p "Are you sure to remove the above-named packages? yes/no [y/n]: " USERKEY
        else
            read -p "Are you sure to remove the above-named package? yes/no [y/n]: " USERKEY
        fi


        if [ "${USERKEY}" = "y" -o "${USERKEY}" = "yes" ]; then
            rpm -e ${FGLRX_PACKAGES}
            if [ $? -ne 0 ]; then
                print_failure
                exit 1
            fi

            if [ "${PACKAGE_COUNTER}" -gt "1" ]; then
                echo "The packages were removed successfully!"
            else
                echo "The package was removed successfully!"
            fi
            print_okay
        else
            print_aborted
            exit 0
        fi
    fi

    if [ -z "${USERKEY}" ]; then
        read -p "Are you sure to remove the AMD files and directories? yes/no [y/n]: " USERKEY
    fi

    if [ "${USERKEY}" = "y" -o "${USERKEY}" = "yes" ]; then
        echo "Try to remove the existing AMD files and directories manually ..."

        if [ -n "`chkconfig atieventsd 2>&1 | grep 'on'`" ]; then
            /sbin/insserv -r atieventsd
        fi

        # This is a file list from all available AMD files.
        # I have zipped it and encoded in base64 to get a smaller script code.
        AMD_FILELIST_GZIP_BASE64="H4sICMxOo0wAA2F0aWZpbGVzLnR4dAClmFt3GycQgN/zX8RKlqKqj47juD5xclpbPfEbBwFaUbFA
uMir/PrO7uruXS20D1YU5psZmBkBQ8Y9zYgXGSmYoY4tEONLEqT/kB0kXuhcorKQJ2PBr+BfvuHK
O4bc6iiiWnmrT1ipc40L4taoXBSIl6Qwkp+L2yVO5Ir4YHdDQgmPWHZ02wwXmhmrFxxEy1zaEsEE
lo0IxpdCVpJyNBpsBON6UDMPwxtE95O+Su0hx2mwwm+r5TkNNDHGVUGjlEo+cOFDJsWimkyQ3GU3
aIrGk8HoZrALZxYMIx4kzRzXupt3a69NNG8Ib2GDs9lCqMMEz0Ya3BLFbBUrkZ9JS5bXyzkMefGO
gopgVIqLkRMvMBOcyzLnxLqzUVsKtdQXQ4M1t4rLwSII2RTTmRiXOSkKchx9Re8z1UiFojIwnj08
Zbm8nT+iVct42SJ4HY0yXnqunIAE7/zWbvckhH86yZgVOyF8Q06fyuAT4kCYLMtWCSWSyi4JY10S
61slYV35RyM0PJWZYhC8kC4z+o3b5ucyqL9D6fBDbBu41DY/lFSV+qK4cHVGwIo33LrD+jfX4Bw+
LsNwBkihQlkJanPMXnW9r/CTFAEFqTxV6k5O9Xf77fPr5tMtosS0jl/EsiubXbnsymRXHruzeIgJ
ZgUi7cOdKk3Jtmk1khbFavU/3gniC+mIOsm5AXQ6fSNWCZU3v07YTpzhih01egovoex6ii6h5FIL
zu32S6W9WG6DOB09OaJOB3Pu3dZ5XlR74CGEbkUsz+A8kVAlvna137bR7jToBV1oRZtzvSYOXzB1
6GfRjzGCP3+NI3kUxiV+eI4jHb5/iSKXAn95jCMt/hLnfRXwH39HkcLjx3kU+Q+JwtYaf42bpJL4
+1McqaMwI+Mwjz/FzdAG/BwXRrfBL/dRpF/FYRbP4yb5a4XvvseS8x8t5OFI/svfacurfXRyhXkI
ogvpN9Jtgmm4xxK6Jvn+GpgRC6dOtZWN8sWKqBytfHWDj9OZTKajVIWbVIVxqsIkVeH3RIXfhqkK
H1MVZqkKqWuYpa5hlprpWWqmZ6mZnqVmepaWB6qtDcbDUWy5/i+aG+/ehKerJF3GN25VpKnkZMyS
f71M62K8m2maYiByxQmrW6skTUkMXD52F70kzUI4B1dFuI1VnuGil6atQ92aO22Tw6T0mA2IeJt9
HA7ZJl117SfDtB+b0gUvFhza7qDSMmOo4GMG2tpuJSfrJGU7uRkuJFFrJpyRZJumvLmZQXjE/zAw
/jh0xlZJJnCnTdGF3GrFqsLYlTPcepMMlMvZFHMFLUtagkvLnYf/VXFPU9w44t1KLKPyezt/xE+P
d/ff4QI0f5330M07TLBRM2rapiX5GQM3vZWrH+Cw08FSjnz+q0dLKMbLGPNCQTClhD4yBnYu8Khd
oO7nIlf4fH/7+ds9egkv9z2kF8YNatMxdmH7sYOCKNg5O+IBwupvdtIWohk6D64RZUEMHC+UYkls
zlFpijageeIzKj8VOgIFaEQGLSvJKFtkd8Qyh0bDzneyo97u9TP7Iix/eEKEMa0uGWhaTVa7b9ri
7JHBMoTfIhi86sbSbPe2t2+sm6hV75dl9o2seeW8B4ajAVNdGOL3b3HX0BgGa4d3Ge6H/4yyCHGk
vWD9CU0e7CpYQIZ6eUhKLrEJC2j5EU2i+2yvqcSEGtFr9gBGWcxNnEHgYuw1W14Uyvgi5FHOGzLG
ptBRBoWmXiaQka5jMO0SQgR1FzXLioux57yNsldxMfb81vAo8I0IH+W5BvssHt5IhUEEPdzdjVMV
ds3462j0PD22+y1PsleI0xfYCww25lp6cyHtcxLl4sLBhjTPobD7s7fqBICNKmvf4/8FNfKEHD0c
AAA="

        AMD_FILELIST="`echo "${AMD_FILELIST_GZIP_BASE64}" | base64 -d | gunzip -`"
        for AMD_FILE in ${AMD_FILELIST}
        do
            if [ -f "${AMD_FILE}" ]; then
                echo -n "Remove ${AMD_FILE} ..."
                rm -f ${AMD_FILE}
                if [ $? -ne 0 ]; then
                    print_failure
                fi
                print_okay
            fi
        done

        AMD_DIRLIST="/etc/ati /usr/share/ati /usr/share/doc/packages/fglrx /usr/src/kernel-modules/fglrx"
        for AMD_DIR in ${AMD_DIRLIST}
        do
            if [ -d "${AMD_DIR}" ]; then
                echo -n "Remove ${AMD_DIR} ..."
                rm -rf ${AMD_DIR}
                if [ $? -ne 0 ]; then
                    print_failure
                fi
                print_okay
            fi
        done

        echo -n "Remove the rebuild script if it exists ..."
        if [ -n "`grep 'rebuild fglrx kernel module' /etc/init.d/xdm`" ]; then
            mv -f /etc/init.d/xdm{.backup,}
        fi
        if [ -f /etc/ati/fglrxrebuild.sh ]; then
            rm -f /etc/ati/fglrxrebuild.sh
        fi

        print_okay
    else
        print_aborted
    fi

    echo "Finish!  Please restart your computer."
    exit 0
fi

echo -n "Remove the unneeded old rebuild script ..."
if [ -n "`grep 'rebuild fglrx kernel module' /etc/init.d/xdm`" ]; then
    mv -f /etc/init.d/xdm{.backup,}
fi
if [ -f /etc/ati/fglrxrebuild.sh ]; then
    rm -f /etc/ati/fglrxrebuild.sh
fi
print_okay

#echo -n "Check about wrong formatting /etc/SuSE-release and fixed this if needed (Bug #845262 / openSUSE 13.1 RC1) ..."
#if [ -n "`grep '#' /etc/SuSE-release`" ]; then
#    mv /etc/SuSE-release{,.orig}
#    grep -v '#' /etc/SuSE-release.orig >/etc/SuSE-release
#    print_fixed
#else
#    print_okay
#fi

echo -n "Get openSUSE Version ..."
SUSE_NAME=`lsb_release -d | head -n1 | cut -f2 | cut -f1 -d" "`
SUSE_VERSION=`lsb_release -r | cut -f2`
if [ "${#SUSE_VERSION}" -eq 8 ]; then
    SUSE_VERSION="TUMBLEWEED"
fi
if [ -n "${SUSE_NAME}" -a -n "${SUSE_VERSION}" ]; then
    echo -n -e "\n   ${SUSE_NAME} ${SUSE_VERSION}"
    print_okay
else
    echo -n -e "\n   No openSUSE Version found!"
    print_aborted
    exit
fi

if [ "${SUSE_NAME}" = "openSUSE" ]; then
    if [ "${SUSE_VERSION}" = "12.2" -o "${SUSE_VERSION}" = "12.3" -o "${SUSE_VERSION}" = "13.1" -o "${SUSE_VERSION}" = "13.2" -o "${SUSE_VERSION}" = "42.1" -o "${SUSE_VERSION}" = "TUMBLEWEED" ]; then
        echo "Check needed packages on ${SUSE_NAME} ${SUSE_VERSION}..."
        check_install rpm-build
    fi
fi

echo -n "Check for existing AMD-Installer ZIP file \"${ZIPFILE}\" in current directory ..."
if [ -f ${ZIPFILE} ]; then
    print_okay
else
    print_missing
    echo "Download the AMD-Installer ZIP file ... $AMDDOWNLOADURL"
    curl -f -A "Mozilla/5.0 (X11; Linux x86_64; rv:29.0) Gecko/20100101 Firefox/29.0" -e "http://support.amd.com/de-de/download/desktop?os=Linux+x86" -o "${ZIPFILE}" "${AMDDOWNLOADURL}"
    if [ $? -ne 0 ]; then
        print_failure
        exit 1
    fi
    print_okay
fi

echo -n "Compare SHA1 checksum of the AMD-Installer ZIP file ..."
if [ "${ZIPFILESHA1}" = "`sha1sum ${ZIPFILE} | cut -f1 -d" "`" ]; then
    print_okay
else
    print_failure
    exit 1
fi

echo -n -e "Extracting the AMD driver installer zip \"${ZIPFILE}\" ...\n"
ZIPAMDINSTALLERFILE="`unzip -l ${ZIPFILE} | awk '/run/ { printf "%s", $4 }'`"
unzip -o "${ZIPFILE}" "${ZIPAMDINSTALLERFILE}"
if [ $? -ne 0 ]; then
    echo -n -e "\n   Error: Extracting failed!"
    print_failure
    exit 1
fi
print_okay

# Set AMDINSTALLER from ZIP-Archive
AMDINSTALLER=$(basename ${ZIPAMDINSTALLERFILE})

# Disabled for the moment until AMD changed the ZIP package structure again.
#echo -n -e "Move the AMD driver installer \"${AMDINSTALLER}\" to the current directory ...\n"
#mv -f ${ZIPAMDINSTALLERFILE} ${AMDINSTALLER}
#if [ $? -ne 0 ]; then
#    echo -n -e "\n   Error: Move-Operation was failed!"
#    print_failure
#    exit 1
#fi
#rm -rf $(dirname ${ZIPAMDINSTALLERFILE})
#print_okay

echo -n "Check for existing AMD-Installer \"${AMDINSTALLER}\" in current directory ..."
if [ -f ${AMDINSTALLER} ]; then
    print_okay
else
    print_failure
    exit 1
fi

echo -n "Compare SHA1 checksum of the AMD-Installer ..."
if [ "${AMDINSTALLERSHA1}" = "`sha1sum ${AMDINSTALLER} | cut -f1 -d" "`" ]; then
    print_okay
else
    print_failure
    exit 1
fi

if [ "${PACKAGINGSCRIPTENABLE}" = "yes" ]; then
    echo -n "Check for existing packaging script tarball \"$(basename ${PACKAGINGSCRIPT})\" in current directory ..."
    if [ -f "$(basename ${PACKAGINGSCRIPT})" ]; then
        print_okay
    else
        print_missing
        echo "Download the packaging script tarball \"$(basename ${PACKAGINGSCRIPT})\" ..."
        curl -L -f -o "$(basename ${PACKAGINGSCRIPT})" "${PACKAGINGSCRIPT}"
        if [ $? -ne 0 ]; then
            print_failure
            exit 1
        fi
        print_okay
    fi

    echo -n "Compare SHA1 checksum of the packaging script tarball \"$(basename ${PACKAGINGSCRIPT})\" ..."
    if [ "${PACKAGINGSCRIPTSHA1}" = "`sha1sum $(basename ${PACKAGINGSCRIPT}) | cut -f1 -d" "`" ]; then
        print_okay
    else
        print_failure
        exit 1
    fi
fi

# AMD Binary Blob
if [ "${AMDREPACKINGENABLE}" = "yes" ]; then
    echo -n "Check for existing repacked AMD Binary Blob tar.gz file \"${AMDREPACKING}\" in current directory ..."
    if [ -f ${AMDREPACKING} ]; then
        print_okay
    else
        print_missing
        echo "Download the AMD Binary Blob tar.gz file ... ${AMDREPACKINGURL}"
        curl -f --location -A "Mozilla/5.0 (X11; Linux x86_64; rv:29.0) Gecko/20100101 Firefox/29.0" -e "https://launchpad.net/ubuntu/+source/fglrx-installer/2:14.201-0ubuntu3" -o "${AMDREPACKING}" "${AMDREPACKINGURL}"
        if [ $? -ne 0 ]; then
            print_failure
            exit 1
        fi
        print_okay
    fi

    echo -n "Compare SHA1 checksum of the repacked AMD Binary Blob tar.gz file ..."
    if [ "${AMDREPACKINGSHA1}" = "`sha1sum ${AMDREPACKING} | cut -f1 -d" "`" ]; then
        print_okay
    else
        print_failure
        exit 1
    fi
fi

# exit here if the option -d or --downloadonly is set
if [ "${DOWNLOADONLY}" = "true" ]; then
    exit 0
fi

echo -n "Set the correct permissions of AMD-Installer \"${AMDINSTALLER}\" ..."
chown root:root "${AMDINSTALLER}" && chmod 744 "${AMDINSTALLER}"
if [ $? -ne 0 ]; then
    echo -n -e "\n   Error: permissions could not be set"
    print_failure
    exit 1
fi
print_okay

# get current directory
CURRENTDIR="`pwd`"
# get a temporary directory for extracted AMD installer
AMDTEMPDIR="${CURRENTDIR}/`mktemp -d -u amd-${AMDVERSION}-tmp.XXXXX`"
./"${AMDINSTALLER}" --extract ${AMDTEMPDIR} >/dev/null

if [ "${PACKAGINGSCRIPTENABLE}" = "yes" ]; then
    # Extracting tarball to AMD installer
    cd ${AMDTEMPDIR}
    echo -n -e "Extracting the AMD packaging script tarball \"$(basename ${PACKAGINGSCRIPT})\" ...\n"
    echo "${AMDTEMPDIR}"
    rm -rf ${AMDTEMPDIR}/packages/SuSE
    tar xjf ../$(basename ${PACKAGINGSCRIPT}) -C ${AMDTEMPDIR}/packages
    if [ $? -ne 0 ]; then
        echo -n -e "\n   Error: Extracting failed!"
        print_failure
        exit 1
    fi
    print_okay

    if [ -n "{$PACKAGINGVERSION}" ]; then
        LATEST_BLOB_VERSION=`grep -A1 "\-\-version)" ${AMDTEMPDIR}/ati-packager-helper.sh | grep echo | sed -n -e 's/.*"\(.*\)"/\1/p'`
        echo -n -e "Replace the current version ${LATEST_BLOB_VERSION} to our own version ${PACKAGINGVERSION} ..."
        sed -i "s/${LATEST_BLOB_VERSION}/${PACKAGINGVERSION}/g" ${AMDTEMPDIR}/ati-packager-helper.sh
        if [ $? -ne 0 ]; then
            echo -n -e "\n   Error: Replacing of version was failed!"
            print_failure
            exit 1
        fi
        print_okay
    fi

    AMDINSTALLER="ati-installer.sh `./ati-packager-helper.sh --version`"
fi

if [ "${AMDREPACKINGENABLE}" = "yes" ]; then
    echo -n -e "Extracting the repacked AMD Binary Blob tar.gz ...\n"
    echo -n -e "   Extract \"arch\" ..."
    tar xzf ../${AMDREPACKING} -C ${AMDTEMPDIR}/ ./arch
    if [ $? -ne 0 ]; then
        echo -n -e "\n   Error: Extracting failed!"
        print_failure
        exit 1
    fi
    print_okay
    echo -n -e "   Extract \"etc\" ..."
    tar xzf ../${AMDREPACKING} -C ${AMDTEMPDIR}/common/ ./etc
    if [ $? -ne 0 ]; then
        echo -n -e "\n   Error: Extracting failed!"
        print_failure
        exit 1
    fi
    print_okay
    echo -n -e "   Extract \"lib\" ..."
    tar xzf ../${AMDREPACKING} -C ${AMDTEMPDIR}/common/ ./lib
    if [ $? -ne 0 ]; then
        echo -n -e "\n   Error: Extracting failed!"
        print_failure
        exit 1
    fi
    print_okay
    echo -n -e "   Extract \"usr\" ..."
    tar xzf ../${AMDREPACKING} -C ${AMDTEMPDIR}/common/ ./usr
    if [ $? -ne 0 ]; then
        echo -n -e "\n   Error: Extracting failed!"
        print_failure
        exit 1
    fi
    print_okay
    echo -n -e "   Extract \"xpic\" ..."
    tar xzf ../${AMDREPACKING} -C ${AMDTEMPDIR}/ ./xpic
    if [ $? -ne 0 ]; then
        echo -n -e "\n   Error: Extracting failed!"
        print_failure
        exit 1
    fi
    print_okay
    echo -n -e "   Extract \"xpic_64a\" ..."
    tar xzf ../${AMDREPACKING} -C ${AMDTEMPDIR}/ ./xpic_64a
    if [ $? -ne 0 ]; then
        echo -n -e "\n   Error: Extracting failed!"
        print_failure
        exit 1
    fi
    print_okay
    LATEST_BLOB_VERSION=`grep -A1 "\-\-version)" ${AMDTEMPDIR}/ati-packager-helper.sh | grep echo | sed -n -e 's/.*"\(.*\)"/\1/p'`
    echo -n -e "Replace the current version ${LATEST_BLOB_VERSION} to the lastet AMD Binary Blob version ${AMDREPACKINGVERSION} ..."
    sed -i "s/${LATEST_BLOB_VERSION}/${AMDREPACKINGVERSION}/g" ${AMDTEMPDIR}/ati-packager-helper.sh
    if [ $? -ne 0 ]; then
        echo -n -e "\n   Error: Replacing of version was failed!"
        print_failure
        exit 1
    fi
    print_okay

    echo -n -e "Change the owner of the extracted files to root ..."
    chown -R root:root arch common xpic xpic_64a
    if [ $? -ne 0 ]; then
        echo -n -e "\n   Error: Change the owner of the extracted files to root was failed!"
        print_failure
        exit 1
    fi
    print_okay
fi

echo "Check for supported graphics card on this machine ..."
# catch whole pci list
PCILIST=`lspci -nn`
# filter only gfxcards
GFXCARDS=`lspci -n | grep 0300 | perl -a -l -n -F: -e 'print $F[3]'`
# extract the supported graphic cards from the source code
SUPPORTEDGFXCARDS=`cat ${AMDTEMPDIR}/common/lib/modules/fglrx/build_mod/fglrxko_pci_ids.h | tr '[A-Z]' '[a-z]' | sed -e 's/\s*fgl_asic_id(0x\(.*\)),/\1/g'`
SUPPORTED="no"

for GFXCARD in ${GFXCARDS}
do
    echo "${PCILIST}" | grep "1002:${GFXCARD}"

    for SUPPORTEDGFXCARD in ${SUPPORTEDGFXCARDS}
    do
        if [ "${GFXCARD}" = "${SUPPORTEDGFXCARD}" ]; then
            echo -n -e "Found supported graphics card by ASIC ID: ${GFXCARD}"
            print_okay
            SUPPORTED="yes"
            break
        fi
    done

done

#if [ "${SUPPORTED}" = "no"  ]; then
if ( [ "${SUPPORTED}" = "no" ] && [ "${VM}" = "no" ] ); then
    echo -n -e "Error: This graphics card is not supported by AMD Catalyst ${AMDVERSION}"
    print_failure
    # clean up
    rm -rf ${AMDTEMPDIR}
    exit 1;
elif ( [ "${SUPPORTED}" = "no" ] && [ "${VM}" = "yes" ] ); then
    echo -n -e "Building the package in vm ..."
    print_okay
fi

echo -n -e "\n\nBuild the RPM-Package ...\n"
echo -n -e "----- START: AMD INSTALLER -----\n"
if [ "${FACTORY}" = "true" ]; then
    if [ "`uname -m`" = "x86_64" ]; then
	BUILDPKG="SuSE/SUSEFACTORY-AMD64"
    else
	BUILDPKG="SuSE/SUSEFACTORY-IA32"
    fi
else
    BUILDPKG="SuSE/SUSE-autodetection"
fi

if [ "${KERNEL}" = "true" ]; then
KERNEL_DEVEL="${KERNEL_DEVEL}" UNSUPPORTED="yes" VERBOSE="1" RELEASE="${PACKAGERELEASE}" ./${AMDINSTALLER} --buildpkg ${BUILDPKG} | tee amdinstaller.log
elif [ "${KERNEL}" = "none" ]; then
KERNEL_DEVEL="no" UNSUPPORTED="yes" VERBOSE="1" RELEASE="${PACKAGERELEASE}" ./${AMDINSTALLER} --buildpkg ${BUILDPKG} | tee amdinstaller.log
else
UNSUPPORTED="yes" VERBOSE="1" RELEASE="${PACKAGERELEASE}" ./${AMDINSTALLER} --buildpkg ${BUILDPKG} | tee amdinstaller.log
fi
echo -n -e "----- END: AMD INSTALLER -----\n\n"
RPMFILESWP=`sed -n -e 's!^Package\s*\(.*\)\s*has\s*been\s*successfully\s*generated$!\1!p' amdinstaller.log`
RPMFILES=""
for RPMFILE in ${RPMFILESWP}
do
    RPMFILES="${RPMFILES} `basename ${RPMFILE}`"
done

if [ -n "${RPMFILESWP}" ]; then
    echo -n -e "RPM-Package was built successfully!"
    print_okay
else
    echo -n -e "Error: RPM-Package was NOT built!"
    print_failure
    exit 1
fi

if [ "${PACKAGINGSCRIPTENABLE}" = "yes" ]; then
    # go back to current directory (because of the packaging script)
    cd ${CURRENTDIR}
fi

# clean up
rm -f amdinstaller.log
rm -rf ${AMDTEMPDIR}

# exit here if the option -b or --buildonly is set
if [ "${BUILDONLY}" = "true" ]; then
    exit 0
fi

if [ "${KERNEL}" = "false" ]; then
    echo -n "Get a list of installed Kernel RPM package(s) to prevent a mess of kernel version(s) ..."
    # All Standard openSUSE/SUSE-Kernels
    KERNEL_LIST=`rpm -q kernel-default kernel-desktop kernel-pae kernel-smp kernel-bigsmp kernel-debug | grep -v 'not installed'`
    if [ -n "${KERNEL_LIST}" ]; then
        KERNEL_VERSION_LIST=`for PKG in ${KERNEL_LIST}; do rpm --qf '%{version}-%{release}\n' -q ${PKG}; done | sort | uniq`
        for KERNEL_VERSION in ${KERNEL_VERSION_LIST}
        do
            ZYPPER_KERNEL_PKG="${ZYPPER_KERNEL_PKG} kernel-syms-${KERNEL_VERSION} kernel-source-${KERNEL_VERSION}"
        done
    fi
    # Vanilla Kernels
    KERNEL_LIST=`rpm -q kernel-vanilla | grep -v 'not installed'`
    if [ -n "${KERNEL_LIST}" ]; then
        KERNEL_VERSION_LIST=`for PKG in ${KERNEL_LIST}; do rpm --qf '%{version}-%{release}\n' -q ${PKG}; done | sort | uniq`
        for KERNEL_VERSION in ${KERNEL_VERSION_LIST}
        do
            ZYPPER_KERNEL_PKG="${ZYPPER_KERNEL_PKG} kernel-vanilla-devel-${KERNEL_VERSION} kernel-source-vanilla-${KERNEL_VERSION}"
        done
    fi
    print_okay
else
    ZYPPER_KERNEL_PKG=""
fi

# The following condition was disabled because this is currently not compatible with new packaging script
#echo -n "Check for existing older fglrx package and decide for installation or update the package ..."
#CHECKPACKAGE="`rpm -qa | grep fglrx`"
#PACKAGENAME="`echo "${RPMFILE}" | sed -e 's/\.rpm//g'`"
##SAMEPACKAGE="`rpm -q ${PACKAGENAME}`"
#print_okay

#if [ "${PACKAGENAME}" = "${CHECKPACKAGE}" ]; then
#    echo "Package is already installed ..."
#    echo "   What would you like to do?"
#    echo "      - force update the package (u)"
#    echo "      - rebuild only the fglrx kernel module (r)"
#    echo "      - do nothing / abort (a)"
#    echo ""
#    read -p "Type a letter for update/rebuild/abort [u/r/a]: " USERKEY
#    if [ "${USERKEY}" = "u" ]; then
#        echo "Update the fglrx package now (force) ..."
#        zypper -v -n install -f ${RPMFILE}
#        if [ $? -ne 0 ]; then
#            echo -n "   Error: zypper could not update the ${RPMFILE} package"
#            print_failure
#            exit 1
#        fi
#        print_okay
#    elif [ "${USERKEY}" = "r" ]; then
#        echo "Rebuild the fglrx kernel module ..."
#        /usr/bin/fglrx-kernel-build.sh -f -a
#        if [ $? -ne 0 ]; then
#            echo -n "   Error: could not build the fglrx kernel module"
#            print_failure
#            exit 1
#        fi
#        print_okay
#    else
#        print_aborted
#        exit 0
#    fi
#else
    echo "Install the fglrx package now ..."
    if [ -n "`echo '${CHECKPACKAGE}' | grep 'fglrxG02'`" ]; then
        zypper -v install -C -t package -t patch ${RPMFILES} ${ZYPPER_KERNEL_PKG}
    else
        zypper -v -n install -C -t package -t patch ${RPMFILES} ${ZYPPER_KERNEL_PKG}
    fi
    if [ $? -ne 0 ]; then
        echo -n "   Error: zypper could not install the packages: ${RPMFILES}"
        print_failure
        exit 1
    fi
    print_okay
#fi

echo -n "Check for activated fglrx rebuild init script ..."
if [ -z "`chkconfig -A -l | grep fglrxrebuild | grep 'B:on'`" ]; then
    chkconfig -a boot.fglrxrebuild
    if [ $? -ne 0 ]; then
        echo -n "   Error: chkconfig could not activate the fglrx rebuild init script"
        print_failure
        exit 1
    fi
fi
print_okay

echo "Finish!  Please restart your computer and have a lot of fun! ;-)"
