#!/bin/bash

# Based on http://files.svenbrauch.de/kdevelop-linux/kdevelop-recipe-centos6.sh

# On Amazon AWS start an Amazon Linux instance (I used c4.2xlarge) and run:
# sudo yum -y install docker
# sudo service docker start
# sudo docker run -i -t scummos/centos6.8-qt5.7
# wget -c https://github.com/probonopd/AppImages/raw/master/recipes/kdevelop/Recipe
# bash -ex Recipe

# Halt on errors
set -e

# Be verbose
set -x

# Now we are inside CentOS 6
grep -r "CentOS release 6" /etc/redhat-release || exit 1

# Get helper functions
wget -q https://github.com/probonopd/AppImages/raw/master/functions.sh -O ./functions.sh
. ./functions.sh
rm -f functions.sh

git_pull_rebase_helper()
{
        git reset --hard
        git pull --rebase
}

yum -y install gettext perl-URI.noarch 

QTVERSION=5.7.0
QVERSION_SHORT=5.7
QTDIR=/usr/local/Qt-${QTVERSION}/

# qjsonparser, used to add metadata to the plugins needs to work in a en_US.UTF-8 environment. That's
# not always set correctly in CentOS 6.7
export LC_ALL=en_US.UTF-8
export LANG=en_us.UTF-8

# Determine which architecture should be built
if [[ "$(arch)" = "i686" || "$(arch)" = "x86_64" ]] ; then
  
else
  echo "Architecture could not be determined"
  exit 1
fi

export PATH=/opt/rh/python27/root/usr/bin/:$PATH
export LD_LIBRARY_PATH=/opt/rh/python27/root/usr/lib64:$LD_LIBRARY_PATH

# Make sure we build from the /, parts of this script depends on that. We also need to run as root...
cd  /

# Use the new compiler
. /opt/rh/devtoolset-4/enable

export CMAKE_PREFIX_PATH=$QTDIR:/app/share/llvm/

# if the library path doesn't point to our usr/lib, linking will be broken and we won't find all deps either
export LD_LIBRARY_PATH=/usr/lib64/:/usr/lib:/app/usr/lib:$QTDIR/lib/:/opt/python3.5/lib/:$LD_LIBRARY_PATH

# Workaround for: On CentOS 6, .pc files in /usr/lib/pkgconfig are not recognized
# However, this is where .pc files get installed when bulding libraries... (FIXME)
# I found this by comparing the output of librevenge's "make install" command
# between Ubuntu and CentOS 6
ln -sf /usr/share/pkgconfig /usr/lib/pkgconfig

# Get kdevplatform
if [ ! -d /kdevplatform ] ; then
	git clone --depth 1 http://anongit.kde.org/kdevplatform.git /kdevplatform
fi
cd /kdevplatform/
git_pull_rebase_helper
git checkout assistantpopup-ng

# Get kdevelop
if [ ! -d /kdevelop ] ; then
	git clone --depth 1 http://anongit.kde.org/kdevelop.git /kdevelop
fi
cd /kdevelop/
git_pull_rebase_helper
git checkout assistantpopup-ng

# Get kdev-python
if [ ! -d /kdev-python ] ; then
	git clone --depth 1 http://anongit.kde.org/kdev-python.git /kdev-python
fi
cd /kdev-python/
git_pull_rebase_helper

# Prepare the install location
rm -rf /app/ || true
mkdir -p /app/usr

export LLVM_ROOT=/opt/llvm/

# make sure lib and lib64 are the same thing
mkdir -p /app/usr/lib
cd  /app/usr
ln -s lib lib64

# start building the deps

function build_framework
{ (
    # errors fatal
    echo "Compiler version:" $(g++ --version)
    set -e

    SRC=/kf5
    BUILD=/kf5/build
    PREFIX=/app/usr/

    # framework
    FRAMEWORK=$1

    # clone if not there
    mkdir -p $SRC
    cd $SRC
    if ( test -d $FRAMEWORK )
    then
        echo "$FRAMEWORK already cloned"
        cd $FRAMEWORK
        git reset --hard
        git pull --rebase
        cd ..
    else
        git clone git://anongit.kde.org/$FRAMEWORK
    fi

    if [ "$FRAMEWORK" = "knotifications" ]; then
	cd $FRAMEWORK
        echo "patching knotifications"
	git reset --hard        
	cat > no_phonon.patch << EOF
diff --git a/CMakeLists.txt b/CMakeLists.txt
index b97425f..8f15f08 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -59,10 +59,10 @@ find_package(KF5Config ${KF5_DEP_VERSION} REQUIRED)
 find_package(KF5Codecs ${KF5_DEP_VERSION} REQUIRED)
 find_package(KF5CoreAddons ${KF5_DEP_VERSION} REQUIRED)
 
-find_package(Phonon4Qt5 4.6.60 REQUIRED NO_MODULE)
+find_package(Phonon4Qt5 4.6.60 NO_MODULE)
 set_package_properties(Phonon4Qt5 PROPERTIES
    DESCRIPTION "Qt-based audio library"
-   TYPE REQUIRED
+   TYPE OPTIONAL
    PURPOSE "Required to build audio notification support")
 if (Phonon4Qt5_FOUND)
   add_definitions(-DHAVE_PHONON4QT5)
EOF
	cat no_phonon.patch |patch -p1
	cd ..
    fi

    # create build dir
    mkdir -p $BUILD/$FRAMEWORK

    # go there
    cd $BUILD/$FRAMEWORK

    # cmake it
    cmake $SRC/$FRAMEWORK -DCMAKE_INSTALL_PREFIX:PATH=$PREFIX $2

    # make
    make -j16

    # install
    make install
) }

for FRAMEWORK in extra-cmake-modules kconfig kguiaddons ki18n kitemviews sonnet kwindowsystem kwidgetsaddons kcompletion kdbusaddons karchive kcoreaddons kjobwidgets kcrash kservice kcodecs kauth kconfigwidgets kiconthemes ktextwidgets  kglobalaccel kxmlgui kbookmarks solid kio kparts kitemmodels threadweaver attica knewstuff ktexteditor kpackage kdeclarative kcmutils knotifications knotifyconfig libkomparediff2 kdoctools ; do
  build_framework $FRAMEWORK
done
build_framework breeze-icons -DBINARY_ICONS_RESOURCE=1
    
cd ..

# Build KDevPlatform
mkdir -p /kdevplatform_build
cd /kdevplatform_build
cmake ../kdevplatform \
    -DCMAKE_INSTALL_PREFIX:PATH=/app/usr/ \
    -DCMAKE_BUILD_TYPE=RelWithDebInfo \
    -DPACKAGERS_BUILD=1 \
    -DBUILD_TESTING=FALSE
make -j16 install
# no idea why this is required but otherwise kdevelop picks it up and fails
rm -f /kdevplatform_build/KDevPlatformConfig.cmake

# Build KDevelop
mkdir -p /kdevelop_build
cd /kdevelop_build
cmake3 ../kdevelop \
    -DCMAKE_INSTALL_PREFIX:PATH=/app/usr/ \
    -DCMAKE_BUILD_TYPE=RelWithDebInfo \
    -DPACKAGERS_BUILD=1 \
    -DBUILD_TESTING=FALSE
make -j16 install
rm -f /kdevelop_build/KDevelopConfig.cmake

# for python
export PATH=/opt/python3.5/bin:$PATH
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH/app/usr/lib/
# Build kdev-python
mkdir -p /kdev-python_build
cd /kdev-python_build
cmake3 ../kdev-python \
    -DCMAKE_INSTALL_PREFIX:PATH=/app/usr/ \
    -DCMAKE_BUILD_TYPE=RelWithDebInfo \
    -DPACKAGERS_BUILD=1 \
    -DBUILD_TESTING=FALSE
make -j16 install

###############################################################
# Build complete, AppImage bundling begins here
###############################################################

cd /app

# FIXME: How to find out which subset of plugins is really needed? I used strace when running the binary
mkdir -p ./usr/lib/qt5/plugins/

PLUGINS=$(dirname $QTDIR/plugins/bearer)

cp -r $PLUGINS/{bearer,generic,imageformats,platforms,iconengines,platforminputcontexts,xcbglintegrations} ./usr/lib/qt5/plugins/
# cp -r $PLUGINS/platformthemes ./usr/lib/qt5/plugins/

cp -ru /usr/share/mime/* /app/usr/share/mime
update-mime-database /app/usr/share/mime/

mv ./usr/lib/plugins/* ./usr/lib/qt5/plugins/

copy_deps
mv usr/local/Qt-*/lib/* usr/lib
rm -rf usr/local/
mv lib64/* usr/lib/
rm -rf lib64/
mv ./opt/python3.5/lib/* usr/lib
mv ./opt/llvm/lib/* usr/lib
rm  -rf ./opt/
rm -rf app/

delete_blacklisted

# We don't bundle the developer stuff
rm -rf usr/include || true
rm -rf usr/lib/cmake || true
rm -rf usr/lib/pkgconfig || true
rm -rf usr/share/ECM/ || true
rm -rf usr/share/gettext || true
rm -rf usr/share/pkgconfig || true
rm -rf rm -rf ./usr/mkspecs/ || true
find . -name '*.a' -exec rm {} \;

strip -g $(find usr) || true

mv usr/lib/libexec/kf5/* /app/usr/bin/

cd /
if [ ! -d appimage-exec-wrapper ]; then
    git clone git://anongit.kde.org/scratch/brauch/appimage-exec-wrapper
fi;
cd /appimage-exec-wrapper/
make clean
make

cd /app
cp -v /appimage-exec-wrapper/exec.so exec_wrapper.so

cat > AppRun << EOF
#!/bin/bash

DIR="\`dirname \"\$0\"\`" 
DIR="\`( cd \"\$DIR\" && pwd )\`"
export APPDIR=\$DIR

export LD_PRELOAD=\$DIR/exec_wrapper.so

export APPIMAGE_ORIGINAL_QML2_IMPORT_PATH=\$QML2_IMPORT_PATH
export APPIMAGE_ORIGINAL_LD_LIBRARY_PATH=\$LD_LIBRARY_PATH
export APPIMAGE_ORIGINAL_QT_PLUGIN_PATH=\$QT_PLUGIN_PATH
export APPIMAGE_ORIGINAL_XDG_DATA_DIRS=\$XDG_DATA_DIRS
export APPIMAGE_ORIGINAL_PATH=\$PATH

export QML2_IMPORT_PATH=\$DIR/usr/lib/qml:\$QML2_IMPORT_PATH
export LD_LIBRARY_PATH=\$DIR/usr/lib/:\$LD_LIBRARY_PATH
export QT_PLUGIN_PATH=\$DIR/usr/lib/qt5/plugins/
export XDG_DATA_DIRS=\$DIR/usr/share/:\$XDG_DATA_DIRS
export PATH=\$DIR/usr/bin:\$PATH
export KDE_FORK_SLAVES=1

export APPIMAGE_STARTUP_QML2_IMPORT_PATH=\$QML2_IMPORT_PATH
export APPIMAGE_STARTUP_LD_LIBRARY_PATH=\$LD_LIBRARY_PATH
export APPIMAGE_STARTUP_QT_PLUGIN_PATH=\$QT_PLUGIN_PATH
export APPIMAGE_STARTUP_XDG_DATA_DIRS=\$XDG_DATA_DIRS
export APPIMAGE_STARTUP_PATH=\$PATH

kdevelop \$@
EOF
chmod +x AppRun

cp ./usr/share/applications/org.kde.kdevelop.desktop kdevelop.desktop
cp usr/share/icons/hicolor/256x256/apps/kdevelop.png .

# What is this and why wasn't it installed automatically?
mkdir -p usr/share/kdevelop/
cp /kf5/build/breeze-icons/icons/breeze-icons.rcc usr/share/kdevelop/icontheme.rcc

rm -Rf usr/share/icons # not needed because of the rcc
rm -f /appusr/bin/llvm*
rm -f usr/bin/clang*
rm -f usr/bin/opt
rm -f usr/bin/lli
rm -f usr/bin/sancov
rm -f usr/bin/cmake
rm -f usr/bin/python
rm -Rf usr/lib/pkgconfig
rm -Rf usr/share/man
rm -Rf usr/lib/python3.5/test
rm -Rf usr/lib/python3.5/__pycache__
rm -Rf usr/lib/libLTO.so
rm -f /app/usr/bin/llc
rm -f /app/usr/bin/bugpoint

# rm -Rf usr/lib/libxcb* # Don't do this, because then it will no longer run on Arch

# add that back in
cp /usr/lib64/libxcb-keysyms.so.1 usr/lib/

# TODO: Can we be sure about that? If yes, inform probono in order to add to the global blacklist
# rm -Rf /app/usr/lib/{libX11.so.6,libXau.so.6,libXext.so.6,libXi.so.6,libXxf86vm.so.1,libX11-xcb.so.1,libXdamage.so.1,libXfixes.so.3,libXrender.so.1}

APP=KDevelop
LOWERAPP=kdevelop

get_desktopintegration kdevelop

cd  /

# Build AppImageKit
if [ ! -d AppImageKit ] ; then
  git clone  --depth 1 https://github.com/probonopd/AppImageKit.git /AppImageKit
fi

cd /AppImageKit/
git_pull_rebase_helper
./build.sh

cd /

mkdir -p /$APP/$APP.AppDir
cd /$APP/

mv ../app/* $APP.AppDir/

VERSION="git"

mkdir -p /out
rm -rf /out/*
/AppImageKit/AppImageAssistant.AppDir/package KDevelop.AppDir/ /out/$APP-$VERSION-$ARCH.AppImage

transfer ../out/* # Upload to transfer.io for testing

# Try to power down Amazon AWS (no guarantees; need to check for yourself!)
grep -r compute.internal /etc/resolv.conf && halt

# Test the resulting AppImage on my local system
# sudo /tmp/*/union/AppImageKit/AppImageAssistant.AppDir/testappimage /isodevice/boot/iso/Fedora-Live-Workstation-x86_64-22-3.iso /tmp/*/union/Scribus.AppDir/

# Could not load plugin "KDevCMakeDocumentation" , it reported the error: "cmake is not installed" Disabling the plugin now.
# QSqlDatabase: QSQLITE driver not loaded
# QSqlDatabase: available drivers: 
# Couldn't setup QtHelp Collection file
# qrc:/qml/main.qml:21:1: module "QtQuick" is not installed
# welcomepage errors: (qrc:/qml/main.qml:21:1: module "QtQuick" is not installed)
# trying to load "/tmp/.mount_YPZnl1/usr/lib/qt5/plugins/kf5/kio/file.so" from "/tmp/.mount_YPZnl1/usr/lib/qt5/plugins/kf5/kio/file.so"
# called
# updating problem highlight
