#!/bin/zsh
# update.zsh - Install/Update KDE
#-------------------------------------------------------------------------------
# Copyright 2005-2017, Mindaugas N. <minde@posix.lt> - https://posix.lt
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#-------------------------------------------------------------------------------

# Exit immediately if a command exits with a non-zero status.
set -e

# Zsh module to arse date's
zmodload zsh/datetime

export KSC="/opt/kde"
export CCACHE_DIR="${KSC}/cache/compiler"
export CCACHE_SIZE="2G"
export DIR_BUILD="${KSC}/build"
export DIR_SOURCE="${KSC}/src"
export ECM_DIR="${DIR_BUILD}/build/share/ECM"
export CMAKE_PREFIX_PATH="$CMAKE_PREFIX_PATH:${DIR_BUILD}/build/lib/cmake"
SKIP_SECONDS=604800 # 7 days
INSYM=(
    "akonadiconsole"
    "akonadictl"
    "ark"
    "balooctl"
    "baloosearch"
    "balooshow"
    "contactthemeeditor"
    "contactprintthemeeditor"
    "headerthemeeditor"
    "dolphin"
    "kaddressbook"
    "kalarm"
    "kate"
    "keditbookmarks"
    "kcachegrind"
    "kdebugsettings"
    "kdebugdialog5"
    "kfind"
    "kmail"
    "konsole"
    "kontact"
    "krusader"
    "ksysguard"
    "ksystemlog"
    "kteatime"
    "ktimer"
    "ktnef"
    "massif-visualizer"
    "spectacle"
    "smb4k"
    "systemdgenie"
    "kleopatra"
    "krename"
    "tellico"
)

mkdir -p ${KSC}/{src,build}
mkdir -p ${KSC}/cache/{build,compiler}
mkdir -p ${HOME}/.bin

function prepare()
{
    [[ -d ${DIR_SOURCE}/${1} ]] && {
        [[ -d ${DIR_SOURCE}/${1}/build ]] && rm -rf ${DIR_SOURCE}/${1}/build
        cd ${DIR_SOURCE}/${1} && git pull
    } || {
        git clone https://anongit.kde.org/${1} ${DIR_SOURCE}/${1}
    }
    mkdir -p ${DIR_SOURCE}/${1}/build
    cd ${DIR_SOURCE}/${1}/build
}

# Configure
function configure()
{
    cmake \
        -DBUILD_TESTING:BOOL="0" \
        -DCMAKE_INSTALL_PREFIX:PATH=${DIR_BUILD} \
        ../
}

function build()
{
    make -j 2 # Do not use more than 2, can cause nervous build problems
    make install

    echo $EPOCHSECONDS > ${KSC}/cache/build/${1}.installed
}

function init()
{
    print "Initializing: ${1}"
    [[ -r ${KSC}/cache/build/${1}.installed ]] && {
        T=$(cat ${KSC}/cache/build/${1}.installed)
        [[ ${T} > ${SKIP_SECONDS} ]] && {
            prepare ${1}
            configure ${1}
            build ${1}
        } || {
            print "Skipping: ${1} updated at $(date -d @${T} '+%Y-%m-%d %H:%M:%S')"
        }
    } || {
        prepare ${1}
        configure ${1}
        build ${1}
    }
}

# Extra cmake modules
init "extra-cmake-modules"

# KArchive
init "karchive"

# KDocTools
init "kdoctools"

# KConfig
init "kconfig"

# KCoreAddons - Qt addon library with a collection of non-GUI utilities
init "kcoreaddons"

# KWindowSystem - Access to the windowing system
init "kwindowsystem"

# KCrash - Graceful handling of application crashes
init "kcrash"

# KDBusAddons - convenience classes for DBus
init "kdbusaddons"

# KI18n - KDE Gettext-based UI text internationalization
init "ki18n"

# KService - plugin framework for desktop services
init "kservice"

# Solid - desktop hardware abstraction
init "solid"

# KCodecs - string encoding library
init "kcodecs"

# KAuth - Execute actions as privileged user
init "kauth"

# KDE GUI Addons - Utilities for graphical user interfaces
init "kguiaddons"

# KWidgetsAddons - Large set of desktop widgets
init "kwidgetsaddons"

# KConfigWidgets - Widgets for configuration dialogs
init "kconfigwidgets"

# KItemViews - Set of item views extending the Qt model-view framework
init "kitemviews"

# KIconThemes - Icon GUI utilities
init "kiconthemes"

# KCompletion - Powerful completion framework, including completion-enabled lineedit and combobox.
init "kcompletion"

# Sonnet - Multi-language spell checker
init "sonnet"

## KTextWidgets - Text editing widgets
init "ktextwidgets"

# KGlobalAccel - Global desktop keyboard shortcuts
init "kglobalaccel"

# Attica - Open Collaboration Service client library
init "attica"

# KXMLGUI - Framework for managing menu and toolbar actions
init "kxmlgui"

# KBookmarks - Bookmarks management library
init "kbookmarks"

# KJobWidgets - Widgets for showing progress of asynchronous jobs
init "kjobwidgets"

# KNotification - Desktop notifications
init "knotifications"

# GpgME++ - C++ bindings/wrapper for gpgme
#init "gpgmepp" kleopatra fails to build

# KWallet Framework - Safe desktop-wide storage for passwords
# TODO: -DGpgmepp_DIR:PATH="/opt/kde/build/"
init "kwallet"

init "kjs"
init "khtml"

# KIO - Network transparent access to files and data
init "kio"
init "kio-extras"

# KInit - Helper library to speed up start of applications on KDE workspaces
init "kinit"

# KPackage Framework - Installation and loading of additional content (ex: scripts, images...) as packages.
init "kpackage"

# KDeclarative - Integration of QML and KDE work spaces
init "kdeclarative"

# KCMUtils - Utilities for KDE System Settings modules
init "kcmutils"

# KNewStuff - Framework for downloading and sharing additional application data
init "knewstuff"

# KParts - Plugin framework for user interface components
init "kparts"

# File manager
# TODO: init "krusader"

# Syntax Highlighting - Syntax highlighting engine for Kate syntax definitions
init "syntax-highlighting"

# KTextEditor - Full text editor component
init "ktexteditor"

# KItemModels - Set of item models extending the Qt model-view framework
init "kitemmodels"

# ThreadWeaver - Helper for multithreaded programming
init "threadweaver"

# Kate text editor
init "kate"

# Grantlee theme support
init "grantleetheme"

# KDesignerPlugin - Integrating KDE frameworks widgets with Qt Designer
init "kdesignerplugin"

# Akonadi - extensible cross-desktop storage service for PIM data
init "akonadi"

# KContact - This library provides vcard support
init "kcontacts"

# KMime - library for handling mail messages and newsgroup articles.
init "kmime"

# Akonadi Mime
init "akonadi-mime"

# Akonadi Contacts
init "akonadi-contacts"

# KIMAP - This library provides a job-based API for interacting with an IMAP4rev1 server.
init "kimap"

# Akonadi Notes
init "akonadi-notes"

# KEmoticons - Convert text emoticons to graphical emoticons
init "kemoticons"

# ???
init "kpimtextedit"

# Kleopatra is a GUI for GnuPG so it needs a working GnuPG setup.
init "libkleo"
init "kleopatra"

# KUnitConversion - Converting physical units
init "kunitconversion"

# KDED - Central daemon of KDE work spaces
init "kded"

# KDELibs 4 Support - Legacy support for kdelibs 4 compatibility
init "kdelibs4support"


# KCalCore - This library provides access to and handling of calendar data.
init "kcalcore"

# only works v16.04.3
# This module includes libraries that are central to the development and execution of a KDE-PIM application.
## DEPRECATED init "kdepimlibs"

# ???
init "kontactinterface"

# KActivities - Core components for the KDE Activity concept
init "kactivities"

# Plasma Framework - Foundational libraries, components, and tools of the Plasma workspaces
init "plasma-framework"

# KRunner - Framework for Plasma runners
init "krunner"

# ???
init "kldap"

# Akonadi search
init "akonadi-search"

# KDE PIM libraries
#LibkdepimConfig
init "libkdepim"

# ???
init "mailimporter"

# ???
init "kmailtransport"

# ???
#LibkdepimConfig
init "pimcommon"

# ???
init "kidentitymanagement"

# KCalUtils
init "kcalutils"

# ???
init "kdepim-apps-libs"


# Gravatar support
init "libgravatar"

# KMBox provides API to access emails in storages in the [MBox](https://tools.ietf.org/html/rfc4155) format
init "kmbox"

# messagelib
init "messagelib"

# ???
init "mailcommon"

# ???
init "kdiagram"

# library provides a C++ API that determines holiday and other
# special events for a geographical region.
init "kholidays"

# Akonadi Calendar
init "akonadi-calendar"

# Calendar Support library provides helper utilities for calendaring
init "calendarsupport"

# ???
init "eventviews"

# ???
init "incidenceeditor"

# ???
init "libksieve"

## ???
init "ktnef"

# C++ library that implements APIs for various Google services.
init "libkgapi"

# ???
init "kdepim-addons"

# Kontact
init "kontact"

# knotify config
init "knotifyconfig"

# KMail!
init "kmail"

# Configurator/manager for akonadi
init "akonadiconsole"

# Organizer
init "korganizer"

# address book
init "kaddressbook"

# ???
init "kross"

# ???
init "kmail-account-wizard"

# ???
# * PopplerQt5 (required version >= 0.12.1) , A PDF rendering library , <http://poppler.freedesktop.org> Support for PDF files
# * EPub , Ebook epub reader , <http://sourceforge.net/projects/ebook-tools> Support for epub metadata
init "kfilemetadata"

# ???
init "kidletime"

# ???
init "baloo"

# ???
init "baloo-widgets"

# To find out eiliskuma
init "dolphin"

# ???
init "dolphin-plugins"

# ???
init "ffmpegthumbs"

# ???
init "kdnssd"

# KDE's Terminal Emulator
init "kpty"

# Konsole
init "konsole"

# ark
init "ark"

# ???
init "kalarmcal"

# ???
init "kdepim-runtime"

# ???
init "kwalletmanager"


# Reikalingas KDecoration2Config.cmake...
#init "breeze"
#init "oxygen"

# Ikonos
init "breeze-icons"
init "oxygen-icons5"

# more stuff...
init "grantlee-editor"
init "kalarm"
init "kcachegrind"
init "kdebugsettings"
init "keditbookmarks"
init "kfilemetadata"
init "kidentitymanagement"
init "kmenuedit"
init "krename"
init "kfind"
init "libksysguard"
init "ksysguard"
init "ksystemlog"
init "kteatime"
init "ktimer"
init "massif-visualizer"
init "pim-data-exporter"
init "pim-storage-service-manager"
init "systemdgenie"
init "tellico"
init "yakuake"
init "zanshin"
init "spectacle"
init "smb4k"

for K in ${INSYM}; do
    ln -sf ${KSC}/run.zsh ${HOME}/.bin/${K}
done