#!/bin/bash

# This is SabyDesktop 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:-sabydesktop}
BUILD=${BUILD:-1}
RPMBUILD=${RPMBUILD:-0}
ARCH=$( uname -m )

if [ "$ARCH" != "x86_64" ]; then
    echo -e "\nThis plugin is only available for x86_64 architecture.\n"
    exit 1
fi

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	
}

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

# Fetch latest versions from Saby update server
echo -e "\nFetching latest versions from Saby update server..."

VERSION=$(wget -qO- "https://update.saby.ru/SabyDesktop/master/linux/version.txt" 2>/dev/null | tr -d '\r')
VER_NMH=$(wget -qO- "https://update.saby.ru/NmhTransport/master/linux/version.txt" 2>/dev/null | tr -d '\r')
VER_CENTER=$(wget -qO- "https://update.saby.ru/SabyCenter/master/linux/version.txt" 2>/dev/null | tr -d '\r')

# Abort script if versions cannot be detected
if [ -z "$VERSION" ] || [ -z "$VER_NMH" ] || [ -z "$VER_CENTER" ]; then
    echo -e "${RED}${BOLD}Error: Failed to detect latest versions from Saby server. Check your internet connection.${RESET}"
    cleanup
fi

echo -e "SabyDesktop version detected: ${GREEN}${BOLD}${VERSION}${RESET}"
echo -e "NmhTransport version detected: ${GREEN}${BOLD}${VER_NMH}${RESET}"
echo -e "SabyCenter version detected: ${GREEN}${BOLD}${VER_CENTER}${RESET}"

SOURCE_SABY="https://update.saby.ru/SabyDesktop/${VERSION}/linux/deb_repo/saby.deb"
SOURCE_NMH="https://update.saby.ru/NmhTransport/${VER_NMH}/linux/deb_repo/nmh-transport.deb"
SOURCE_CENTER="https://update.saby.ru/SabyCenter/${VER_CENTER}/linux/deb_repo/sabycenter.deb"

# download sabydesktop deb packages
echo -e "\nDownloading ${CYAN}${BOLD}${PRGNAM}${RESET} components..."
wget -q --show-progress "$SOURCE_SABY" -O saby.deb
wget -q --show-progress "$SOURCE_NMH" -O nmh-transport.deb
wget -q --show-progress "$SOURCE_CENTER" -O sabycenter.deb

# check if sabydesktop is installed in the system
if ls /var/lib/pkgtools/packages/sabydesktop-* 1> /dev/null 2>&1; then
  MYVER=${MYVER:-`ls /var/lib/pkgtools/packages/sabydesktop-* 2>/dev/null | head -n 1 | xargs basename | sed 's/sabydesktop-//' | cut -d'-' -f1`}
fi

if [ "$MYVER" == "$VERSION" ]; then
    echo -e "You have the latest ${GREEN}$MYVER${RESET} version of $PRGNAM"
    sleep 5
    cleanup
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
        cleanup
    fi
fi

# extract deb packages directly into the package directory
mkdir -p deb_tmp
cd deb_tmp

for DEB_FILE in ../saby.deb ../nmh-transport.deb ../sabycenter.deb; do
    ar x $DEB_FILE
    DATA_FILE=$(ls data.tar.gz data.tar.xz data.tar.zst 2>/dev/null | head -n 1)
    if [ -z "$DATA_FILE" ]; then
        echo -e "${RED}Failed to find data archive in $DEB_FILE.${RESET}"
        cleanup
    fi
    tar xf $DATA_FILE -C $PKG
    rm -f control.tar.* data.tar.* debian-binary
done

cd ..
rm -rf deb_tmp

cd $PKG

# move files from temporary directories to their final locations
if [ -d "opt/Tensor/Saby/temp_saby" ]; then
    cp -a opt/Tensor/Saby/temp_saby/. opt/Tensor/Saby/
    rm -rf opt/Tensor/Saby/temp_saby
fi

if [ -d "opt/Tensor/Saby Center/temp_sabycenter" ]; then
    mkdir -p "opt/Tensor/Saby Center"
    cp -a "opt/Tensor/Saby Center/temp_sabycenter/." "opt/Tensor/Saby Center/"
    rm -rf "opt/Tensor/Saby Center/temp_sabycenter"
fi

if [ -d "opt/nmh-transport/temp_nmh" ]; then
    mkdir -p "opt/nmh-transport"
    cp -a opt/nmh-transport/temp_nmh/. opt/nmh-transport/
    rm -rf opt/nmh-transport/temp_nmh
fi

# create integrity marker, Saby refuses to launch if this file is missing
VER_DIR=$(find opt/Tensor/Saby -maxdepth 1 -type d -regextype posix-extended -regex '.*/[0-9]+\.[0-9]+\.[0-9]+' 2>/dev/null | sort -V | tail -n1)
if [ -n "$VER_DIR" ]; then
    touch "$VER_DIR/integrity.checked"
else
    echo -e "${RED}Warning: Version directory not found, integrity.checked marker was not created.${RESET}"
fi

# create .desktop entry
mkdir -p usr/share/applications
cat > usr/share/applications/sabydesktop.desktop << EOF
[Desktop Entry]
Name=SabyDesktop (СБИС)
Comment=Saby applications, including saby-plugin, provides access to SBIS services and electronic signatures.
Exec=/opt/Tensor/Saby/saby
Icon=/opt/Tensor/Saby/icons/default_dark.png
Terminal=false
Type=Application
Categories=Office;Network;
EOF

chown -R root:root .
find -L . \
 \( -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 {} \;

# strip binaries to reduce module size
find . -print0 | xargs -0 file | grep -e "executable" -e "shared object" | grep ELF \
  | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null || true

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

cat >> $PKGINFO/$PRGNAM-$VERSION-$ARCH << EOM
PACKAGE DESCRIPTION:
sabydesktop: SabyDesktop (SBIS Plugin replacement) provides access to 
sabydesktop: SBIS services, electronic signatures, and document management.
sabydesktop:
sabydesktop: https://saby.ru/
sabydesktop:
FILE LIST:
EOM

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

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

# check if sabydesktop xzm file exists
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
