#!/bin/bash

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

# 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:-rustdesk}
BUILD=${BUILD:-1}
RPMBUILD=${RPMBUILD:-0}
ARCH=$( uname -m )
VERSION=$(lynx -head -dump "https://github.com/rustdesk/rustdesk/releases/latest" | grep Location | grep -o "[0-9].*$")
SOURCE=$(echo https://github.com/rustdesk/rustdesk/releases/download/${VERSION}/${PRGNAM}-${VERSION}-${RPMBUILD}.${ARCH}.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 rustdesk installed in the system
if [[ -f "/usr/bin/rustdesk" ]]; then
  MYVER=${MYVER:-`rustdesk --version`}
fi

if [ "$MYVER" == "$VERSION" ]; 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
cd $PKG

# download rustdesk
echo -e "\nDownloading ${CYAN}${BOLD}${PRGNAM}-${VERSION}${RESET}"
wget -q --show-progress "$SOURCE"
rpm2cpio ${PRGNAM}-${VERSION}-${RPMBUILD}.${ARCH}.rpm | cpio -idmv &>/dev/null
rm -f *.rpm

# install desktop entry
mkdir -p $PKG/opt/rustdesk $PKG/usr/bin $PKG/usr/share/applications
cp -r $PKG/usr/share/rustdesk/{data,lib,rustdesk} $PKG/opt/rustdesk/
( cd usr/bin ; ln -sf /opt/rustdesk/rustdesk rustdesk )
( cp usr/share/rustdesk/files/rustdesk.desktop usr/share/applications/ )

# add Russian description
sed -i '/Comment=Remote Desktop/a\Comment[ru]=Удаленный рабочий стол' $PKG/usr/share/applications/rustdesk.desktop

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

# create rc.service in Slackware BSD style
mkdir -p $PKG/etc/rc.d
wget -q -P $PKG/etc/rc.d https://slackbuilds.org/slackbuilds/15.0/network/rustdesk/rc.rustdesk

# 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

# xdotool (dep of rustdesk)
if [[ "${XDG_CURRENT_DESKTOP,,}" == "x-cinnamon" ]]; then
    ( mkdir -p "$PKG/usr/lib64"; cd "$PKG/usr/lib64"; ln -sf libxdo.so.4 libxdo.so.3 )

elif [[ "${XDG_CURRENT_DESKTOP,,}" == "gnome"   || \
        "${XDG_CURRENT_DESKTOP,,}" == "kde"     || \
        "${XDG_CURRENT_DESKTOP,,}" == "lxde"    || \
        "${XDG_CURRENT_DESKTOP,,}" == "lxqt"    || \
        "${XDG_CURRENT_DESKTOP,,}" == "mate"    || \
        "${XDG_CURRENT_DESKTOP,,}" == "xfce"    || \
        "${XDG_CURRENT_DESKTOP,,}" == "openbox" || \
        "${XDG_DESKTOP_SESSION,,}" == "openbox" ]]; then
    
    XDOTOOLVER=$(lynx --source "https://slackware.uk/csb/current/x86_64/" | grep -oP "(xdotool-)[^\"' ]+\.txz" | head -n1)
    XDOTOOL="https://slackware.uk/csb/current/x86_64/${XDOTOOLVER}"
    
    echo -e "\nDownloading ${CYAN}${BOLD}${XDOTOOLVER}${RESET} (dependency of rustdesk)"
    wget -q --show-progress "$XDOTOOL"
    
    tar -xf "${XDOTOOLVER}" --wildcards 'usr/lib64/libxdo*'
    
    LIBXDO=$(cd "$PKG/usr/lib64" && ls -1 | grep libxdo | head -n1)
    ( cd "$PKG/usr/lib64"; ln -sf "$LIBXDO" libxdo.so; ln -sf "$LIBXDO" libxdo.so.3 )
    
    rm -f "$PKG/${XDOTOOLVER}"
fi

# cleanup
rm -rf $PKG/usr/share/rustdesk

### 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:
rustdesk: rustdesk (open source remote control)
rustdesk:
rustdesk: RustDesk is a full-featured open source remote control
rustdesk: alternative for self-hosting and security with minimal
rustdesk: configuration.
rustdesk:
rustdesk: https://rustdesk.com/
rustdesk:
FILE LIST:
EOM

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

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

# check on rustdesk 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-x86_64-${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
