#!/bin/bash

# Copyright (c) 2010-2012, 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.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/2012/01/26/opensuse-proprietaeren-grafik-treiber-amd-catalyst-12-1-als-rpm-installieren/

AMDVERSION="12.1"
AMDINSTALLER="amd-driver-installer-`echo "${AMDVERSION}" | sed -e 's/\./-/g'`-x86.x86_64.run"
AMDINSTALLERSHA1="8262b2a66cf87063713852c8f3a20bc995be47e6"
AMDDOWNLOADURL="https://a248.e.akamai.net/f/674/9206/0/www2.ati.com/drivers/linux/${AMDINSTALLER}"
SCRIPTVERSION="5.0"
XORGCONF="/etc/X11/xorg.conf"
PACKAGERELEASE="1"
PACKAGINGSCRIPT="http://www.sebastian-siebert.de/downloads/amd-${AMDVERSION}-packaging-script.tar.bz2"
PACKAGINGSCRIPTSHA1="8b6d6f0e03da5b9e663414eff5e6f19fa807f723"

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 "  -/--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 "  -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"
KMS=""
OLD2DDRIVER=""
REPORT="false"
UPLOADREPORT="false"
VM="no"
ERROROPTION=""

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

check_invalid_options() {
    # $1 = option
    if [ "${BUILDONLY}" = "true" -a "buildonly" != "$1" ]; then
        ERROROPTION="--buildonly"
    elif [ "${DOWNLOADONLY}" = "true" -a "downloadonly" != "$1" ]; then
        ERROROPTION="--downloadonly"
    elif [ "${INSTALL}" = "true" -a "install" != "$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
        ;;
        -i|--install)
            check_invalid_options "install"
            INSTALL="true"
            echo "build and install"
            shift 1
        ;;
        -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
        ;;
        -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_pkg_available() {
    echo -e "[\e[1;32m AVAILABLE \e[0m]"
}
print_pkg_missing() {
    echo -e "[\e[1;31m MISSING \e[0m]"
}

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 [ -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_file /etc/SuSE-release
    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 /etc/sysconfig/kernel
    report_files /home/*/.kde4/share/config/kwinrc

    echo -n -e "\nThe sytem 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.to? 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 for existing AMD-Installer \"${AMDINSTALLER}\" in current directory ..."
if [ -f ${AMDINSTALLER} ]; then
    print_okay
else
    print_missing
    echo "Download the AMD-Installer ..."
    curl -f -o "${AMDINSTALLER}" "${AMDDOWNLOADURL}"
    if [ $? -ne 0 ]; then
        print_failure
        exit 1
    fi
    print_okay
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

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 -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

# 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

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]'`
# 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
# 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

# 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

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

echo -n -e "\n\nBuild the RPM-Package ...\n"
echo -n -e "----- START: AMD INSTALLER -----\n"
UNSUPPORTED="yes" VERBOSE="1" RELEASE="${PACKAGERELEASE}" ./${AMDINSTALLER} --buildpkg SuSE/SUSE-autodetection | tee amdinstaller.log
echo -n -e "----- END: AMD INSTALLER -----\n\n"
RPMFILEWP=`grep "generated" amdinstaller.log | cut -f2- -d" "`
RPMFILE=`basename "${RPMFILEWP%%.rpm*}.rpm"`
if [ -n "${RPMFILEWP}" ]; 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

# go back to current directory (because of the packaging script)
cd ${CURRENTDIR}

# 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

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
        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 ${RPMFILE}
    else
        zypper -v -n install ${RPMFILE}
    fi
    if [ $? -ne 0 ]; then
        echo -n "   Error: zypper could not install the ${RPMFILE} package"
        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! ;-)"

