#!/bin/bash

# OBS Studio AppImage Porteus module build script
# Version 2026-08-26
# Copyright 2023-2030, Blaze, Dankov, Russia. All rights reserved.

PRGNAM=${PRGNAM:-obs-studio}
BUILD=${BUILD:-1}
ARCH=$(uname -m)
CWD=$(pwd)
TMPDIR=/tmp/portch
PKG=$TMPDIR/package-$PRGNAM
PKGINFO=$PKG/var/lib/pkgtools/packages
OUTPUT=${OUTPUT:-/tmp}

BOLD=$'\e[1m'
CYAN=$'\e[96m'
GREEN=$'\e[92m'
RED=$'\e[31m'
RESET=$'\e[0m'

cleanup() {
    [ -d "$TMPDIR" ] && rm -rf "$TMPDIR"
    [ -d "$PKG" ] && rm -rf "$PKG"
}
trap cleanup EXIT INT TERM HUP

if [ "$(whoami)" != "root" ]; then
    echo -e "\n${RED}You need to be root to run this script.${RESET}\n"
    exit 1
fi

echo -e "\nFetching latest release info..."
JSON=$(wget -q -O- "https://api.github.com/repos/pkgforge-dev/OBS-Studio-AppImage/releases/latest")
APPIMAGE_NAME=$(echo "$JSON" | grep -m1 '"name":.*anylinux-x86_64.AppImage' | cut -d'"' -f4 | tr -d '\r')
VERSION=$(echo "$APPIMAGE_NAME" | sed -n 's/.*OBS_Studio-\([0-9.]\+\).*/\1/p')
DOWNLOAD_URL=$(echo "$JSON" | grep -m1 '"browser_download_url":.*anylinux-x86_64.AppImage' | cut -d'"' -f4 | tr -d '\r')

if [ -z "$VERSION" ] || [ -z "$DOWNLOAD_URL" ]; then
    echo -e "${RED}Failed to determine the latest version or download URL.${RESET}"
    exit 1
fi

INSTALLED_VERSION=""
[ -f "/opt/$PRGNAM/version.txt" ] && INSTALLED_VERSION=$(cat "/opt/$PRGNAM/version.txt")

if [ "$INSTALLED_VERSION" = "$VERSION" ]; then
    echo -e "You have the latest ${GREEN}$INSTALLED_VERSION${RESET} version of $PRGNAM."
    exit 0
else
    read -p "Build $PRGNAM ${GREEN}$VERSION${RESET} xzm module? [y/N]: " -n 1 -r -s && echo
    [[ ! $REPLY =~ ^[Yy]$ ]] && exit 0
fi

rm -rf "$PKG" "$TMPDIR"
mkdir -p "$PKG/opt/$PRGNAM" "$PKG/usr/bin" "$PKG/usr/share/applications" "$PKG/usr/share/pixmaps"

APPIMAGE_FILE="$TMPDIR/obs-studio.AppImage"
echo -e "\nDownloading ${CYAN}${BOLD}obs-studio.AppImage${RESET}"
wget -q -L --show-progress -O "$APPIMAGE_FILE" "$DOWNLOAD_URL"

if [ ! -s "$APPIMAGE_FILE" ]; then
    echo -e "${RED}Download failed or file is empty!${RESET}"
    exit 1
fi

cd "$TMPDIR" || exit 1
chmod +x obs-studio.AppImage
echo -e "\nExtracting AppImage..."
./obs-studio.AppImage --appimage-extract > /dev/null 2>&1

if [ $? -ne 0 ] || [ ! -d "squashfs-root" ]; then
    echo -e "${RED}Extraction failed!${RESET}"
    exit 1
fi

# ============================================================================
# LOCALE SELECTION
# ============================================================================
LOCALE_DIR=$(find squashfs-root -type d -path "*/share/locale" 2>/dev/null | head -1)
LANG_CHOICE="en"

if [ -n "$LOCALE_DIR" ] && [ -d "$LOCALE_DIR" ]; then
    mapfile -t LANGUAGES < <(find "$LOCALE_DIR" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' 2>/dev/null | grep -E '^[a-z]{2,3}(_[A-Z]{2})?$' | sort -u)
    if [ ${#LANGUAGES[@]} -gt 0 ]; then
        echo -e "\n${CYAN}OBS Studio locale setup${RESET}"
        echo -e "Available locales (${#LANGUAGES[@]}):"
        i=1
        for loc in "${LANGUAGES[@]}"; do
            printf "  %2d) %-15s" "$i" "$loc"
            [ $((i % 5)) -eq 0 ] && echo
            i=$((i + 1))
        done
        [ $((${#LANGUAGES[@]} % 5)) -ne 0 ] && echo
        
        while true; do
            echo
            read -p "Locale number to keep (English always kept) [1-${#LANGUAGES[@]}, Enter=English only]: " choice
            if [ -z "$choice" ]; then
                choice=0
                break
            fi
            [[ "$choice" =~ ^[0-9]+$ ]] && [ "$choice" -ge 1 ] && [ "$choice" -le "${#LANGUAGES[@]}" ] && break
            echo -e "${RED}Invalid choice. Try again.${RESET}"
        done
        
        target="en"
        base_lang="en"
        if [ "$choice" -gt 0 ]; then
            target="${LANGUAGES[$((choice-1))]}"
            base_lang="${target%%_*}"
        fi
        
        echo -e "${CYAN}Removing all locales except English and $target...${RESET}"
        
        find "$LOCALE_DIR" -mindepth 1 -maxdepth 1 -type d -not -name "en*" -not -name "$target" -exec rm -rf {} + 2>/dev/null
        
        find squashfs-root -type d -path "*/obs-studio/locale" -o -path "*/obs-plugins/*/locale" 2>/dev/null | while read -r pdir; do
            find "$pdir" -mindepth 1 -maxdepth 1 -type f -name "*.ini" -not -name "en-US.ini" -not -name "en-GB.ini" -not -name "${target}.ini" -not -name "${base_lang}-*.ini" -exec rm -f {} + 2>/dev/null
        done
        
        find squashfs-root -type d -path "*/qt6/translations" 2>/dev/null | while read -r tdir; do
            find "$tdir" -mindepth 1 -maxdepth 1 -type f -name "*.qm" | while read -r qm; do
                bn=$(basename "$qm")
                lang=$(echo "$bn" | sed 's/^qt[a-z_]*_//;s/\.qm$//')
                [ "$lang" != "en" ] && [ "$lang" != "en_US" ] && [ "$lang" != "$target" ] && [ "$lang" != "$base_lang" ] && rm -f "$qm"
            done
        done
        
        echo -e "${GREEN}info: kept: en + $target${RESET}"
    fi
fi

# ============================================================================
# DEEP CLEANUP
# ============================================================================
echo -e "\n${CYAN}Cleaning up unnecessary files...${RESET}"

find squashfs-root -type d \( -name licenses -o -name doc -o -name docs -o -name man -o -name info -o -name cmake -o -name pkgconfig -o -name aclocal -o -name gettext -o -name i18n -o -name help -o -name examples -o -name tutorials -o -name tests -o -name test -o -name benchmarks \) -exec rm -rf {} + 2>/dev/null
find squashfs-root -type f \( -name "*.a" -o -name "*.la" -o -name "*.prl" -o -name "*.h" -o -name "*.hpp" -o -name "*.c" -o -name "*.cpp" -o -name "*.cc" -o -name "*.pdb" -o -name "*.dbg" -o -name "*.map" -o -name "*.sym" -o -name "*.pc" -o -name "*.cmake" -o -name "CMakeLists.txt" \) -delete 2>/dev/null
find squashfs-root -type f \( -iname "README*" -o -iname "LICENSE*" -o -iname "COPYING*" \) -delete 2>/dev/null

find squashfs-root -type d \( -name "obs-browser" -o -name "cef" \) -exec rm -rf {} + 2>/dev/null
find squashfs-root -type f \( -name "libcef.so*" -o -name "chrome-sandbox" -o -name "obs-browser.so" -o -name "obs-vst*.so*" -o -name "libobs-vst*.so*" -o -name "libswiftShader*" -o -name "libvk_swiftshader*" -o -name "vk_swiftshader*" \) -delete 2>/dev/null
rm -rf squashfs-root/usr/lib/obs-plugins/obs-browser* squashfs-root/usr/share/obs/obs-plugins/obs-browser* squashfs-root/usr/lib/obs-plugins/frontend/obs-vst* 2>/dev/null

find squashfs-root -type f -regextype posix-extended -regex ".*libQt6(WebEngine|WebEngineCore|WebEngineWidgets|WebChannel|Quick3D|Quick3DRuntimeRender|Quick3DAssetImport|Multimedia|MultimediaWidgets|SpatialAudio|Positioning|Location|Geoservices|Bluetooth|Nfc|Sensors|SerialPort|Scxml|StateMachine|StateChart|QmlModels|QmlWorkerScript|Designer|DesignerComponents|UiTools|Help|Assistant|NetworkAuth|HttpServer|RemoteObjects|WebView|Charts|ChartsQml|DataVisualization|VirtualKeyboard|TextToSpeech).*\.so.*" -delete 2>/dev/null
find squashfs-root -type d -regextype posix-extended -regex ".*/qt6/qml/Qt6(WebEngine|WebEngineCore|WebEngineWidgets|WebChannel|Quick3D|Quick3DRuntimeRender|Quick3DAssetImport|Multimedia|MultimediaWidgets|SpatialAudio|Positioning|Location|Geoservices|Bluetooth|Nfc|Sensors|SerialPort|Scxml|StateMachine|StateChart|QmlModels|QmlWorkerScript|Designer|DesignerComponents|UiTools|Help|Assistant|NetworkAuth|HttpServer|RemoteObjects|WebView|Charts|ChartsQml|DataVisualization|VirtualKeyboard|TextToSpeech)" -exec rm -rf {} + 2>/dev/null

for plugin_dir in squashfs-root/usr/lib/qt6/plugins squashfs-root/usr/lib/x86_64-linux-gnu/qt6/plugins; do
    [ -d "$plugin_dir" ] || continue
    find "$plugin_dir" -mindepth 1 -maxdepth 1 -type d ! -name imageformats ! -name platforms ! -name platformthemes ! -name styles ! -name tls ! -name iconengines ! -name xcbglintegrations ! -name printsupport ! -name "wayland-*" ! -name "dbusmenu-*" -exec rm -rf {} + 2>/dev/null
done

for theme_dir in squashfs-root/usr/lib/qt6/plugins/styles squashfs-root/usr/lib/x86_64-linux-gnu/qt6/plugins/styles; do
    [ -d "$theme_dir" ] || continue
    find "$theme_dir" -mindepth 1 -maxdepth 1 ! -iname "*fusion*" ! -iname "*breeze*" ! -iname "*kvantum*" -exec rm -rf {} + 2>/dev/null
done

find squashfs-root -type d -path "*/icons/hicolor" | while read -r icon_base; do
    find "$icon_base" -mindepth 1 -maxdepth 1 -type d -regextype posix-extended -regex ".*/[0-9]+x[0-9]+" ! -name "256x256" ! -name "128x128" -exec rm -rf {} + 2>/dev/null
done

find squashfs-root -type d -path "*/python3.*/idlelib" -o -path "*/python3.*/turtledemo" -o -path "*/python3.*/ensurepip" -o -path "*/python3.*/test" -o -path "*/python3.*/Tools" -exec rm -rf {} + 2>/dev/null

find squashfs-root -type d \( -name "drirc.d" -o -name "pipewire" -o -name "mime" \) -exec rm -rf {} + 2>/dev/null
find squashfs-root -type d -path "*/glib-2.0/schemas" | while read -r schema_dir; do
    find "$schema_dir" -type f -name "*.xml" -exec rm -f {} + 2>/dev/null
done

find squashfs-root -type f -name "*.so*" -exec strip --strip-unneeded {} + 2>/dev/null
find squashfs-root -type f -executable ! -name "*.so*" ! -name "*.sh" ! -name "*.py" ! -name "*.pl" -exec sh -c 'head -c 4 "$1" 2>/dev/null | grep -q ELF && strip --strip-unneeded "$1"' _ {} \; 2>/dev/null

find squashfs-root -type d -empty -delete 2>/dev/null

# ============================================================================
# INSTALLATION
# ============================================================================
rm -f obs-studio.AppImage
mv squashfs-root/* "$PKG/opt/$PRGNAM/" 2>/dev/null
mv squashfs-root/.DirIcon "$PKG/opt/$PRGNAM/" 2>/dev/null
rmdir squashfs-root 2>/dev/null

echo "$VERSION" > "$PKG/opt/$PRGNAM/version.txt"
chmod +x "$PKG/opt/$PRGNAM/AppRun"

ICON_SRC=""
for candidate in \
    "$PKG/opt/$PRGNAM/.DirIcon" \
    "$PKG/opt/$PRGNAM/usr/share/icons/hicolor/256x256/apps/com.obsproject.Studio.png" \
    "$PKG/opt/$PRGNAM/usr/share/icons/hicolor/128x128/apps/com.obsproject.Studio.png" \
    "$PKG/opt/$PRGNAM/usr/share/icons/hicolor/scalable/apps/com.obsproject.Studio.svg" \
    "$PKG/opt/$PRGNAM/com.obsproject.Studio.png"; do
    [ -f "$candidate" ] && { ICON_SRC="$candidate"; break; }
done

if [ -n "$ICON_SRC" ]; then
    EXT="${ICON_SRC##*.}"
    cp "$ICON_SRC" "$PKG/usr/share/pixmaps/obs-studio.$EXT"
    chmod 644 "$PKG/usr/share/pixmaps/obs-studio.$EXT"
    ICON_NAME="obs-studio.$EXT"
else
    wget -q -O "$PKG/usr/share/pixmaps/obs-studio.png" "https://raw.githubusercontent.com/obsproject/obs-studio/master/UI/obs.png"
    chmod 644 "$PKG/usr/share/pixmaps/obs-studio.png"
    ICON_NAME="obs-studio.png"
fi

find "$PKG/opt/$PRGNAM" -type f \( -name "*.a" -o -name "*.prl" -o -name "*.la" -o -name "*.h" \) -delete 2>/dev/null
find "$PKG/opt/$PRGNAM" -type d -name "objects-RelWithDebInfo" -exec rm -rf {} + 2>/dev/null
rm -f "$PKG/opt/$PRGNAM/.DirIcon" "$PKG/opt/$PRGNAM/com.obsproject.Studio.desktop" 2>/dev/null

cat > "$PKG/usr/bin/obs" << EOF
#!/bin/bash
export APPDIR=/opt/$PRGNAM
export XDG_DATA_DIRS="/usr/share:/usr/local/share:\$APPDIR/usr/share"
export QT_PLUGIN_PATH="\$APPDIR/usr/lib/qt6/plugins:\$APPDIR/usr/lib/x86_64-linux-gnu/qt6/plugins:\$QT_PLUGIN_PATH"
exec /opt/$PRGNAM/AppRun "\$@"
EOF
chmod 755 "$PKG/usr/bin/obs"

cat > "$PKG/usr/share/applications/$PRGNAM.desktop" << EOM
[Desktop Entry]
Name=OBS Studio
GenericName=Streaming and Recording
GenericName[ru]=Запись и потоковое вещание
Comment=Free and open source software for live streaming and screen recording
Comment[ru]=Свободное программное обеспечение для записи и потокового вещания
Icon=/usr/share/pixmaps/${ICON_NAME}
Exec=obs %U
Terminal=false
Type=Application
Categories=AudioVideo;Recorder;
MimeType=x-scheme-handler/obs;
StartupWMClass=obs
EOM
chmod 644 "$PKG/usr/share/applications/$PRGNAM.desktop"

mkdir -p "$PKGINFO"
cat > "$PKGINFO/$PRGNAM-$VERSION-$ARCH" << EOM
PACKAGE NAME: $PRGNAM-$VERSION-$ARCH
PACKAGE DESCRIPTION:
obs-studio: OBS Studio is free and open source software for live streaming and screen recording.
obs-studio: https://obsproject.com/
FILE LIST:
EOM
cd "$PKG" || exit 1
find . -path ./var -prune -o -print | grep -v "^\./var" >> "$PKGINFO/$PRGNAM-$VERSION-$ARCH"
cd "$CWD" || exit 1

echo -e "\n${CYAN}Building XZM module...${RESET}"
dir2xzm "$PKG" "$OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.xzm"

if [ -f "$OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.xzm" ]; then
    MODULE_SIZE=$(du -h "$OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.xzm" | cut -f1)
    echo -e "\n${BOLD}Module successfully created!${RESET}"
    echo -e "${BOLD}Location: ${GREEN}$OUTPUT/$PRGNAM-$VERSION-${ARCH}-${BUILD}.xzm${RESET}"
    echo -e "${BOLD}Size: ${CYAN}$MODULE_SIZE${RESET}"
    echo -e "${BOLD}Action: Copy it to your /porteus/modules folder to survive a reboot.${RESET}\n"
else
    echo -e "\n${RED}${BOLD}Failed to build the module.${RESET}\n"
fi
