#!/bin/bash

# ======================================================================
# File:       cleanmaster
# Author:     Charlie Martínez® <cmartinez@quirinux.org>
# License:    https://www.gnu.org/licenses/gpl-2.0.txt
# Purpose:    Free up disk space
# Supported:  Multi-distro (originally for Quirinux 2.0)
# ======================================================================

# This script was originally created for Quirinux 2.0 and is used to perform
# an unattended deep system cleanup to lighten a Linux installation intended
# to serve as a master for creating a derived live ISO.
#
# IMPORTANT:
# These were designed to save space in live ISO systems by removing 
# unsupported languages, all program documentation, and all "man" manual
# pages (if you prefer to disable any function, you can comment it at the 
# end of this code at "Function Execution" section).
#
# Copyright (c) 2019-2025 Charlie Martinez. All rights reserved.
# License: https://www.gnu.org/licenses/gpl-2.0.txt
# For permitted and unauthorized uses of the Quirinux trademark:
# Visit https://www.quirinux.org/aviso-legal

# ======================================================================
# Global Functions
# ======================================================================

function _rootcheck() {
    # Check if the script is run as root
    if [ "$EUID" -ne 0 ]; then
        echo -e "\nThis script must be run as root.\nPlease execute \"su root\" first and enter the root password.\n"
        exit 1
    fi
}

function _diskspace() {
    # Get disk space usage before cleanup
    disk_before=$(df --output=used / | tail -1)
}

function _package_cleanup() {
    # Clean package caches (multi-distro support)
    echo "Cleaning package caches..."
    if command -v apt-get &> /dev/null; then
        apt-get clean
        apt-get autoclean
        apt-get autoremove
        rm -rf /var/lib/apt/lists/*
    elif command -v dnf &> /dev/null; then
        dnf clean all
    elif command -v pacman &> /dev/null; then
        pacman -Sc --noconfirm
    elif command -v zypper &> /dev/null; then
        zypper clean --all
    else
        echo "Package manager cleanup not supported on this system."
    fi
}

function _bash_history() {
    # Clear Bash history
    echo "Clearing Bash history..."
    rm -rf ~/.bash_history
}

function _deep_cleanup() {
    # Remove backup files, temporary files, and VIM swap files
    echo "Removing backup, temp, and VIM swap files..."
    for user_home in /home/*; do
        if [[ -d "$user_home" ]]; then
            find "$user_home" -type f -name "*.bak" -delete
            find "$user_home" -type f -name "*~" -delete
            find "$user_home" -type f -name "*.sw[nop]" -delete
        fi
    done
}

function _log_cleanup() {
    # Delete system log files
    echo "Deleting log files..."
    rm -rf /var/log/*.log /var/log/*/*.log /var/log/*/*.gz /var/log/*/*.[0-9]
    dmesg --clear
}

function _trash_cleanup() {
    # Empty user trash folders
    for user_home in /home/*; do
        if [[ -d "$user_home" ]]; then
            # El comodín va fuera de las comillas para que el shell lo expanda
            rm -rf "$user_home"/.cache/*
            rm -f "$user_home/.local/share/recently-used.xbel"
            rm -f "$user_home/.recently-used"
            rm -rf "$user_home"/.local/share/Trash/*
        fi
    done
    rm -rf /root/.cache/* /root/.local/share/Trash/*
}

function _wallpapers() {
	if [ -e "/usr/share/wallpapers/Next" ]; then
		rm -rf /usr/share/wallpapers/Next/*
	fi
	if [ -e "/usr/share/backgrounds/xfce" ]; then
		rm -rf /usr/share/backgrounds/xfce/*
	fi
}

function _themes() {
	if [ -e "/usr/share/desktop-base/grub-themes" ]; then
		rm -rf /usr/share/desktop-base/grub-themes/*
	fi
}

function _lang() {
    # Remove unused language files except for specified ones.
    #
    # NOTA: esta lista de idiomas protegidos debe coincidir con los
    # locales que genera quirinux-config en su postinst
    # (LOCALES_REQUERIDOS: es_ES, pt_BR, pt_PT, hu_HU, gl_ES, de_DE,
    # ru_RU, fr_FR, it_IT). Si cleanmaster corre en el master después
    # de instalar quirinux-config y algún idioma generado ahí no está
    # protegido acá, se borran los catálogos de traducción de la
    # interfaz para ese idioma aunque el locale glibc siga existiendo,
    # y el sistema termina mostrando la interfaz en inglés para ese
    # idioma pese a tenerlo "instalado". Se agregaron hu/hu_HU,
    # ru/ru_RU y pt_BR, que faltaban.
    echo "Removing unused language files..."
    find /usr/share/locale -mindepth 1 -maxdepth 1 \
        ! -name "en" ! -name "en_US" ! -name "de" ! -name "de_DE" \
        ! -name "es" ! -name "es_ES" ! -name "pt" ! -name "pt_PT" ! -name "pt_BR" \
        ! -name "fr" ! -name "fr_FR" ! -name "it" ! -name "it_IT" \
        ! -name "gl" ! -name "gl_ES" ! -name "hu" ! -name "hu_HU" \
        ! -name "ru" ! -name "ru_RU" -exec rm -rf {} +
}

function _lang_extra() {
    # Remove translations kept outside /usr/share/locale by specific programs
    echo "Removing unused translations of Converseen, CUPS, XFCE panel profiles and UFW..."

    # Converseen: keep only de_DE, fr_FR, it_IT and pt_BR
    if [ -d /usr/share/converseen/loc ]; then
        find /usr/share/converseen/loc -mindepth 1 -maxdepth 1 \
            ! -name "converseen_de_DE.qm" ! -name "converseen_fr_FR.qm" \
            ! -name "converseen_it_IT.qm" ! -name "converseen_pt_BR.qm" \
            -exec rm -rf {} +
    fi

    # CUPS: keep only de, en, es, fr, it, pt_BR and ru
    if [ -d /usr/share/cups/locale ]; then
        find /usr/share/cups/locale -mindepth 1 -maxdepth 1 -type d \
            ! -name "de" ! -name "en" ! -name "es" ! -name "fr" \
            ! -name "it" ! -name "pt_BR" ! -name "ru" \
            -exec rm -rf {} +
    fi

    # XFCE panel profiles: keep only de, en, es, fr, gl, hu, it, pt and ru
    if [ -d /usr/share/xfce4-panel-profiles/local ]; then
        find /usr/share/xfce4-panel-profiles/local -mindepth 1 -maxdepth 1 -type d \
            ! -name "de" ! -name "en" ! -name "es" ! -name "fr" ! -name "gl" \
            ! -name "hu" ! -name "it" ! -name "pt" ! -name "ru" \
            -exec rm -rf {} +
    fi

    # UFW messages: keep only de, es, fr, hu, it, pt and ru
    if [ -d /usr/share/ufw/messages ]; then
        find /usr/share/ufw/messages -mindepth 1 -maxdepth 1 \
            ! -name "de.mo" ! -name "es.mo" ! -name "fr.mo" ! -name "hu.mo" \
            ! -name "it.mo" ! -name "pt.mo" ! -name "ru.mo" \
            -exec rm -rf {} +
    fi
}

function _help_dicts() {
    # Remove GNOME-style help folders and MySpell dictionaries
    echo "Removing help files and spell-check dictionaries..."

    # All folders in /usr/share/help
    if [ -d /usr/share/help ]; then
        find /usr/share/help -mindepth 1 -maxdepth 1 -type d -exec rm -rf {} +
    fi

    # All contents of /usr/share/myspell/dicts
    if [ -d /usr/share/myspell/dicts ]; then
        find /usr/share/myspell/dicts -mindepth 1 -maxdepth 1 -exec rm -rf {} +
    fi
}

function _doc() {
    # Remove documentation except for Quirinux-specific docs
    echo "Removing documentation, except for Quirinux docs..."
    find /usr/share/doc -mindepth 1 -not -path "/usr/share/doc/quirinux*" -exec rm -rf {} +
    rm -rf /usr/share/info/*
    if [ -e "/usr/local/share/doc/" ]; then
		rm -rf /usr/local/share/doc/*
	fi
}

function _doc_extra() {
    # Remove extra documentation folders outside /usr/share/doc
    echo "Removing Debian Reference, GTK-Doc, HardInfo docs and doc-base registry..."
    local dir
    for dir in /usr/share/debian-reference /usr/share/gtk-doc \
               /usr/share/hardinfo/doc /usr/share/doc-base; do
        if [ -d "$dir" ]; then
            find "$dir" -mindepth 1 -maxdepth 1 -exec rm -rf {} +
        fi
    done
}

function _man() {
    # Remove all manual pages
    echo "Removing manual pages..."
    rm -rf /usr/share/man/*
}

function _diskfree() {
    # Get disk space usage after cleanup
    disk_after=$(df --output=used / | tail -1)
    recovered=$((disk_before - disk_after))
}

function _completion_message() {
    # Display final message with recovered space
    echo "Cleanup complete. Recovered $((recovered / 1024)) MB of disk space."
}

# ======================================================================
# Function Execution
# ======================================================================
_rootcheck        # Ensure root permissions
_diskspace        # Get initial disk usage
_package_cleanup  # Clean package caches (multi-distro support)
_bash_history     # Clear Bash history
_trash_cleanup    # Empty trash bins
_wallpapers       # Empty old wallpapers
_log_cleanup      # Delete logs
_deep_cleanup     # Remove temp and backup files
_lang             # Remove unused languages
_lang_extra       # Remove extra translations (Converseen, CUPS, XFCE panel profiles, UFW)
_help_dicts       # Remove /usr/share/help folders and myspell dictionaries
_doc              # Remove documentation
_doc_extra        # Remove debian-reference, gtk-doc, hardinfo/doc and doc-base
_man              # Remove manual pages
_diskfree         # Get final disk usage
_completion_message # Display results
