#!/bin/bash

# This is MAX update script for Porteus
# Version 2026-03-31

# Copyright 2026-2035, 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:-max}
BUILD=${BUILD:-1}
ARCH=$( uname -m )
VERSION=$(curl -s "https://aur.archlinux.org/cgit/aur.git/plain/PKGBUILD?h=max-bin" | grep -Po '(?<=pkgver=)[\d.]+')
SOURCE=$(echo https://download.max.ru/linux/rpm/el/9/x86_64/MAX-${VERSION}.rpm)
BOLD=${BOLD:-"\e[1m"}
CYAN=${CYAN:-"\e[96m"}
GREEN=${GREEN:-"\e[92m"}
RED=${RED:-"\e[31m"}
RESET=${RESET:-"\e[0m"}
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	
}

# check if max installed in the system
if [[ -f "/opt/$PRGNAM/bin/${PRGNAM}" ]]; then
    MYVER=${MYVER:-`basename /var/lib/pkgtools/packages/max* | cut -d'-' -f2`}
fi

if [ "$MYVER" == "$VERSION" ]; then
    echo -e "You have the latest ${GREEN}$MYVER${RESET} version of $PRGNAM messenger."
    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/opt
cd $PKG

# download and extract max
echo -e "\nDownloading ${CYAN}${BOLD}${PRGNAM}-${VERSION}${RESET}"
wget -q --show-progress "$SOURCE"
rpm2cpio MAX-${VERSION}.rpm | cpio -idmv &>/dev/null
rm -rf *.rpm $PKG/usr/lib
mv $PKG/usr/share/max $PKG/opt/max

chown -R root:root .
chmod -R 755 $PKG
find $PKG -type f -not -name "*.so*" -exec chmod 644 {} +
find $PKG/usr/bin $PKG/opt/max -type f -exec chmod +x {} +

# clean and strip
rm -rf $PKG/opt/max/bin/max-service/{plugins/{egldeviceintegrations,qmltooling},qml/QtQuick/Controls/{FluentWinUI3,Imagine,Universal}}
rm -f $PKG/opt/max/bin/max-service/plugins/imageformats/{libqicns.so,libqtga.so,libqtiff.so,libqwbmp.so}
rm -rf $PKG/opt/max/{lib,lib64}/{*-gdb.py,libQt6FFmpegStub-*.so,libgcc_s.so*,libstdc++.modules.json,libstdc++.so*,pkgconfig}
rm -f $PKG/opt/max/bin/crashpad_handler
find $PKG/opt/max/bin/max-service/lib64 -type l -delete
find $PKG/opt/max -type f -name "*.so*" -exec strip --strip-unneeded {} + 2>/dev/null
strip --strip-unneeded $PKG/opt/max/bin/max 2>/dev/null
strip --strip-unneeded $PKG/opt/max/bin/max-service/bin/max-service 2>/dev/null
find $PKG/opt/max -type d -empty -delete

# create a symlink at MAX to usr/bin
ln -sf /opt/$PRGNAM/bin/${PRGNAM} $PKG/usr/bin

sed -i 's|/usr/share/max|/opt/max|' $PKG/usr/share/applications/max.desktop

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

cat >> $PKGINFO/$PRGNAM-$VERSION-$ARCH << EOM
PACKAGE DESCRIPTION:
max: max (messaging app)
max:
max: max is a cloud-based mobile and desktop messaging app
max: with a focus on security and speed.
max:
max: https://max.ru/
max:
FILE LIST:
EOM

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

# Auto-detect Desktop Environment (for su/root cases)
if [ -z "$XDG_CURRENT_DESKTOP" ]; then
    if pgrep -x "cinnamon" > /dev/null; then XDG_CURRENT_DESKTOP="X-Cinnamon"
    elif pgrep -x "cosmic-session" > /dev/null; then XDG_CURRENT_DESKTOP="COSMIC"
    elif pgrep -x "gnome-session|gnome-shell|mutter" > /dev/null; then XDG_CURRENT_DESKTOP="GNOME"
    elif pgrep -x "ksmserver|plasmashell|kwin_wayland" > /dev/null; then XDG_CURRENT_DESKTOP="KDE"
    elif pgrep -x "lxsession" > /dev/null; then XDG_CURRENT_DESKTOP="LXDE"
    elif pgrep -x "lxqt-session" > /dev/null; then XDG_CURRENT_DESKTOP="LXQt"
    elif pgrep -x "mate-session" > /dev/null; then XDG_CURRENT_DESKTOP="MATE"
    elif pgrep -x "openbox" > /dev/null; then XDG_CURRENT_DESKTOP="openbox"
    elif pgrep -x "xfce4-session" > /dev/null; then XDG_CURRENT_DESKTOP="XFCE"
    fi
fi
export XDG_CURRENT_DESKTOP

# Downloading dependencies libappindicator and libindicator for tray icon support
if [[ "${XDG_CURRENT_DESKTOP,,}" == "gnome" || \
      "${XDG_CURRENT_DESKTOP,,}" == "kde"   || \
      "${XDG_CURRENT_DESKTOP,,}" == "lxqt" ]]; then
    
    echo -e "\nDownloading dependencies for ${BOLD}$PRGNAM-$VERSION-$ARCH${RESET}"
    rm -f "${OUTPUT}"/*.txz
    getpkg -q libappindicator libindicator
    
    find "${OUTPUT}" -type f -name "*.txz" | sort | while read -r pkg_file; do
        ROOT="$PKG" installpkg "$pkg_file" >/dev/null
    done
    
    rm -f "${OUTPUT}"/*.txz
fi

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

# check on max xzm file exists in /tmp
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}Faile. Your $PRGNAM module is not built.${RESET}\n"
fi
cleanup
