#!/bin/bash

# This is WPS Office build script for Porteus
# Version 2026-08-17

# Copyright 2023-2030, 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 "\nYou need to be root to run this script.\n"
    exit 1
fi

PRGNAM=${PRGNAM:-wps-office}
BUILD=${BUILD:-1}
RPMBUILD=${RPMBUILD:-0}
ARCH=$(uname -m)

# WPS Office is currently only available for 64-bit architecture
if [ "$ARCH" != "x86_64" ]; then
    echo -e "\n$PRGNAM is only available for x86_64 architecture.\n"
    exit 1
fi

# Automatically fetch the latest version and download URL from SlackBuilds.org repository
SBO_INFO_URL="https://slackbuilds.org/slackbuilds/15.0/office/wps-office/wps-office.info"
VERSION=$(wget -qO- "$SBO_INFO_URL" | grep '^VERSION=' | head -n 1 | cut -d'"' -f2)
SOURCE=$(wget -qO- "$SBO_INFO_URL" | grep '^DOWNLOAD_x86_64=' | cut -d'"' -f2)

# Terminate execution if version or source URL cannot be determined
if [ -z "$VERSION" ] || [ -z "$SOURCE" ]; then
    echo -e "\n${RED}${BOLD}Failed to determine the latest version or download URL for $PRGNAM.${RESET}"
    echo -e "${RED}Please check your internet connection or SBO repository status.${RESET}\n"
    exit 1
fi

# Remove .XA suffix for version comparison if present
CURRENT_VER=$(echo "$VERSION" | sed 's/\.XA$//')

TICON='https://slackbuilds.org/slackbuilds/15.0/office/wps-office/wps-office.png'
BOLD=${BOLD:-"\e[1m"}
CYAN=${CYAN:-"\e[96m"}
GREEN=${GREEN:-"\e[92m"}
RED=${RED:-"\e[31m"}
RESET=${RESET:-"\e[0m"}

log()   { echo -e "\n$BOLD$CYAN$*$RESET"; }
info()  { echo -e "$GREEN$*$RESET"; }
warn()  { echo -e "$RED$BOLD$*$RESET"; }

CWD=$(pwd)
TMPDIR=/tmp/portch
PKG=$TMPDIR/package-$PRGNAM
PKGINFO=$PKG/var/lib/pkgtools/packages
OUTPUT=${OUTPUT:-/tmp}

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

setup_locale(){
    # WPS Office stores its language packs in the mui directory
    local ldir="$PKG/opt/kingsoft/wps-office/office6/mui"
    [ -d "$ldir" ] || return 0

    log "WPS Office locale setup"

    local locales=($(ls "$ldir" 2>/dev/null | sort))
    local count=${#locales[@]}
    [ $count -eq 0 ] && { warn "no locales found"; return 0; }

    echo "Available locales ($count):"
    local i=1
    for loc in "${locales[@]}"; do
        printf "  %2d) %-10s" "$i" "$loc"
        [ $((i % 5)) -eq 0 ] && echo
        i=$((i + 1))
    done
    echo

    local choice=""
    while true; do
        echo
        read -p "Locale number to keep (English always kept) [1-$count, Enter=English only]: " choice

        if [ -z "$choice" ]; then
            cd "$ldir"
            for loc in *; do
                case "$loc" in en_US|en|en_*) ;; *) rm -rf "$loc" ;; esac
            done
            cd "$TMPDIR"
            info "only English kept"
            return 0
        fi

        if [[ "$choice" =~ ^[0-9]+$ ]] && [ "$choice" -ge 1 ] && [ "$choice" -le "$count" ]; then
            break
        fi

        warn "invalid input, try again"
    done

    local target="${locales[$((choice - 1))]}"
    log "Removing all locales except English and $target..."
    cd "$ldir"
    for loc in *; do
        case "$loc" in en_US|en|en_*|$target) ;; *) rm -rf "$loc" ;; esac
    done
    cd "$TMPDIR"
    info "kept: en + $target"
}

# Check if wps-office is installed in the system
if [[ -f "/usr/bin/wps" ]] || [[ -d "/opt/kingsoft/wps-office" ]]; then
  INSTALLED_PKG=$(ls /var/lib/pkgtools/packages/wps-office* 2>/dev/null | head -n 1)
  if [ -n "$INSTALLED_PKG" ]; then
      # Extract version (3rd field if name is wps-office-ver-arch) and remove .XA
      MYVER=$(basename "$INSTALLED_PKG" | cut -d'-' -f3 | sed 's/\.XA$//')
  fi
fi

if [ -n "$MYVER" ] && [ "$MYVER" == "$CURRENT_VER" ]; then
    echo -e "You have the latest ${GREEN}$MYVER${RESET} version of $PRGNAM"
    sleep 5
    exit
else
    read -p "$(echo -e "Would you like 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/usr/bin" "$PKG/usr/share/applications" "$PKG/usr/share/pixmaps"
cd "$TMPDIR"

echo -e "\nDownloading ${CYAN}${BOLD}${PRGNAM}-${VERSION}${RESET}"
wget -q --show-progress "$SOURCE" -O "${PRGNAM}.deb"

# Verify downloaded file
if ! file "${PRGNAM}.deb" | grep -q "Debian binary package"; then
    warn "Downloaded file is not a valid Debian package."
    cleanup
fi

echo -e "\nExtracting ${CYAN}${BOLD}${PRGNAM}-${VERSION}${RESET}"
# Clean up any old extracted files
rm -f data.tar.* control.tar.* debian-binary

# Extract the deb package (ar extracts control.tar, data.tar, and debian-binary)
ar x "${PRGNAM}.deb"

# Find the data archive (could be data.tar.xz, data.tar.gz, or data.tar.zst depending on the package version)
DATA_ARCHIVE=$(ls data.tar.* 2>/dev/null | head -n 1)
if [ -z "$DATA_ARCHIVE" ]; then
    warn "Failed to find data archive in the downloaded deb package."
    cleanup
fi

# Extract the filesystem structure from the deb package
tar xf "$DATA_ARCHIVE"

SRCDIR=.
cd "$SRCDIR"
chown -R root:root opt usr 2>/dev/null || true
find -L opt usr \
 \( -perm 777 -o -perm 775 -o -perm 750 -o -perm 711 -o -perm 555 \
  -o -perm 511 \) -exec chmod 755 {} \; -o \
 \( -perm 666 -o -perm 664 -o -perm 640 -o -perm 600 -o -perm 444 \
  -o -perm 440 -o -perm 400 \) -exec chmod 644 {} \; 2>/dev/null

# Move extracted directories to the package directory
cp -a opt "$PKG/" 2>/dev/null || true
cp -a usr "$PKG/" 2>/dev/null || true

find "$PKG" -print0 | xargs -0 file | grep -e "executable" -e "shared object" | grep ELF \
  | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null || true

setup_locale

# WPS provides its own desktop files, but we ensure a main launcher exists
cat > "$PKG/usr/share/applications/wps-office-porteus.desktop" << EOM
[Desktop Entry]
Name=WPS Office
GenericName=Office Suite
Comment=All-in-one office suite
Comment[ru]=Комплексный офисный пакет
Icon=wps-office
Exec=wps %f
TryExec=wps
Terminal=false
Type=Application
Categories=Office;
EOM

# Attempt to download the icon from SlackBuilds repository or fallback
wget -q -O "$PKG/usr/share/pixmaps/wps-office.png" "$TICON" || true

cd "$PKG"

mkdir -p "$PKGINFO"
echo "PACKAGE NAME: $PRGNAM-$VERSION-$ARCH" > "$PKGINFO/$PRGNAM-$VERSION-$ARCH"

cat >> "$PKGINFO/$PRGNAM-$VERSION-$ARCH" << EOM
PACKAGE DESCRIPTION:
wps-office: wps-office (office productivity suite)
wps-office:
wps-office: WPS Office is a lightweight, fast and feature-rich
wps-office: alternative to Microsoft Office.
wps-office:
wps-office: https://www.wps.com/
wps-office:
FILE LIST:
EOM

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

dir2xzm "$PKG" "$OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.xzm"

if [ -f "$OUTPUT/${PRGNAM}-${VERSION}-${ARCH}-${BUILD}.xzm" ]; then
    echo -e "\n${BOLD}Your $PRGNAM module is at: ${GREEN}${BOLD}$OUTPUT/$PRGNAM-$VERSION-${ARCH}-${BUILD}.xzm${RESET}\n${BOLD}Please copy it to your modules folder to survive a reboot.${RESET}\n"
else
    echo -e "\n${RED}${BOLD}Failed. Your $PRGNAM module is not built.${RESET}\n"
fi
cleanup
