#!/bin/bash

# BleachBit xzm Module Builder for Porteus
# Version: 2026-08-28
#
# 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.

export LC_ALL=C
export XZ_OPT="-T0"

PRGNAM=${PRGNAM:-bleachbit}
BUILD=${BUILD:-1}
OUTPUT=${OUTPUT:-/tmp}
TMPDIR=/tmp/portch
SRC="$TMPDIR/src"
PKG="$TMPDIR/package-$PRGNAM"
PKGINFO="$PKG/var/lib/pkgtools/packages"
ARCH=$(uname -m)

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

cleanup() { 
    rm -rf "$TMPDIR" /tmp/*.txz 2>/dev/null
}
trap cleanup EXIT INT TERM HUP

[ "$(id -u)" -ne 0 ] && { printf "\n${RED}Error: You need to be root to run this script.${RESET}\n"; exit 1; }

# Fast version fetch
printf "\nFetching latest release info...\n"
VERSION=$(curl -sI "https://github.com/bleachbit/bleachbit/releases/latest" 2>/dev/null | grep -i "^Location:" | sed -n 's/.*\/tag\/v\([0-9.]*\).*/\1/p' | tr -d '\r')

[[ -z "$VERSION" ]] && { printf "${RED}Failed to determine version.${RESET}\n"; exit 1; }
SOURCE="https://github.com/bleachbit/bleachbit/releases/download/v${VERSION}/bleachbit-${VERSION}.tar.gz"

# Check installed version
if [[ -f "/usr/bin/bleachbit" ]]; then
    MYVER=$(basename /var/lib/pkgtools/packages/bleachbit-* 2>/dev/null | cut -d'-' -f2)
    printf "[${GREEN}OK${RESET}] Installed version: %s\n" "${MYVER:-Unknown}"
    if [[ "${MYVER:-}" == "$VERSION" ]]; then
        printf "You already have the latest ${GREEN}%s${RESET} version of %s.\n" "$MYVER" "$PRGNAM"
        exit 0
    fi
else
    printf "[${CYAN}INFO${RESET}] BleachBit is not currently installed.\n"
fi

printf "Current: ${RED}${MYVER:-None}${RESET} | Available: ${GREEN}%s${RESET}\n" "$VERSION"
read -r -p "Build ${PRGNAM} ${GREEN}${VERSION}${RESET} xzm module? [y/N]: " -n 1 -r -s && echo
[[ ! $REPLY =~ ^[Yy]$ ]] && { printf "Build cancelled.\n"; exit 0; }

rm -rf "$TMPDIR"
mkdir -p "$SRC" "$PKG/usr/bin" "$PKG/usr/share/applications" "$OUTPUT"
cd "$TMPDIR" || exit 1

printf "\nDownloading %s%s%s${RESET}\n" "${CYAN}" "${BOLD}" "bleachbit-${VERSION}.tar.gz"
if wget -q "$SOURCE" -O "$TMPDIR/$PRGNAM.tar.gz"; then
    tar -xf "$TMPDIR/$PRGNAM.tar.gz" -C "$SRC" --strip-components=1 || { printf "${RED}Failed to extract.${RESET}\n"; exit 1; }
    rm -f "$TMPDIR/$PRGNAM.tar.gz"
else
    printf "  -> Falling back to git clone...\n"
    git clone --depth 1 --branch "v${VERSION}" https://github.com/bleachbit/bleachbit.git "$SRC" >/dev/null 2>&1 || { printf "${RED}Download failed.${RESET}\n"; exit 1; }
fi

[[ -f "$SRC/Makefile" && -f "$SRC/bleachbit.py" ]] || { printf "${RED}Source validation failed.${RESET}\n"; exit 1; }

cd "$SRC" || exit 1
printf "Building translations...\n"
make -s -C po local >/dev/null 2>&1 || { printf "${RED}Failed to build translations.${RESET}\n"; exit 1; }

printf "Installing to package directory...\n"
make -s install DESTDIR="$PKG" prefix=/usr >/dev/null 2>&1 || { printf "${RED}Installation failed.${RESET}\n"; exit 1; }

[[ -f "$PKG/usr/bin/bleachbit" ]] || { printf "${RED}Build failed: bleachbit binary not found.${RESET}\n"; exit 1; }

# Locale selection
setup_locale() {
    local ldir="$PKG/usr/share/locale"
    [[ ! -d "$ldir" ]] && return 0
    
    local locales=($(find "$ldir" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' 2>/dev/null | sort))
    local count=${#locales[@]}
    [[ "$count" -eq 0 ]] && return 0
    
    printf "\n${CYAN}BleachBit locale setup${RESET}\n"
    printf "Available locales (%s):\n" "$count"
    
    local COLS=5
    local ROWS=$(( (count + COLS - 1) / COLS ))
    for ((i=0; i<ROWS; i++)); do
        for ((j=0; j<COLS; j++)); do
            local idx=$((i + j * ROWS))
            if [ $idx -lt $count ]; then
                local num=$((idx + 1))
                printf "  %2d) %-15s" "$num" "${locales[$idx]}"
            fi
        done
        echo
    done

    local choice
    while true; do
        echo
        read -r -p "Locale number to keep (English always kept) [1-$count, Enter=English only]: " choice
        if [ -z "$choice" ]; then 
            find "$ldir" -mindepth 1 -maxdepth 1 -type d -not -name "en*" -exec rm -rf {} +
            printf "${GREEN}info: only English kept${RESET}\n"
            return 0
        fi
        if [[ "$choice" =~ ^[0-9]+$ ]] && [ "$choice" -ge 1 ] && [ "$choice" -le "$count" ]; then 
            break 
        fi
        printf "${RED}warn: invalid input, try again.${RESET}\n"
    done
    
    local target="${locales[$((choice-1))]}"
    printf "  -> Locale set to: ${GREEN}%s${RESET} (English also kept)\n" "$target"
    find "$ldir" -mindepth 1 -maxdepth 1 -type d -not -name "en*" -not -name "$target" -exec rm -rf {} +
}

setup_locale

printf "\n${CYAN}Cleaning up unnecessary files...${RESET}\n"
printf "  -> Removing Windows-specific files...\n"
rm -f "$PKG/usr/share/bleachbit/cleaners/"{internet_explorer,windows_explorer,win*.xml,microsoft_office,smartftp,tortoisesvn,wordpad}.xml
rm -f "$PKG/usr/share/bleachbit/"{Winapp,Windows*.py}

printf "  -> Removing documentation, metadata, and dev files...\n"
rm -rf "$PKG/usr/share/"{doc,man,metainfo,polkit-1,icons} "$PKG/usr/include"
rm -f "$PKG/usr/share/bleachbit/"{README*,COPYING*,NEWS*,AUTHORS*,THANKS*,ChangeLog*,CHANGES*,LICENSE*}
rm -rf "$PKG/usr/share/bleachbit/tests" "$PKG/usr/lib/python*/site-packages/bleachbit/tests"

printf "  -> Removing optimized Python bytecode (.opt-*.pyc) to save space...\n"
find "$PKG" -type f -name "*.opt-*.pyc" -delete 2>/dev/null

printf "  -> Fixing desktop icon path...\n"
desktop_file="$PKG/usr/share/applications/org.bleachbit.BleachBit.desktop"
[[ -f "$desktop_file" ]] && sed -i 's|^Icon=bleachbit$|Icon=/usr/share/pixmaps/bleachbit.png|' "$desktop_file"

printf "  -> Generating metadata...\n"
mkdir -p "$PKGINFO"
{
    printf "PACKAGE NAME: %s-%s-%s\n" "$PRGNAM" "$VERSION" "$ARCH"
    printf "PACKAGE DESCRIPTION:\n"
    printf "bleachbit: BleachBit (system cleaner and privacy tool)\n"
    printf "bleachbit: Frees disk space and maintains privacy.\n"
    printf "bleachbit: Homepage: https://www.bleachbit.org/\n"
    printf "FILE LIST:\n"
    find . -type f ! -path './var/*' -printf '%P\n' | sort
} > "$PKGINFO/${PRGNAM}-${VERSION}-${ARCH}"

# Module creation
printf "\n${CYAN}Building XZM module...${RESET}\n"
FINAL_MODULE="$OUTPUT/${PRGNAM}-${VERSION}-${ARCH}-${BUILD}.xzm"

if ! dir2xzm "$PKG" "$FINAL_MODULE" >/dev/null 2>&1; then
    printf "\n${RED}${BOLD}[FAIL] Failed to build the module.${RESET}\n\n"
    exit 1
fi

if [ -f "$FINAL_MODULE" ]; then
    MODULE_SIZE=$(du -h "$FINAL_MODULE" | cut -f1)
    printf "\n${BOLD}[OK] Module successfully created!${RESET}\n"
    printf "${BOLD}Location: ${GREEN}%s${RESET}\n" "$FINAL_MODULE"
    printf "${BOLD}Size: ${CYAN}%s${RESET}\n" "$MODULE_SIZE"
    printf "${BOLD}Action: Copy it to your /porteus/modules folder to survive a reboot.${RESET}\n\n"
else
    printf "\n${RED}${BOLD}[FAIL] Failed to build the module.${RESET}\n\n"
    exit 1
fi
