#!/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.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/06/17/opensuse-11-2-proprietaeren-grafik-treiber-ati-catalyst-10-6-als-rpm-installieren/

ATIVERSION="10.6"
ATIINSTALLER="ati-driver-installer-10-6-x86.x86_64.run"
ATIINSTALLERSHA1="fd903b41d5bd3bd095322142d78e11dcf65aa1b8"
ATIDOWNLOADURL="https://a248.e.akamai.net/f/674/9206/0/www2.ati.com/drivers/linux/${ATIINSTALLER}"
SCRIPTVERSION="3.0-beta2"
OPENSUSERELEASE="/etc/SuSE-release"
XORGCONF="/etc/X11/xorg.conf"
NEWXSERVERRPM="xorg-x11-server-7.4-61.1"

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 "  -/--kms <yes|no>           enable or disable Kernel-Mode-Setting"
    echo "  -/--old2ddriver <yes|no>   enable or disable the older 2D-Driver"
    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"
UPDATEXONLY="false"
KMS=""
OLD2DDRIVER=""
ERRORMESSAGE=""

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

while [ "$#" -gt "0" ]; do
    case $1 in
        -b|--buildonly)
            if [ "${DOWNLOADONLY}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--downloadonly\""
            elif [ "${INSTALL}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--install\""
            elif [ -n "${MONITORTYPE}" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--configure\""
            elif [ -n "${KMS}" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--kms\""
            elif [ -n "${OLD2DDRIVER}" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--old2ddriver\""
            elif [ "${UPDATEXONLY}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--update-x-only\""
            fi
            if [ -n "${ERRORMESSAGE}" ]; then
                echo "${ERRORMESSAGE}"
                exit 1;
            fi
            BUILDONLY="true"
            echo "only build"
            shift 1
        ;;
        -c|--configure)
            if [ "${BUILDONLY}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--buildonly\""
            elif [ "${DOWNLOADONLY}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--downloadonly\""
            elif [ "${INSTALL}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--install\""
            elif [ -n "${KMS}" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--kms\""
            elif [ -n "${OLD2DDRIVER}" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--old2ddriver\""
            elif [ "${UPDATEXONLY}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--update-x-only\""
            fi
            if [ -n "${ERRORMESSAGE}" ]; then
                echo "${ERRORMESSAGE}"
                exit 1;
            fi
            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)
            if [ "${BUILDONLY}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--buildonly\""
            elif [ "${INSTALL}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--install\""
            elif [ -n "${MONITORTYPE}" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--configure\""
            elif [ -n "${KMS}" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--kms\""
            elif [ -n "${OLD2DDRIVER}" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--old2ddriver\""
            elif [ "${UPDATEXONLY}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--update-x-only\""
            fi
            if [ -n "${ERRORMESSAGE}" ]; then
                echo "${ERRORMESSAGE}"
                exit 1;
            fi
            DOWNLOADONLY="true"
            echo "only download"
            shift 1
        ;;
        -i|--install)
            if [ "${BUILDONLY}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--buildonly\""
            elif [ "${DOWNLOADONLY}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--downloadonly\""
            elif [ -n "${MONITORTYPE}" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--configure\""
            elif [ -n "${KMS}" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--kms\""
            elif [ -n "${OLD2DDRIVER}" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--old2ddriver\""
            elif [ "${UPDATEXONLY}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--update-x-only\""
            fi
            if [ -n "${ERRORMESSAGE}" ]; then
                echo "${ERRORMESSAGE}"
                exit 1;
            fi
            INSTALL="true"
            echo "build and install"
            shift 1
        ;;
        -kms|--kms)
            if [ "${BUILDONLY}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--buildonly\""
            elif [ "${INSTALL}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--install\""
            elif [ "${DOWNLOADONLY}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--downloadonly\""
            elif [ -n "${MONITORTYPE}" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--configure\""
            elif [ -n "${OLD2DDRIVER}" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--old2ddriver\""
            elif [ "${UPDATEXONLY}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--update-x-only\""
            fi
            if [ -n "${ERRORMESSAGE}" ]; then
                echo "${ERRORMESSAGE}"
                exit 1;
            fi
            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)
            if [ "${BUILDONLY}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--buildonly\""
            elif [ "${INSTALL}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--install\""
            elif [ "${DOWNLOADONLY}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--downloadonly\""
            elif [ -n "${MONITORTYPE}" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--configure\""
            elif [ -n "${KMS}" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--kms\""
            elif [ "${UPDATEXONLY}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--update-x-only\""
            fi
            if [ -n "${ERRORMESSAGE}" ]; then
                echo "${ERRORMESSAGE}"
                exit 1;
            fi
            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
        ;;
        -ux|--update-x-only)
            if [ "${BUILDONLY}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--buildonly\""
            elif [ "${INSTALL}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--install\""
            elif [ "${DOWNLOADONLY}" = "true" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--downloadonly\""
            elif [ -n "${KMS}" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--kms\""
            elif [ -n "${OLD2DDRIVER}" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--old2ddriver\""
            elif [ -n "${MONITORTYPE}" ]; then
                ERRORMESSAGE="Error: Option \"$1\" can not use with \"--configure\""
            fi
            if [ -n "${ERRORMESSAGE}" ]; then
                echo "${ERRORMESSAGE}"
                exit 1;
            fi
            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_available() {
    echo -e "[\e[1;32m AVAILABLE \e[0;37m]"
}
print_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_available
    else
        print_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
}

refill_spaces() {
    STRING=$1
    echo -n "${STRING}"
    printf ' %.0s' $(seq 1 $[48-${#STRING}])
}

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 [ "${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_failure

        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
    #echo -n -e "\n   Error: Please download the ATI Installer from http://support.amd.com/us/gpudownload/Pages/index.aspx"
    print_failure
    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 ATI driver support officially openSUSE 11.3, remove or disable this part.
if [ "${OPENSUSEVERSION}" = "11.3" ]; then
    ATIPATCH1="ati-10.6-xorg-7.5.patch"
    ATIPATCH1URL="http://www.sebastian-siebert.de/downloads/${ATIPATCH1}"
    ATIPATCH1SHA1="a2491ee0d6d903e06293375fff0a6b6ff6a606d2"

    echo -n "Check for existing patch \"${ATIPATCH1}\" in current directory ..."
    if [ -f ${ATIPATCH1} ]; then
        print_okay
    else
        print_failure
        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

    ATIPATCH2="ati-10.6-fixed-missing-include.patch"
    ATIPATCH2URL="http://www.sebastian-siebert.de/downloads/${ATIPATCH2}"
    ATIPATCH2SHA1="3813621ca733726499ba7574d432aa20d030cce9"
    echo -n "Check for existing patch \"${ATIPATCH2}\" in current directory ..."
    if [ -f ${ATIPATCH2} ]; then
        print_okay
    else
        print_failure
        echo "Download the patch \"${ATIPATCH2}\" ..."
        curl -f -o "${ATIPATCH2}" "${ATIPATCH2URL}"
        if [ $? -ne 0 ]; then
            print_failure
            exit 1
        fi
        print_okay
    fi

    echo -n "Compare SHA1 checksum of the patch \"${ATIPATCH2}\" ..."
    if [ "${ATIPATCH2SHA1}" = "`sha1sum ${ATIPATCH2} | 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}`
./${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'`

for GFXCARD in ${GFXCARDS}
do
    SUPPORTED="no"
    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

    if [ "${SUPPORTED}" = "no" ]; then
        echo -n -e "Error: This grafics card is not supported by ATI Catalyst ${ATIVERSION}"
        print_failure
        # clean up
        rm -rf ${ATITEMPDIR}
        exit 1;
    fi
done

# clean up
if [ "${OPENSUSEVERSION}" != "11.3" ]; then
    rm -rf ${ATITEMPDIR}
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"
print_okay

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

# If ATI driver support officially openSUSE 11.3, remove or disable this part.
if [ "${OPENSUSEVERSION}" = "11.3" ]; then
    PACKAGE="${PACKAGE}-unofficial-Xorg75"
    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

    echo -n -e "Patch the ATI-Installer with \"${ATIPATCH2}\" ...\n"
    patch -p1 <../${ATIPATCH2}
    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=`cat atiinstaller.log | grep "generated" | 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

# clean up
rm -f atiinstaller.log
if [ "${OPENSUSEVERSION}" = "11.3" ]; then
    rm -rf ${ATITEMPDIR}
    # change to current directory
    cd ${CURRENTDIR}
fi

# 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`"
print_okay

if [ -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
    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
    fi
    print_okay
fi

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