#!/bin/bash

# This is LibreOffice build script of xzm module for Porteus
# Version 2026-04-10

# Copyright 2019 Blaze, Dankov, Russia
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 THE AUTHOR 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.

# root check
if [ `whoami` != "root" ]; then
    echo -e "\nOnly root can run this.\n"
    exit 1
fi

PRGNAM=${PRGNAM:-LibreOffice}
VERSION=${VERSION:-`curl -s http://download.documentfoundation.org/libreoffice/stable/ | grep -oP 'href="\K[0-9]+\.[0-9]+\.[0-9]+(?=/")' | sort -V | tail -n 1`}
ARCH=$( uname -m )
CWD=$(pwd)
TMPDIR=/tmp/portch
PKG=$TMPDIR/package-$PRGNAM
PKGINFO=$PKG/var/lib/pkgtools/packages
OUTPUT=${OUTPUT:-/tmp}
BOLD="\e[1m"; CYAN="\e[96m"; GREEN="\e[92m"; RED="\e[31m"; RESET="\e[0m"

cleanup(){
[ -d $TMPDIR ] && rm -rf $TMPDIR
[ -d $PKG ] && rm -rf $PKG
exit	
}

# Check if LO installed in the system
if [ -d "/opt/libreoffice*/program" ]; then
  MYVER=${MYVER:-`/opt/libreoffice*/program/soffice --version | awk '{print $2}' | sed 's/..$//'`}
fi

if [ "$MYVER" == "$VERSION" ]; then
    echo -e "You have the latest ${GREEN}$MYVER${RESET} version of $PRGNAM"
    exit
else
    read -p "$(echo -e Do you want to build $PRGNAM ${GREEN}$VERSION${RESET} xzm module? [y/n])" -n 1 -r -s && echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo "We continue the execution of the $0 script" &>/dev/null
        else
        exit
    fi
fi

rm -rf $PKG
mkdir -p $TMPDIR $PKG $OUTPUT
cd $TMPDIR

## functions to choose locale from a menu
# how to check supported languages of LO:
# curl -sv http://download.documentfoundation.org/libreoffice/stable/25.2.0/rpm/x86_64/ 2>/dev/null | awk '/langpack/' | cut -d'_' -f7 | cut -d'.' -f1 | sort -u | tr '\n' ' ' | fmt
array_menu(){
echo
echo "$1"
echo "$2"
select CHOICE in ${RESULT[@]}; do
	if [ -z "$CHOICE" ]; then
        CHOICE="en-US"
		echo "English locale chosen." && echo
			else
		echo -e "${BOLD}${CYAN}${CHOICE}${RESET} locale chosen"
	fi
	break
done
}

get_locale(){
# set locales in array
for a in ab af am ar as ast be bg bn bn-IN bo br brx bs ca ca-valencia ckb cs cy da de dgo dsb dz el en-GB en-US en-ZA eo es et eu fa fi fr fur fy ga gd gl gu gug he hi hr hsb hu hy id is it ja ka kab kk km kmr-Latn kn ko kok ks lb lo lt lv mai mk ml mn mni mr my nb ne nl nn nr nso oc om or pa-IN pl pt pt-BR ro ru rw sa-IN sat sat-Olck sd si sid sk sl sq sr sr-Latn ss st sv sw-TZ szl ta te tg th tl tn tr ts tt ug uk uz ve vec vi xh zh-CN zh-TW zu; do
	RESULT+=( $a )
done

array_menu "Choose a locale from the list." "All other locales will be removed." ${RESULT[@]}
unset RESULT
}

get_locale

# download LibreOffice
echo -e "\nDownloading LibreOffice"
wget -q --show-progress http://download.documentfoundation.org/libreoffice/stable/"$VERSION"/rpm/'x86_64'/LibreOffice\_"$VERSION"'_Linux_x86-64_'rpm.tar.gz
tar -xf LibreOffice_"$VERSION"'_Linux_x86-64_'rpm.tar.gz
rm -f LibreOffice_"$VERSION".*'_Linux_x86-64_'rpm/RPMS/libreoffice*.*-dict-{es,fr}-*.rpm
mv LibreOffice_"$VERSION".*'_Linux_x86-64_'rpm/RPMS/* $PKG
rm -rf LibreOffice_"$VERSION".*'_Linux_x86-64_'rpm
rm -f LibreOffice_"$VERSION"'_Linux_x86-64_'rpm.tar.gz

# download langpack and helppack
if [ "${CHOICE}" != 'en-US' ]; then
    # download langpack
    echo -e "\nDownloading ${BOLD}${CYAN}${CHOICE}${RESET} langpack"
    wget -q --show-progress http://download.documentfoundation.org/libreoffice/stable/"$VERSION"/rpm/'x86_64'/LibreOffice\_"$VERSION"'_Linux_x86-64_rpm_langpack_'"${CHOICE}".tar.gz
    tar -xf LibreOffice_"$VERSION"'_Linux_x86-64_rpm_langpack_'"${CHOICE}".tar.gz
    mv LibreOffice_"$VERSION".*'_Linux_x86-64_rpm_langpack_'"${CHOICE}"/RPMS/* $PKG
    rm -rf LibreOffice_"$VERSION".*'_Linux_x86-64_rpm_langpack_'"${CHOICE}"
    rm -f LibreOffice_"$VERSION"'_Linux_x86-64_rpm_langpack_'"${CHOICE}".tar.gz
    # download helppack
    echo -e "\nDownloading ${BOLD}${CYAN}${CHOICE}${RESET} helppack"
    wget -q --show-progress http://download.documentfoundation.org/libreoffice/stable/"$VERSION"/rpm/'x86_64'/LibreOffice\_"$VERSION"'_Linux_x86-64_rpm_helppack_'"${CHOICE}".tar.gz
    tar -xf LibreOffice_"$VERSION"'_Linux_x86-64_rpm_helppack_'"${CHOICE}".tar.gz
    mv LibreOffice_"$VERSION".*'_Linux_x86-64_rpm_helppack_'"${CHOICE}"/RPMS/* $PKG
    rm -rf LibreOffice_"$VERSION".*'_Linux_x86-64_rpm_helppack_'"${CHOICE}"
    rm -f LibreOffice_"$VERSION"'_Linux_x86-64_rpm_helppack_'"${CHOICE}".tar.gz
else
    echo "English locale chosen." &>/dev/null
fi

# extract all rpm
echo -e "\nBuilding of $OUTPUT/$PRGNAM-$VERSION-$ARCH-${CHOICE}.xzm module"
cd $PKG
find . -name "*.rpm" | xargs -I {} sh -c "rpm2cpio {} | cpio -idm --quiet"
rm -f *.rpm

# cleanup
rm -rf $PKG/opt/libreoffice*.*/{readmes,CREDITS.fodt,LICENSE,LICENSE.fodt,LICENSE.html,NOTICE}
find $PKG/opt/libreoffice*.*/share/extensions/wiki-publisher -maxdepth 1 -type f | grep -Ev "description-en-US.txt|description-${CHOICE}.txt" | xargs -i rm -rf {}
find $PKG/opt/libreoffice*.*/share/extensions/wiki-publisher/help -maxdepth 1 -type f ! -name "en-US*" ! -name "${CHOICE}" | xargs -i rm -rf {}
find $PKG/opt/libreoffice*.*/share/extensions/wiki-publisher/help -maxdepth 1 -type d ! -name 'help' | grep -Ev "en-US|${CHOICE}" | xargs -i rm -rf {}
rm -rf $PKG/opt/libreoffice*.*/share/extensions/wiki-publisher/license
rm -rf $PKG/opt/libreoffice*.*/share/extensions/dict-en/WordNet_license.txt
find $PKG/opt/libreoffice*.*/share/extensions/nlpsolver -maxdepth 1 -type f | grep -Ev "description-en-US.txt|description-${CHOICE}.txt" | xargs -i rm -rf {}
find $PKG/opt/libreoffice*.*/share/extensions/nlpsolver/help -maxdepth 1 -type f ! -name "en-US*" ! -name "${CHOICE}" | xargs -i rm -rf {}
find $PKG/opt/libreoffice*.*/share/extensions/nlpsolver/help -maxdepth 1 -type d ! -name 'help' | grep -Ev "en-US|${CHOICE}" | xargs -i rm -rf {}
find ${PKG} -type f -iname "README*" -delete
find ${PKG} -type f -iname "LICENSE*" -delete

# fix of double menu entries
find $PKG/usr/share/applications/ -name *.desktop -delete
mv -f $PKG/opt/libreoffice*.*/share/xdg/*.desktop $PKG/usr/share/applications

# remove MIME types for txt files
sed -i 's|text/plain;||' $PKG/usr/share/applications/writer.desktop

# if you use official LibreOffice 6.1.x (or higher) rpm.tar.gz package -
# need to drop avahi and wayland dependences.

# set SAL_USE_VCLPLUGIN=gtk
LO=$(find $PKG/opt/libreoffice*/program -name soffice | awk 'NR==1 {print $0}')
sed -i -e '/^#\ restore/i# Prefer GTK2\nexport SAL_USE_VCLPLUGIN=${SAL_USE_VCLPLUGIN:-gtk}\n' $LO

# built two dummy/empty libraries (need for run LO Impress)
# for Porteus 5.1 or higher these steps are not needed
if [ ! -f "/usr/sbin/avahi-daemon" ]; then
    cd $(echo $LO | sed 's|soffice||')
    gcc -shared -o libavahi-client.so.3 -x c - < /dev/null
    gcc -shared -o libavahi-common.so.3 -x c - < /dev/null
    unset LO
else
    unset LO
fi

### fake Slackware type package info: super dumb version
mkdir -p $PKGINFO
echo "PACKAGE NAME: $PRGNAM-$VERSION-$ARCH-$CHOICE" > $PKGINFO/$PRGNAM-$VERSION-$ARCH-$CHOICE

cat >> $PKGINFO/$PRGNAM-$VERSION-$ARCH-$CHOICE << EOM
PACKAGE DESCRIPTION:
libreoffice: libreoffice (free office suite)
libreoffice:
libreoffice: LibreOffice is an Open Source, community-developed, office
libreoffice: productivity suite.  It includes key desktop applications,
libreoffice: such as a word processor, spreadsheet, presentation manager,
libreoffice: formula editor and drawing program, with a user interface and
libreoffice: feature set similar to other office suites.  LibreOffice also
libreoffice: works transparently with a variety of file formats, including
libreoffice: Microsoft Office File Formats.  
libreoffice:
libreoffice: libreoffice home: http://www.documentfoundation.org/
FILE LIST:
EOM

find * | grep -v var >> $PKGINFO/$PRGNAM-$VERSION-$ARCH-$CHOICE

# building xzm module
dir2xzm $PKG $OUTPUT/$PRGNAM-$VERSION-$ARCH-${CHOICE}.xzm
rm -rf $PKG

# check on LO xzm file exists in /tmp
if [ -f "$OUTPUT/$PRGNAM-$VERSION-$ARCH-${CHOICE}.xzm" ]; then
    echo -e "\n${BOLD}Your $PRGNAM module is at: ${GREEN}${BOLD}$OUTPUT/$PRGNAM-$VERSION-$ARCH-${CHOICE}.xzm${RESET}\n${BOLD}Please move it to your modules folder to survive a reboot.${RESET}\n"
else
    echo -e "\n${RED}${BOLD}Faile. Your $PRGNAM module is not built.${RESET}\n"
fi
cleanup
