#!/bin/bash

# Copyright (c) 2010, 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 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/2010/10/24/opensuse-11-3-proprietaeren-grafik-treiber-ati-catalyst-10-10-als-rpm-installieren/

ATIVERSION="10.10"
ATIINSTALLER="ati-driver-installer-`echo "${ATIVERSION}" | sed -e 's/\./-/g'`-x86.x86_64.run"
ATIINSTALLERSHA1="d50d0b7ec2755c7be20ff81670958b98ace6a713"
ATIDOWNLOADURL="https://a248.e.akamai.net/f/674/9206/0/www2.ati.com/drivers/linux/${ATIINSTALLER}"
SCRIPTVERSION="3.9"
OPENSUSERELEASE="/etc/SuSE-release"
XORGCONF="/etc/X11/xorg.conf"
NEWXSERVERRPM="xorg-x11-server-7.4-61.1"
REBUILDSCRIPT="/etc/ati/fglrxrebuild.sh"
REBUILDSCRIPTSHA1="9ae6fa09601ef9403bf4d097b8db33f90a195ad3"

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 ATI-Installer"
    echo "  -i/--install               build and install/update the RPM-Package"
    echo "  -irs/--irs                 install a rebuild script to /etc/ati/fglrxrebuild.sh and modified the xdm startup script"
    echo "  -/--kms <yes|no>           enable or disable Kernel-Mode-Setting"
    echo "  -/--old2ddriver <yes|no>   enable or disable the older 2D-Driver"
    echo "  -r/--report                generate a report from this system"
    echo "  -u/--uninstall             remove ATI Catalyst and clean up completely all possible ATI files and directories"
    echo "  -ur/--uploadreport         same as --report, additionally the report will be uploaded to sprunge.us"
    echo "  -urs/--urs                 uninstall the rebuild script /etc/ati/fglrxrebuild.sh and restore the xdm startup script"
    echo "  -ux/--update-x-only        update the X-Server to set up the screen depth to 24bit for fglrx-driver (strongly recommends)"
    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"
UPDATEXONLY="false"
KMS=""
OLD2DDRIVER=""
REPORT="false"
UPLOADREPORT="false"
INSTALLREBUILDSCRIPT="false"
UNINSTALLREBUILDSCRIPT="false"
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"
    elif [ "${UPDATEXONLY}" = "true" -a "updatexonly" != "$1" ]; then
        ERROROPTION="--update-x-only"
    elif [ "${INSTALLREBUILDSCRIPT}" = "true" -a "installrebuildscript" != "$1" ]; then
        ERROROPTION="--irs"
    elif [ "${UNINSTALLREBUILDSCRIPT}" = "true" -a "uninstallrebuildscript" != "$1" ]; then
        ERROROPTION="--urs"
    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
        ;;
        -irs|--irs)
            check_invalid_options "installrebuildscript"
            INSTALLREBUILDSCRIPT="true"
            echo "install rebuild script"
            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
        ;;
        -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
        ;;
        -urs|--urs)
            check_invalid_options "uninstallrebuildscript"
            UNINSTALLREBUILDSCRIPT="true"
            echo "uninstall rebuild script"
            shift 1
        ;;
        -ux|--update-x-only)
            check_invalid_options "updatexonly"
            UPDATEXONLY="true"
            echo "update the X-Server"
            shift 1
        ;;
        -h|--help)
            OutputUsage
            exit 0
        ;;
        -V|--version)
            echo -e "$(basename $0) - Version ${SCRIPTVERSION}\n"
            echo "Copyright (c) 2010, 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[0;37m]"
}
print_failure() {
    echo -e "\033[${COLUMNS}C\033[15D[\e[1;31m FAILURE \e[0;37m]"
}
print_missing() {
    echo -e "\033[${COLUMNS}C\033[15D[\e[1;33m MISSING \e[0;37m]"
}
print_aborted() {
    echo -e "\033[${COLUMNS}C\033[15D[\e[1;33m ABORTED \e[0;37m]"
}

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

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}\"\n"
        zypper -q -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 ATI 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

echo -n "Grab openSUSE Version ..."
if [ -f ${OPENSUSERELEASE} ]; then
    OPENSUSEVERSION=`cat ${OPENSUSERELEASE} | grep VERSION | cut -c 11-`
    ATIOSVERSION=`echo "${OPENSUSEVERSION}" | sed -e 's/\.//g'`
    echo -n -e "\n   openSUSE Version = ${OPENSUSEVERSION} (${ATIOSVERSION})"
else
    echo -n -e "\n   Error: This script runs only under openSUSE!"
    print_failure
    exit 1
fi
print_okay

echo -n "Get the architecture of this machine ..."
ARCH="$(uname -m)"
case "${ARCH}" in
i?86)
    ATIARCH="IA32"
    ;;
x86_64)
    ATIARCH="AMD64"
    ;;
esac
echo -n -e "\n   Architecture: ${ARCH} (${ATIARCH})"
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

    if [ "${OPENSUSEVERSION}" = "11.2" ]; then
        echo "Create a new configuration file ${XORGCONF} via SaX2 ..."
        sax2 -a
        if [ $? -ne 0 ]; then
            print_failure
            exit 1
        fi
        print_okay
    fi

    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
        cat /etc/sysconfig/kernel | sed -e 's/NO_KMS_IN_INITRD=.*/NO_KMS_IN_INITRD="no"/g' >/etc/sysconfig/kernel.new
    elif [ "${KMS}" = "no" ]; then
        cat /etc/sysconfig/kernel | sed -e 's/NO_KMS_IN_INITRD=.*/NO_KMS_IN_INITRD="yes"/g' >/etc/sysconfig/kernel.new
    fi
    mv /etc/sysconfig/kernel{,.old}
    mv /etc/sysconfig/kernel{.new,}
    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="ati-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 "================================================" >>${REPORTFILE}
    echo -n -e "\n\n\n" >>${REPORTFILE}
}

report_output() {
    echo "   OUTPUT: $@"
    echo "# OUTPUT: $@" >>${REPORTFILE}
    echo "------------------------------------------------" >>${REPORTFILE}
    echo "`$@ 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_output `which dmesg`
    report_echo "lsmod | grep fglrx" `lsmod | 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
    report_echo "rpm -qa | grep fglrx | sort" `rpm -qa | grep fglrx | sort`
    report_echo "rpm -qa | grep kernel | sort" `rpm -qa | grep kernel | sort`
    report_file /boot/grub/menu.lst
    report_file /etc/sysconfig/kernel
    report_files /home/*/.kde4/share/config/kwinrc

    print_okay

    if [ "${UPLOADREPORT}" = "true" ]; then
#        REPORTFILECONTENT="`cat ${REPORTFILE}`"
#        REPORTUSER="openSUSE User"
        REPORTURL="`cat ati-report.txt | curl -F 'sprunge=<-' http://sprunge.us -s 2>&1`"

#        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'`"
        echo -n -e "\n\nThe report was uploaded to sprunge.us.\n   The link is: ${REPORTURL}\n"
    fi

    exit 0
fi

if [ "${UNINSTALL}" = "true" ]; then
    echo "Remove the ATI 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 ATI files and directories? yes/no [y/n]: " USERKEY
    fi

    if [ "${USERKEY}" = "y" -o "${USERKEY}" = "yes" ]; then
        echo "Try to remove the existing ATI 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 ATI files.
        # I have zipped it and encoded in base64 to get a smaller script code.
        ATI_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="

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

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

        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

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

    echo "Download and install the rebuild script ..."
    curl -f -o ${REBUILDSCRIPT} http://www.sebastian-siebert.de/downloads/$(basename ${REBUILDSCRIPT})
    if [ $? -ne 0 ]; then
        print_failure
        exit 1
    fi
    print_okay

    echo -n "Compare SHA1 checksum of the rebuild script ..."
    if [ "${REBUILDSCRIPTSHA1}" = "`sha1sum ${REBUILDSCRIPT} | cut -f1 -d" "`" ]; then
        print_okay
    else
        rm -f ${REBUILDSCRIPT}
        print_failure
        exit 1
    fi

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

    echo -n "Backup and modify the xdm init script /etc/init.d/xdm ..."
    if [ -z "`grep 'rebuild fglrx kernel module' /etc/init.d/xdm`" ]; then
        cp -p /etc/init.d/xdm{,.backup}
        sed -i "s|### END INIT INFO|### END INIT INFO\n\n# rebuild fglrx kernel module if necessary\nif [ -f ${REBUILDSCRIPT} ]; then\n\t${REBUILDSCRIPT}\nfi|g" /etc/init.d/xdm
    fi
    print_okay

    exit 0
fi

if [ "${UNINSTALLREBUILDSCRIPT}" = "true" ]; then
    echo -n "Remove the rebuild script ..."
    if [ -n "`grep 'rebuild fglrx kernel module' /etc/init.d/xdm`" ]; then
        mv -f /etc/init.d/xdm{.backup,}
    fi
    if [ -f ${REBUILDSCRIPT} ]; then
        rm -f ${REBUILDSCRIPT}
    fi
    print_okay
    exit 0
fi


if [ "${UPDATEXONLY}" = "true" -a "${OPENSUSEVERSION}" = "11.2" ]; then
    echo -n "Check for existing X-Server Repo in zypper ..."
    CHECKREPO="`zypper lr -d | grep '/repositories/home:/Freespacer:/X11:/XOrg/openSUSE_11.2/'`"
    if [ -z "${CHECKREPO}" ]; then
        print_missing

        echo "Add the X-Server Repo to http://download.opensuse.org/repositories/home:/Freespacer:/X11:/XOrg/openSUSE_11.2/  ..."
        zypper ar -f "http://download.opensuse.org/repositories/home:/Freespacer:/X11:/XOrg/openSUSE_11.2/"  "X-Server (fglrx)"
        if [ $? -ne 0 ]; then
            print_failure
            exit 1
        fi
        print_okay

        echo "Modify X-Server Repo to set higher priority ..."
        zypper mr -p 90 "X-Server (fglrx)"
        if [ $? -ne 0 ]; then
            print_failure
            exit 1
        fi
        print_okay

        echo "Refresh the X-Server Repo ..."
        zypper ref "X-Server (fglrx)"
        if [ $? -ne 0 ]; then
            print_failure
            exit 1
        fi
    fi
    print_okay

    echo -n "Check the Patch-Level Version of installed X-Server ..."
    XSERVERRPMVERSION="`rpm -q xorg-x11-server | cut -d"." -f3`"
    if [ "${XSERVERRPMVERSION}" -eq "63" ]; then
        print_okay

        echo "Install the patched X-Server ..."
        case "${ARCH}" in
        i?86)
            XDOWNLOADURL="http://download.opensuse.org/repositories/home:/Freespacer:/X11:/XOrg/openSUSE_11.2/i586/${NEWXSERVERRPM}.i586.rpm"
            ;;
        x86_64)
            XDOWNLOADURL="http://download.opensuse.org/repositories/home:/Freespacer:/X11:/XOrg/openSUSE_11.2/x86_64/${NEWXSERVERRPM}.x86_64.rpm"
            ;;
        esac
        curl -f -L -O "${XDOWNLOADURL}"
        if [ $? -ne 0 ]; then
            print_failure
            exit 1
        fi
        rpm -Uhv --force $(basename ${XDOWNLOADURL})
        if [ $? -ne 0 ]; then
            print_failure
            exit 1
        fi
        print_okay
    elif [ "${XSERVERRPMVERSION}" -eq "1" ]; then
        print_okay
        echo "The patched X-Server is already installed!"
    else
        print_failure
    fi

    exit 0
elif [ "${UPDATEXONLY}" = "true" -a "${OPENSUSEVERSION}" = "11.3" ]; then
    echo -n "Your openSUSE-Version doesn't need a patched X-Server!"
    print_failure
    exit 1
elif [ "${UPDATEXONLY}" = "true" -a "${OPENSUSEVERSION}" != "11.2" ]; then
    echo -n "Sorry, your openSUSE-Version isn't support yet to install a patched X-Server!"
    print_failure
    exit 1
fi


echo -n "Check for existing ATI-Installer \"${ATIINSTALLER}\" in current directory ..."
if [ -f ${ATIINSTALLER} ]; then
    print_okay
else
    print_missing
    echo "Download the ATI-Installer ..."
    curl -f -o "${ATIINSTALLER}" "${ATIDOWNLOADURL}"
    if [ $? -ne 0 ]; then
        print_failure
        exit 1
    fi
    print_okay
fi

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

#if [ "${OPENSUSEVERSION}" = "11.3" ]; then
#    ATIPATCH1="ati-10.9-replace-function-compat_alloc_user_space.patch"
#    ATIPATCH1URL="http://www.sebastian-siebert.de/downloads/${ATIPATCH1}"
#    ATIPATCH1SHA1="cd3485cd1d42d5299d820fef3f1180f64f5e43d0"
#
#    echo -n "Check for existing patch \"${ATIPATCH1}\" in current directory ..."
#    if [ -f ${ATIPATCH1} ]; then
#        print_okay
#    else
#        print_missing
#        echo "Download the patch \"${ATIPATCH1}\" ..."
#        curl -f -o "${ATIPATCH1}" "${ATIPATCH1URL}"
#        if [ $? -ne 0 ]; then
#            print_failure
#            exit 1
#        fi
#        print_okay
#    fi
#
#    echo -n "Compare SHA1 checksum of the patch \"${ATIPATCH1}\" ..."
#    if [ "${ATIPATCH1SHA1}" = "`sha1sum ${ATIPATCH1} | 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 ATI-Installer \"${ATIINSTALLER}\" ..."
chown root:root ${ATIINSTALLER} && chmod 744 ${ATIINSTALLER}
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 ati installer
ATITEMPDIR=`mktemp -d -u --tmpdir=${CURRENTDIR} ati-${ATIVERSION}-tmp.XXXXX`
./${ATIINSTALLER} --extract ${ATITEMPDIR} >/dev/null
# extract the supported graphic cards from the source code
SUPPORTEDGFXCARDS=`cat ${ATITEMPDIR}/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
    echo -n -e "Error: This graphics card is not supported by ATI Catalyst ${ATIVERSION}"
    print_failure
    # clean up
    rm -rf ${ATITEMPDIR}
    exit 1;
fi

echo "Check the installed development packages ..."
check_install "gcc"
check_install "make"
check_install "patch"
check_install "kernel-source"
if [ "${OPENSUSEVERSION}" != "11.3" ]; then
    check_install "linux-kernel-headers"
elif [ "${OPENSUSEVERSION}" = "11.3" ]; then
    check_install "kernel-devel"
fi
check_install "kernel-$(uname -r | cut -f3 -d"-")-devel"
check_install "kernel-syms"
print_okay

# run the ATI Installer
PACKAGE="SuSE/SUSE${ATIOSVERSION}-${ATIARCH}"

# Patch the source of fglrx kernel module
#if [ "${OPENSUSEVERSION}" = "11.3" ]; then
#    cd ${ATITEMPDIR}
#    echo -n -e "Patch the ATI-Installer with \"${ATIPATCH1}\" ...\n"
#    patch -p1 <../${ATIPATCH1}
#    if [ $? -ne 0 ]; then
#        echo -n -e "\n   Error: Patch doesn't applied"
#        print_failure
#        exit 1
#    fi
#    print_okay
#
#    ATIINSTALLER="ati-installer.sh `./ati-packager-helper.sh --version`"
#fi

echo -n -e "\n\nBuild the RPM-Packages \"${PACKAGE}\" ...\n"
echo -n -e "----- START: ATI INSTALLER -----\n"
./${ATIINSTALLER} --buildpkg ${PACKAGE} | tee atiinstaller.log
echo -n -e "----- END: ATI INSTALLER -----\n\n"
RPMFILEWP=`grep "generated" atiinstaller.log | cut -f2 -d" "`
if [ -n "${RPMFILEWP}" ]; then
    echo -n -e "RPM-Package was builded successfully!"
    print_okay
    RPMFILE=`basename ${RPMFILEWP}`
    if [ "${BUILDONLY}" = "true" ]; then
        echo -n -e "\nInstall the RPM-Package with: rpm -ihv ${RPMFILE}\n"
        echo -n -e "   OR\n"
        echo -n -e "Update the RPM-Package with: rpm -Uhv ${RPMFILE}\n"
    fi
else
    echo -n -e "Error: RPM-Package was NOT builded!"
    print_failure
    exit 1
fi

# go back to current directory (because of the patch)
#if [ "${OPENSUSEVERSION}" = "11.3" ]; then
#    cd ${CURRENTDIR}
#fi

# clean up
rm -f atiinstaller.log
rm -rf ${ATITEMPDIR}

# 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) ..."
        rpm -Uhv --force ${RPMFILE}
        if [ $? -ne 0 ]; then
            echo -n "   Error: rpm 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
elif [ -z ${CHECKPACKAGE} ]; then
    echo "Install the fglrx package now ..."
    rpm -ihv ${RPMFILE}
    if [ $? -ne 0 ]; then
        echo -n "   Error: rpm could not install the ${RPMFILE} package"
        print_failure
        exit 1
    fi
    print_okay
else
    echo "Update the fglrx package now ..."
    rpm -Uhv ${RPMFILE}
    if [ $? -ne 0 ]; then
        echo -n "   Error: rpm could not update the ${RPMFILE} package"
        print_failure
        exit 1
    fi
    print_okay
fi

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