#!/bin/bash

# Copyright (c) 2011, 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 1.4  - support Flash Player 11.2 (11.2.202.96)
# Version 1.3  - support Flash Player 11 (11.0.1.152)
# Version 1.2  - support Flash Player 11 (11.0.r1.129)
# Version 1.1  - add needed patch tool
# Version 1.0  - inital development

# Webpage:
# http://www.sebastian-siebert.de/2011/12/03/opensuse-adobe-flash-player-12.1-installieren

FLASHVERSION="11.2.202.96"
FLASHDOWNLOADURL="http://download.macromedia.com/pub/labs/flashplatformruntimes/flashplayer11-2/"
FLASH32="flashplayer11-2_p2_install_lin_32_112211.tar.gz"
FLASH32SHA1="eaa833e4d73deb86d77c9391f488e117878c7b12"
FLASH64="flashplayer11-2_p2_install_lin_64_112211.tar.gz"
FLASH64SHA1="b9447ed203d0c2503d733233b4b0c95ed9302fad"
FLASHRPMSPEC="http://www.sebastian-siebert.de/downloads/flash-player-11.2-beta2-spec.tar.bz2"
FLASHRPMSPECSHA1="dc0294361fa84303bbfb3e325c7fec076ee26ad3"
SCRIPTVERSION="1.4"

function OutputUsage() {
    echo "Usage : $(basename $0) [options...]"
    echo "Options:"
    echo "  -b/--build <all|gnome|kde>     build the RPM-Packages (all = default)"
    echo "  -i/--install <all|gnome|kde>   build and install/update the RPM-Package"
    echo "  -u/--uninstall                 remove flash-player and clean up completely"
    echo "  -h/--help                  this help text"
    echo "  -V/--version               show version number"

    exit 1
}

# set default configuration
BUILDONLY="all"
INSTALL="false"
UNINSTALL="false"
ERROROPTION=""
FLASHSPECFILE="flash-player.spec"

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

check_invalid_options() {
    # $1 = option
    if [ "${BUILDONLY}" != "false" -a "build" != "$1" ]; then
        ERROROPTION="--build"
    elif [ "${INSTALL}" != "false" -a "install" != "$1" ]; then
        ERROROPTION="--install"
    elif [ "${UNINSTALL}" = "true" -a "uninstall" != "$1" ]; then
        ERROROPTION="--uninstall"
    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|--build)
            check_invalid_options "build"
            if [ -z "$2" -o "${2:0:1}" = "-" ]; then
                BUILDONLY="all"
                shift 1
            else
                if [ "$2" != "all" -a "$2" != "gnome" -a "$2" != "kde" ]; then
                    echo "Error: Value \"$2\" is unknown. Please set only \"all\", \"gnome\" or \"kde\"."
                    exit 1
                fi
                BUILDONLY="$2"
                shift 2
            fi
            case "${BUILDONLY}" in
                all)
                    FLASHSPECFILE="flash-player.spec"
                    ;;
                gnome)
                    FLASHSPECFILE="flash-player-gnome.spec"
                    ;;
                kde)
                    FLASHSPECFILE="flash-player-kde.spec"
                    ;;
            esac
            echo "build for ${BUILDONLY}"
        ;;
        -i|--install)
            check_invalid_options "install"
            if [ -z "$2" -o "${2:0:1}" = "-" ]; then
                INSTALL="all"
                shift 1
            else
                if [ "$2" != "all" -a "$2" != "gnome" -a "$2" != "kde" ]; then
                    echo "Error: Value \"$2\" is unknown. Please set only \"all\", \"gnome\" or \"kde\"."
                    exit 1
                fi
                INSTALL="$2"
                shift 2
            fi
            case "${INSTALL}" in
                all)
                    FLASHSPECFILE="flash-player.spec"
                ;;
                gnome)
                    FLASHSPECFILE="flash-player-gnome.spec"
                ;;
                kde)
                    FLASHSPECFILE="flash-player-kde.spec"
                ;;
            esac
            echo "build and install for ${INSTALL}"
        ;;
        -u|--uninstall)
            check_invalid_options "uninstall"
            UNINSTALL="true"
            shift 1
        ;;
        -h|--help)
            OutputUsage
            exit 0
        ;;
        -V|--version)
            echo -e "$(basename $0) - Version ${SCRIPTVERSION}\n"
            echo "Copyright (c) `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]"
}

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 Adobe Flash Player"
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 "Get the architecture of this machine ..."
ARCH=$(uname -m)
case "${ARCH}" in
i?86)
    ARCHBIT="32"
    FLASHURL="${FLASHDOWNLOADURL}${FLASH32}"
    FLASHFILE="${FLASH32}"
    FLASHSHA1="${FLASH32SHA1}"
    ;;
x86_64)
    ARCHBIT="64"
    FLASHURL="${FLASHDOWNLOADURL}${FLASH64}"
    FLASHFILE="${FLASH64}"
    FLASHSHA1="${FLASH64SHA1}"
    ;;
esac
echo -n -e "\n   Architecture: ${ARCH} (${ARCHBIT}-bit)"
print_okay

if [ "${UNINSTALL}" = "true" ]; then
    echo "Remove the Adobe Flash Player from this system ..."
    FLASHPLAYER_PACKAGES="`rpm -qa | grep '^flash-player'`"
    PACKAGE_COUNTER="$(echo ${FLASHPLAYER_PACKAGES} | wc -w)"
    if [ -n "${FLASHPLAYER_PACKAGES}" ]; then
        if [ "${PACKAGE_COUNTER}" -gt "1" ]; then
            echo "   Following packages will be removed:"
        else
            echo "   Following package will be removed:"
        fi
        for FLASHPLAYER_PACKAGE in ${FLASHPLAYER_PACKAGES}
        do
            rpm -q --qf "   =>   Name:         %{name}
        Summary:      %{summary}
        Version:      %{version}
        Release:      %{release}
        Architecture: %{arch}
        Size:         %{size} bytes
        Installed on: %{installtime:date}\n\n" ${FLASHPLAYER_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 ${FLASHPLAYER_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

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

echo "Check the installed needed packages ..."
check_install "update-desktop-files"
check_install "fdupes"
check_install "patch"
if [ "${BUILDONLY}" = "all" -o "${INSTALL}" = "all" -o "${BUILDONLY}" = "kde" -o "${INSTALL}" = "kde" ]; then
check_install "kde4-filesystem"
fi

echo -n "Check for existing flash-player tarball \"${FLASHFILE}\" in current directory ..."
if [ -f ${FLASHFILE} ]; then
    print_okay
else
    print_missing
    echo "Download the flash-player tarball ..."
    curl -f -o "${FLASHFILE}" "${FLASHURL}"
    if [ $? -ne 0 ]; then
        print_failure
        exit 1
    fi
    print_okay
fi

echo -n "Compare SHA1 checksum of the flash-player tarball ..."
if [ "${FLASHSHA1}" = "`sha1sum ${FLASHFILE} | cut -f1 -d" "`" ]; then
    print_okay
else
    print_failure
    exit 1
fi

echo -n "Check for existing RPM spec tarball \"$(basename ${FLASHRPMSPEC})\" in current directory ..."
if [ -f "$(basename ${FLASHRPMSPEC})" ]; then
    print_okay
else
    print_missing
    echo "Download the RPM spec tarball \"$(basename ${FLASHRPMSPEC})\" ..."
    curl -f -o "$(basename ${FLASHRPMSPEC})" "${FLASHRPMSPEC}"
    if [ $? -ne 0 ]; then
        print_failure
        exit 1
    fi
    print_okay
fi

echo -n "Compare SHA1 checksum of the RPM spec tarball \"$(basename ${FLASHRPMSPEC})\" ..."
if [ "${FLASHRPMSPECSHA1}" = "`sha1sum $(basename ${FLASHRPMSPEC}) | 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 "Clean up the /usr/src/packages directory ..."
find /usr/src/packages/ -type f -print0 | xargs -r -0 rm
if [ $? -ne 0 ]; then
    echo -n -e "\n   Error: some files could not be deleted"
    print_failure
    exit 1
fi
print_okay

echo -e -n "Extract the RPM spec tarball to /usr/src/packages/SOURCES ...\n"
tar -C /usr/src/packages/SOURCES -xjvf $(basename ${FLASHRPMSPEC}) --strip 1 flash-player-spec
if [ $? -ne 0 ]; then
    echo -n -e "\n   Error: tarball could not be extracted"
    print_failure
    exit 1
fi
print_okay

echo -e -n "Move the RPM spec files to /usr/src/packages/SPECS ...\n"
mv -v /usr/src/packages/SOURCES/*.spec /usr/src/packages/SPECS
if [ $? -ne 0 ]; then
    echo -n -e "\n   Error: spec files could not be moved"
    print_failure
    exit 1
fi
print_okay

echo -e -n "Copy the flash-player tarball to /usr/src/packages/SOURCES ...\n"
cp -v ${FLASHFILE} /usr/src/packages/SOURCES
if [ $? -ne 0 ]; then
    echo -n -e "\n   Error: tarball could not be copied"
    print_failure
    exit 1
fi
print_okay

echo -e -n "Selected RPM spec file:\n   ${FLASHSPECFILE}\n"
pushd /usr/src/packages/SPECS
echo -n "Create the RPM package, please wait ..."
rpmbuild -bb ${FLASHSPECFILE} >/tmp/flash-player-build.log 2>&1
if [ $? -ne 0 ]; then
    echo -n -e "\n   Error: RPM package could not be created"
    print_failure
    exit 1
fi
print_okay
popd

echo -e -n "Move the RPM files to the current directory ...\n"
find /usr/src/packages/RPMS -type f -print0 | xargs -0 -r -I '{}' mv -v {} `pwd`
if [ $? -ne 0 ]; then
    echo -n -e "\n   Error: RPM packages could not be moved"
    print_failure
    exit 1
fi
print_okay

echo -n "Clean up the /usr/src/packages directory ..."
find /usr/src/packages/ -type f -print0 | xargs -r -0 rm -f
if [ $? -ne 0 ]; then
    echo -n -e "\n   Error: some files could not be deleted"
    print_failure
    exit 1
fi
print_okay


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

echo "Install the flash player packages now ..."
RPMPACKAGES="`find . -type f -iname "flash-player*.rpm"`"
zypper -v -n install ${RPMPACKAGES}
if [ $? -ne 0 ]; then
    echo -n "   Error: zypper could not install the flash-player packages"
    print_failure
    exit 1
fi
print_okay

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