#!/bin/bash

# This is Steam xzm builder for Porteus (with Proton-GE support)
# Version 2026-08-17
# Includes: Steam client bootstrap for Porteus

# 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

log() {
    echo -e "${GREEN}$1${RESET}"
}

warn() {
    echo -e "${RED}$1${RESET}"
}

setup_locale(){
    local ldir="$PKG/usr/lib/$PRGNAM/localization"
    [ -d "$ldir" ] || return 0

    log "Steam 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|en_*) ;; *) rm -rf "$loc" ;; esac
            done
            cd "$TMPDIR"
            log "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|en_*|$target) ;; *) rm -rf "$loc" ;; esac
    done
    cd "$TMPDIR"
    log "kept: en + $target"
}

cleanup_junk(){
    local sdir="$PKG/usr/lib/$PRGNAM"
    [ -d "$sdir" ] || return 0

    cd "$sdir"
    rm -rf COPYING Makefile README \
           bin_steamdeps.py steamdeps \
           buildutils \
           com.valvesoftware.Steam.metainfo.xml \
           debian \
           steam-beta.list steam-key.asc steam-stable.list steam.gpg \
           steam.6 \
           steam_subscriber_agreement.txt \
           subprojects \
           tests
    cd "$TMPDIR"
}

install_icons(){
    local sdir="$PKG/usr/lib/$PRGNAM"
    local idir="$sdir/icons"
    [ -d "$idir" ] || return 0

    mkdir -p $PKG/usr/share/icons/hicolor/{16x16,24x24,32x32,48x48,256x256}/apps
    mkdir -p $PKG/usr/share/pixmaps

    [ -f "$idir/16/steam.png" ]  && cp "$idir/16/steam.png"  $PKG/usr/share/icons/hicolor/16x16/apps/steam.png
    [ -f "$idir/24/steam.png" ]  && cp "$idir/24/steam.png"  $PKG/usr/share/icons/hicolor/24x24/apps/steam.png
    [ -f "$idir/32/steam.png" ]  && cp "$idir/32/steam.png"  $PKG/usr/share/icons/hicolor/32x32/apps/steam.png
    [ -f "$idir/48/steam.png" ]  && cp "$idir/48/steam.png"  $PKG/usr/share/icons/hicolor/48x48/apps/steam.png
    [ -f "$idir/256/steam.png" ] && cp "$idir/256/steam.png" $PKG/usr/share/icons/hicolor/256x256/apps/steam.png

    [ -f "$idir/48/steam.png" ] && cp "$idir/48/steam.png" $PKG/usr/share/pixmaps/steam.png

    rm -rf "$idir"
    cd "$TMPDIR"
}

install_desktop(){
    local src="$PKG/usr/lib/$PRGNAM/steam.desktop"
    local dst="$PKG/usr/share/applications/steam.desktop"

    if [ -f "$src" ]; then
        cp "$src" "$dst"
    else
        cat > "$dst" << EOM
[Desktop Entry]
Name=Steam
GenericName=Game Manager
GenericName[ru]=Менеджер игр
Comment=Application for managing and playing games on Steam
Comment[ru]=Приложение для игр и управления играми в Steam
Icon=/usr/share/pixmaps/steam.png
Exec=/usr/bin/steam %U
Terminal=false
Type=Application
Categories=Game;
EOM
        return
    fi

    # Remove all [Desktop Action ...] sections to simplify menu parsing
    sed -i '/^\[Desktop Action/,$d' "$dst"

    # Remove problematic fields that may break simple DE menus
    sed -i '/^MimeType=/d' "$dst"
    sed -i '/^Actions=/d' "$dst"
    sed -i '/^PrefersNonDefaultGPU=/d' "$dst"
    sed -i '/^X-KDE-RunOnDiscreteGpu=/d' "$dst"

    # Force absolute path for Icon (fixes missing icon in Porteus without cache update)
    sed -i 's|^Icon=.*|Icon=/usr/share/pixmaps/steam.png|' "$dst"

    # Force Exec path
    sed -i 's|^Exec=.*|Exec=/usr/bin/steam %U|' "$dst"

    # Simplify Categories to guarantee appearance in Games menu
    sed -i 's|^Categories=.*|Categories=Game;|' "$dst"

    # Add GenericName if missing
    if ! grep -q "^GenericName=" "$dst"; then
        sed -i '/^Name=Steam$/a GenericName=Game Manager\nGenericName[ru]=Менеджер игр' "$dst"
    fi

    rm -f "$PKG/usr/lib/$PRGNAM/steam.desktop"
}

PRGNAM=${PRGNAM:-steam}
SRCDIR=.
BUILD=${BUILD:-1}
ARCH=$( uname -m )
VERSION="latest"
SOURCE="https://repo.steampowered.com/steam/archive/stable/steam_latest-stable.tar.gz"
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	
}

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
    exit 0
fi

rm -rf $PKG
mkdir -p $TMPDIR $PKG/usr/bin $PKG/usr/lib/$PRGNAM $PKG/usr/share/applications $PKG/usr/share/pixmaps
cd $TMPDIR

wget -q --show-progress "$SOURCE"
tar xf steam_latest-stable.tar.gz 2>/dev/null

# detect source directory
if [ -d steam-launcher ]; then
    SRCDIR=steam-launcher
elif [ -d steam ]; then
    SRCDIR=steam
else
    SRCDIR=.
fi

# copy only the source directory contents, not the entire TMPDIR
cd $TMPDIR/$SRCDIR
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 {} \;

cp -a * $PKG/usr/lib/$PRGNAM
cd $TMPDIR

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

# install desktop file from source
install_desktop

# remove junk files
cleanup_junk

# install icons from source
install_icons

# create doinst.sh for icon cache update (useful if converted to txz)
create_doinst

# setup locale
setup_locale

# create a wrapper at steam to usr/bin
cat > $PKG/usr/bin/steam << 'EOM'
#!/bin/sh
export STEAM_RUNTIME=1
exec /usr/lib/steam/steam "$@"
EOM
chmod 755 $PKG/usr/bin/steam

cd $PKG

### 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:
steam: steam (game manager)
steam:
steam: Steam is a digital distribution, digital rights management,
steam: multiplayer and communications platform developed by Valve Corporation.
steam:
steam: https://store.steampowered.com/
steam:
FILE LIST:
EOM

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

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

# check on steam 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}Failed. Your $PRGNAM module is not built.${RESET}\n"
fi
cleanup
