diff --git a/install.sh b/install.sh index 0bf359b..d75ff96 100755 --- a/install.sh +++ b/install.sh @@ -3,127 +3,294 @@ set -Eeuo pipefail BASE="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" -# Funções compartilhadas do instalador. +# Funções compartilhadas. source "$BASE/scripts/common.sh" DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}" CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}" + PACK_DIR="$DATA_HOME/steam-media-pack" +LAUNCHER_INSTALL_DIR="$PACK_DIR/launchers" +INSTALLED_BIN_DIR="$PACK_DIR/bin" +PACK_CONFIG_DIR="$PACK_DIR/config" + APP_DIR="$DATA_HOME/applications" ICON_DIR="$DATA_HOME/icons/hicolor/scalable/apps" +MODE_CONFIG="$CONFIG_HOME/steam-media-pack/mode.conf" + CONTROLLER_BRIDGE_DIR="$BASE/controller-bridge" CONTROLLER_BRIDGE_BIN="$CONTROLLER_BRIDGE_DIR/controller-bridge" -INSTALLED_BIN_DIR="$PACK_DIR/bin" INSTALLED_CONTROLLER_BRIDGE="$INSTALLED_BIN_DIR/controller-bridge" + CONTROLLER_BRIDGE_CONFIG_SOURCE="$CONTROLLER_BRIDGE_DIR/controller.conf.example" -CONTROLLER_BRIDGE_CONFIG_DIR="$PACK_DIR/config" -CONTROLLER_BRIDGE_CONFIG_TARGET="$CONTROLLER_BRIDGE_CONFIG_DIR/controller.conf" -SYSTEMD_DIR="$BASE/packaging/systemd" -SYSTEMD_INSTALL_SCRIPT="$SYSTEMD_DIR/install-controller-bridge-service.sh" +CONTROLLER_BRIDGE_CONFIG_TARGET="$PACK_CONFIG_DIR/controller.conf" -log_info "Criando diretórios de instalação..." +SYSTEMD_INSTALL_SCRIPT="$BASE/packaging/systemd/install-controller-bridge-service.sh" +STEAM_SHORTCUT_INSTALLER="$BASE/tools/install-steam-shortcuts.sh" -ensure_directory "$PACK_DIR/launchers" -ensure_directory "$INSTALLED_BIN_DIR" -ensure_directory "$APP_DIR" -ensure_directory "$ICON_DIR" -ensure_directory "$CONFIG_HOME/steam-media-pack" -ensure_directory "$CONTROLLER_BRIDGE_CONFIG_DIR" +on_error() +{ + local exit_code=$? + local line_number="${1:-desconhecida}" -log_info "Compilando o Controller Bridge..." + log_error "A instalação falhou na linha $line_number." + exit "$exit_code" +} -if [[ ! -f "$CONTROLLER_BRIDGE_DIR/Makefile" ]]; then - log_error "Makefile não encontrado em: $CONTROLLER_BRIDGE_DIR" - exit 1 -fi +trap 'on_error "$LINENO"' ERR -make -C "$CONTROLLER_BRIDGE_DIR" +require_command() +{ + local command_name="$1" + local package_hint="${2:-$1}" -if [[ ! -x "$CONTROLLER_BRIDGE_BIN" ]]; then - log_error "Binário não foi gerado: $CONTROLLER_BRIDGE_BIN" - exit 1 -fi + if ! command_exists "$command_name"; then + log_error "Dependência não encontrada: $command_name" + log_error "Instale o pacote correspondente: $package_hint" + exit 1 + fi +} -log_success "Controller Bridge compilado." +install_project_files() +{ + log_info "Criando diretórios de instalação..." -log_info "Instalando o Controller Bridge..." + ensure_directory "$LAUNCHER_INSTALL_DIR" + ensure_directory "$INSTALLED_BIN_DIR" + ensure_directory "$PACK_CONFIG_DIR" + ensure_directory "$APP_DIR" + ensure_directory "$ICON_DIR" + ensure_directory "$(dirname "$MODE_CONFIG")" -install_executable \ - "$CONTROLLER_BRIDGE_BIN" \ - "$INSTALLED_CONTROLLER_BRIDGE" + log_success "Diretórios preparados." -log_success "Controller Bridge instalado em: $INSTALLED_CONTROLLER_BRIDGE" + log_info "Instalando launchers..." -log_info "Preparando a configuração do Controller Bridge..." + local launcher_files=("$BASE"/launchers/*.sh) -if [[ ! -f "$CONTROLLER_BRIDGE_CONFIG_SOURCE" ]]; then - log_error "Configuração de exemplo não encontrada: $CONTROLLER_BRIDGE_CONFIG_SOURCE" - exit 1 -fi + if [[ ! -e "${launcher_files[0]}" ]]; then + log_error "Nenhum launcher encontrado em: $BASE/launchers" + exit 1 + fi -if [[ ! -f "$CONTROLLER_BRIDGE_CONFIG_TARGET" ]]; then - install_regular_file \ - "$CONTROLLER_BRIDGE_CONFIG_SOURCE" \ - "$CONTROLLER_BRIDGE_CONFIG_TARGET" + install -m 755 \ + "$BASE"/launchers/*.sh \ + "$LAUNCHER_INSTALL_DIR/" - log_success "Configuração criada em: $CONTROLLER_BRIDGE_CONFIG_TARGET" -else - log_info "Configuração existente preservada: $CONTROLLER_BRIDGE_CONFIG_TARGET" -fi + install_executable \ + "$BASE/diagnostics.sh" \ + "$PACK_DIR/diagnostics.sh" -log_success "Diretórios preparados." + install_executable \ + "$BASE/select-mode.sh" \ + "$PACK_DIR/select-mode.sh" -install -m 755 "$BASE/launchers/"*.sh "$PACK_DIR/launchers/" -install -m 755 "$BASE/diagnostics.sh" "$PACK_DIR/diagnostics.sh" -install -m 755 "$BASE/select-mode.sh" "$PACK_DIR/select-mode.sh" -install -m 644 "$BASE/desktop/"*.desktop "$APP_DIR/" -install -m 644 "$BASE/icons/"*.svg "$ICON_DIR/" + log_success "Launchers instalados em: $LAUNCHER_INSTALL_DIR" -MODE_CONFIG="$CONFIG_HOME/steam-media-pack/mode.conf" + log_info "Instalando atalhos do ambiente gráfico..." -if [[ ! -f "$MODE_CONFIG" ]]; then - cat >"$MODE_CONFIG" <<'EOF' -MODE=auto -EOF + local desktop_files=("$BASE"/desktop/*.desktop) + local icon_files=("$BASE"/icons/*.svg) + + if [[ -e "${desktop_files[0]}" ]]; then + install -m 644 \ + "$BASE"/desktop/*.desktop \ + "$APP_DIR/" + else + log_warning "Nenhum arquivo .desktop encontrado." + fi - log_success "Configuração padrão criada: $MODE_CONFIG" -else - log_info "Configuração existente preservada: $MODE_CONFIG" -fi + if [[ -e "${icon_files[0]}" ]]; then + install -m 644 \ + "$BASE"/icons/*.svg \ + "$ICON_DIR/" + else + log_warning "Nenhum ícone SVG encontrado." + fi -if command -v update-desktop-database >/dev/null 2>&1; then - update-desktop-database "$APP_DIR" || true -fi + if command_exists update-desktop-database; then + update-desktop-database "$APP_DIR" || true + fi -log_info "Instalando o serviço do Controller Bridge..." + log_success "Integração com o ambiente gráfico concluída." +} -if [[ -x "$SYSTEMD_INSTALL_SCRIPT" ]]; then - "$SYSTEMD_INSTALL_SCRIPT" - log_success "Serviço instalado." -else - log_warning "Instalador do serviço não encontrado." -fi +install_mode_configuration() +{ + log_info "Preparando a configuração de modo..." -cat <"$MODE_CONFIG" <<'EOF' +MODE=auto +EOF -Steam Media Pack instalado em: + log_success "Configuração padrão criada: $MODE_CONFIG" + else + log_info "Configuração existente preservada: $MODE_CONFIG" + fi +} + +build_controller_bridge() +{ + log_info "Compilando o Controller Bridge..." + + if [[ ! -f "$CONTROLLER_BRIDGE_DIR/Makefile" ]]; then + log_error "Makefile não encontrado em: $CONTROLLER_BRIDGE_DIR" + exit 1 + fi + + make -C "$CONTROLLER_BRIDGE_DIR" + + if [[ ! -x "$CONTROLLER_BRIDGE_BIN" ]]; then + log_error "Binário não foi gerado: $CONTROLLER_BRIDGE_BIN" + exit 1 + fi + + log_success "Controller Bridge compilado." +} + +install_controller_bridge() +{ + log_info "Instalando o Controller Bridge..." + + install_executable \ + "$CONTROLLER_BRIDGE_BIN" \ + "$INSTALLED_CONTROLLER_BRIDGE" + + log_success \ + "Controller Bridge instalado em: $INSTALLED_CONTROLLER_BRIDGE" +} + +install_controller_bridge_configuration() +{ + log_info "Preparando a configuração do Controller Bridge..." + + if [[ ! -f "$CONTROLLER_BRIDGE_CONFIG_SOURCE" ]]; then + log_error \ + "Configuração de exemplo não encontrada: $CONTROLLER_BRIDGE_CONFIG_SOURCE" + exit 1 + fi + + if [[ ! -f "$CONTROLLER_BRIDGE_CONFIG_TARGET" ]]; then + install_regular_file \ + "$CONTROLLER_BRIDGE_CONFIG_SOURCE" \ + "$CONTROLLER_BRIDGE_CONFIG_TARGET" + + log_success \ + "Configuração criada em: $CONTROLLER_BRIDGE_CONFIG_TARGET" + else + log_info \ + "Configuração existente preservada: $CONTROLLER_BRIDGE_CONFIG_TARGET" + fi +} + +install_controller_bridge_service() +{ + log_info "Instalando o serviço do Controller Bridge..." + + if [[ ! -f "$SYSTEMD_INSTALL_SCRIPT" ]]; then + log_warning \ + "Instalador do serviço não encontrado: $SYSTEMD_INSTALL_SCRIPT" + return + fi + + if ! command_exists systemctl; then + log_warning \ + "systemctl não encontrado. O serviço não será instalado automaticamente." + return + fi + + bash "$SYSTEMD_INSTALL_SCRIPT" + + log_success "Serviço do Controller Bridge instalado e iniciado." +} + +install_steam_shortcuts() +{ + log_info "Instalando atalhos e artes na Steam..." + + if [[ ! -f "$STEAM_SHORTCUT_INSTALLER" ]]; then + log_error \ + "Instalador de atalhos não encontrado: $STEAM_SHORTCUT_INSTALLER" + exit 1 + fi + + if pgrep -x steam >/dev/null 2>&1 || + pgrep -x steamwebhelper >/dev/null 2>&1; then + log_error "A Steam está em execução." + log_error "Feche completamente a Steam e execute o instalador novamente." + exit 1 + fi + + bash "$STEAM_SHORTCUT_INSTALLER" + + log_success "Atalhos e artes da Steam instalados." +} + +show_summary() +{ + cat < app - Gaming Mode -> kiosk em tela cheia + Gaming Mode -> kiosk em tela cheia + EOF +} + +main() +{ + log_info "Iniciando a instalação do Steam Media Pack..." + + require_command bash + require_command install coreutils + require_command make make + require_command python3 python + require_command pgrep procps-ng + + install_project_files + install_mode_configuration + + build_controller_bridge + install_controller_bridge + install_controller_bridge_configuration + install_controller_bridge_service + + install_steam_shortcuts + + show_summary +} + +main "$@" diff --git a/tools/build-controller-bridge.sh b/tools/build-controller-bridge.sh old mode 100644 new mode 100755 diff --git a/tools/install-steam-shortcuts.py b/tools/install-steam-shortcuts.py old mode 100644 new mode 100755 index 647f97d..0910c4d --- a/tools/install-steam-shortcuts.py +++ b/tools/install-steam-shortcuts.py @@ -1,282 +1,441 @@ #!/usr/bin/env python3 + from __future__ import annotations + +import argparse +import binascii +import shutil +import sys from pathlib import Path -from collections import OrderedDict -import shutil, struct, zlib, re, subprocess, sys - -SERVICES = { - "netflix": ("Netflix", "netflix.sh"), - "prime-video": ("Prime Video", "prime-video.sh"), - "disney-plus": ("Disney+", "disney-plus.sh"), - "max": ("Max", "max.sh"), - "youtube-tv": ("YouTube TV", "youtube-tv.sh"), - "spotify": ("Spotify", "spotify.sh"), -} - -TYPE_OBJECT = 0x00 -TYPE_STRING = 0x01 -TYPE_INT32 = 0x02 -TYPE_FLOAT32 = 0x03 -TYPE_PTR = 0x04 -TYPE_WSTRING = 0x05 -TYPE_COLOR = 0x06 -TYPE_UINT64 = 0x07 -TYPE_END = 0x08 - -def read_cstr(data: bytes, pos: int): - end = data.index(b"\x00", pos) - return data[pos:end].decode("utf-8", errors="replace"), end + 1 - -def parse_object(data: bytes, pos: int): - obj = OrderedDict() - while pos < len(data): - t = data[pos] - pos += 1 - if t == TYPE_END: - return obj, pos - key, pos = read_cstr(data, pos) - if t == TYPE_OBJECT: - val, pos = parse_object(data, pos) - elif t == TYPE_STRING: - val, pos = read_cstr(data, pos) - elif t == TYPE_INT32: - val = struct.unpack_from(" bytes: - return s.encode("utf-8") + b"\x00" - -def encode_entry(key: str, tv): - t, val = tv - out = bytes([t]) + cstr(key) - if t == TYPE_OBJECT: - out += encode_object(val) - elif t == TYPE_STRING: - out += cstr(str(val)) - elif t in (TYPE_INT32, TYPE_PTR): - out += struct.pack(" None: + print(f"[INFO] {message}") + + +def warning(message: str) -> None: + print(f"[AVISO] {message}") + + +def error(message: str) -> None: + print(f"[ERRO] {message}", file=sys.stderr) + + +def calculate_appid(executable: str, app_name: str) -> int: + """ + Calcula o AppID de um atalho não Steam. + + A Steam utiliza o CRC32 da concatenação entre o executável e o nome + do aplicativo. O bit mais significativo deve estar habilitado. + """ + + source = f"{executable}{app_name}".encode("utf-8") + checksum = binascii.crc32(source) & 0xFFFFFFFF + + return checksum | 0x80000000 + + +def normalize_executable(path: Path) -> str: + return f'"{path}"' + + +def normalize_start_directory(path: Path) -> str: + return f'"{path}"' + + +def get_shortcuts_container( + document: dict[str, Any], +) -> dict[str, Any]: + shortcuts = document.get("shortcuts") + + if shortcuts is None: + shortcuts = {} + document["shortcuts"] = shortcuts + + if not isinstance(shortcuts, dict): + raise VDFError( + "A chave 'shortcuts' não contém um objeto VDF válido." + ) + return shortcuts -def existing_shortcuts(shortcuts): - result = {} - for _, (t, entry) in shortcuts.items(): - if t != TYPE_OBJECT: + +def next_shortcut_index(shortcuts: dict[str, Any]) -> str: + numeric_indexes = [] + + for key in shortcuts: + if str(key).isdigit(): + numeric_indexes.append(int(key)) + + if not numeric_indexes: + return "0" + + return str(max(numeric_indexes) + 1) + + +def find_existing_shortcut( + shortcuts: dict[str, Any], + app_name: str, +) -> tuple[str, dict[str, Any]] | None: + for index, shortcut in shortcuts.items(): + if not isinstance(shortcut, dict): continue - name_tv = entry.get("AppName") or entry.get("appname") or entry.get("appName") - appid_tv = entry.get("appid") - if name_tv and appid_tv: - result[str(name_tv[1])] = { - "entry": entry, - "appid": int(appid_tv[1]) & 0xffffffff, - } - return result - -def next_index(shortcuts): - nums = [] - for key in shortcuts.keys(): - try: - nums.append(int(key)) - except ValueError: - pass - return max(nums, default=-1) + 1 - -def copy_art(grid_dir, appid, service_dir): - grid_dir.mkdir(parents=True, exist_ok=True) - mapping = { - "grid.png": f"{appid}p.png", - "wide.png": f"{appid}.png", - "hero.png": f"{appid}_hero.png", - "logo.png": f"{appid}_logo.png", - "icon.png": f"{appid}_icon.png", + + current_name = str(shortcut.get("appname", "")).strip() + + if current_name.casefold() == app_name.casefold(): + return str(index), shortcut + + return None + + +def build_shortcut( + app_name: str, + launcher_path: Path, +) -> dict[str, Any]: + executable = normalize_executable(launcher_path) + start_directory = normalize_start_directory(launcher_path.parent) + appid = calculate_appid(executable, app_name) + + return { + "appid": appid, + "appname": app_name, + "exe": executable, + "StartDir": start_directory, + "icon": "", + "ShortcutPath": "", + "LaunchOptions": "", + "IsHidden": 0, + "AllowDesktopConfig": 1, + "AllowOverlay": 1, + "OpenVR": 0, + "Devkit": 0, + "DevkitGameID": "", + "DevkitOverrideAppID": 0, + "LastPlayTime": 0, + "FlatpakAppID": "", + "tags": { + "0": "Steam Media Pack", + }, } - for src, dst in mapping.items(): - p = service_dir/src - if p.exists(): - shutil.copy2(p, grid_dir/dst) - -def choose_user(users): - if len(users) == 1: - return users[0] - print("Usuários Steam encontrados:") - for i,(_,u) in enumerate(users,1): - print(f"{i}) {u.name}") - while True: - try: - n = int(input("Escolha: ")) - return users[n-1] - except Exception: - print("Escolha inválida.") -def main(): + +def update_shortcut( + shortcut: dict[str, Any], + app_name: str, + launcher_path: Path, +) -> int: + executable = normalize_executable(launcher_path) + start_directory = normalize_start_directory(launcher_path.parent) + appid = calculate_appid(executable, app_name) + + shortcut["appid"] = appid + shortcut["appname"] = app_name + shortcut["exe"] = executable + shortcut["StartDir"] = start_directory + shortcut.setdefault("icon", "") + shortcut.setdefault("ShortcutPath", "") + shortcut.setdefault("LaunchOptions", "") + shortcut.setdefault("IsHidden", 0) + shortcut.setdefault("AllowDesktopConfig", 1) + shortcut.setdefault("AllowOverlay", 1) + shortcut.setdefault("OpenVR", 0) + shortcut.setdefault("Devkit", 0) + shortcut.setdefault("DevkitGameID", "") + shortcut.setdefault("DevkitOverrideAppID", 0) + shortcut.setdefault("LastPlayTime", 0) + shortcut.setdefault("FlatpakAppID", "") + + tags = shortcut.get("tags") + + if not isinstance(tags, dict): + tags = {} + + if "Steam Media Pack" not in tags.values(): + index = 0 + + while str(index) in tags: + index += 1 + + tags[str(index)] = "Steam Media Pack" + + shortcut["tags"] = tags + + return appid + + +def copy_if_exists(source: Path, destination: Path) -> bool: + if not source.is_file(): + return False + + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, destination) + + return True + + +def install_artwork( + grid_directory: Path, + service_id: str, + appid: int, +) -> int: + """ + Instala artes usando os nomes mais comuns do projeto. + + Arquivos aceitos dentro de steam-art//: + + - grid.png ou portrait.png + - hero.png + - logo.png + - icon.png + - grid-wide.png ou capsule.png + """ + + source_directory = STEAM_ART_DIR / service_id + + if not source_directory.is_dir(): + warning( + f"Diretório de artes não encontrado para " + f"{service_id}: {source_directory}" + ) + return 0 + + mappings = ( + ( + ("grid.png", "portrait.png"), + grid_directory / f"{appid}p.png", + ), + ( + ("hero.png",), + grid_directory / f"{appid}_hero.png", + ), + ( + ("logo.png",), + grid_directory / f"{appid}_logo.png", + ), + ( + ("grid-wide.png", "capsule.png", "wide.png"), + grid_directory / f"{appid}.png", + ), + ( + ("icon.png",), + grid_directory / f"{appid}_icon.png", + ), + ) + + installed = 0 + + for source_names, destination in mappings: + for source_name in source_names: + source = source_directory / source_name + + if copy_if_exists(source, destination): + installed += 1 + break + + return installed + + +def create_backup(shortcuts_path: Path) -> Path | None: + if not shortcuts_path.is_file(): + return None + + backup_path = shortcuts_path.with_name(BACKUP_FILENAME) + + try: + shutil.copy2(shortcuts_path, backup_path) + except OSError as exc: + raise VDFError( + f"Não foi possível criar o backup {backup_path}: {exc}" + ) from exc + + return backup_path + + +def load_shortcuts_document( + shortcuts_path: Path, +) -> dict[str, Any]: + if not shortcuts_path.exists(): + return {"shortcuts": {}} + + return load_vdf(shortcuts_path) + + +def install_for_user(user_directory: Path) -> tuple[int, int, int]: + shortcuts_path = user_directory / SHORTCUTS_RELATIVE_PATH + grid_directory = user_directory / GRID_RELATIVE_PATH + + shortcuts_path.parent.mkdir(parents=True, exist_ok=True) + grid_directory.mkdir(parents=True, exist_ok=True) + + document = load_shortcuts_document(shortcuts_path) + shortcuts = get_shortcuts_container(document) + + backup_path = create_backup(shortcuts_path) + + if backup_path is not None: + log(f"Backup criado: {backup_path}") + + created = 0 + updated = 0 + artworks = 0 + + for service_id, service in SERVICES.items(): + app_name = service["name"] + launcher_filename = service["launcher"] + launcher_path = INSTALLED_LAUNCHERS_DIR / launcher_filename + + if not launcher_path.is_file(): + warning( + f"Launcher não encontrado para {app_name}: " + f"{launcher_path}" + ) + continue + + existing = find_existing_shortcut(shortcuts, app_name) + + if existing is None: + shortcut_index = next_shortcut_index(shortcuts) + shortcut = build_shortcut(app_name, launcher_path) + shortcuts[shortcut_index] = shortcut + + appid = int(shortcut["appid"]) + created += 1 + + log(f"Atalho criado: {app_name}") + else: + _, shortcut = existing + appid = update_shortcut( + shortcut, + app_name, + launcher_path, + ) + + updated += 1 + log(f"Atalho atualizado: {app_name}") + + installed_artworks = install_artwork( + grid_directory, + service_id, + appid, + ) + + artworks += installed_artworks + + if installed_artworks: + log( + f"{installed_artworks} arte(s) instalada(s) " + f"para {app_name}." + ) + + save_vdf(shortcuts_path, document) + + return created, updated, artworks + + +def parse_arguments() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=( + "Instala os atalhos do Steam Media Pack " + "nos perfis Steam." + ) + ) + + parser.add_argument( + "--all-users", + action="store_true", + help="Instala para todos os usuários Steam sem perguntar.", + ) + + return parser.parse_args() + + +def main() -> int: + args = parse_arguments() + if steam_running(): - print("Feche completamente a Steam antes de continuar.") - sys.exit(2) + error( + "A Steam está em execução. Feche completamente a Steam " + "antes de instalar os atalhos." + ) + return 1 users = find_userdata() + if not users: - print("Nenhum usuário Steam encontrado.") - sys.exit(3) - - _, userdir = choose_user(users) - config = userdir/"config" - vdf = config/"shortcuts.vdf" - backup = config/"shortcuts.vdf.steam-media-pack.backup" - - if vdf.exists(): - if not backup.exists(): - shutil.copy2(vdf, backup) - root = parse_vdf(vdf.read_bytes()) - else: - root = OrderedDict([("shortcuts", (TYPE_OBJECT, OrderedDict()))]) - - shortcuts = get_shortcuts(root) - existing = existing_shortcuts(shortcuts) - index = next_index(shortcuts) - - pack = Path(__file__).resolve().parent.parent - launcher_dir = Path.home()/".local/share/steam-media-pack/launchers" - art_root = pack/"steam-art" - grid_dir = config/"grid" - - added = [] - updated_art = [] - for sid,(name, script) in SERVICES.items(): - script_path = launcher_dir/script - - if name in existing: - # O atalho já existe: preserva todos os seus campos e usa o - # appid realmente armazenado pela Steam para nomear as artes. - appid = existing[name]["appid"] - copy_art(grid_dir, appid, art_root/sid) - updated_art.append(name) + error("Nenhum usuário Steam foi encontrado.") + return 1 + + selected_users = users if args.all_users else choose_users(users) + + if not selected_users: + error("Nenhum usuário Steam foi selecionado.") + return 1 + + total_created = 0 + total_updated = 0 + total_artworks = 0 + failures: list[str] = [] + + for user_directory in selected_users: + print() + log(f"Processando usuário Steam: {user_directory.name}") + + try: + created, updated, artworks = install_for_user( + user_directory + ) + except (OSError, VDFError, ValueError) as exc: + failures.append(user_directory.name) + error( + f"Falha ao processar o usuário " + f"{user_directory.name}: {exc}" + ) continue - entry, appid = make_shortcut(name, script_path, launcher_dir) - shortcuts[str(index)] = (TYPE_OBJECT, entry) - index += 1 - copy_art(grid_dir, appid, art_root/sid) - added.append(name) - updated_art.append(name) + total_created += created + total_updated += updated + total_artworks += artworks + + print() + print("Resumo da instalação:") + print(f" Atalhos criados: {total_created}") + print(f" Atalhos atualizados: {total_updated}") + print(f" Artes instaladas: {total_artworks}") + + if failures: + print( + " Usuários com falha: " + + ", ".join(failures) + ) + return 1 - vdf.write_bytes(encode_vdf(root)) + print(" Instalação concluída com sucesso.") + return 0 - print("Instalação concluída.") - print("Usuário Steam:", userdir.name) - print("Atalhos adicionados:", ", ".join(added) if added else "nenhum") - print("Artes instaladas/atualizadas:", ", ".join(updated_art) if updated_art else "nenhuma") - print("Backup:", backup if backup.exists() else "não havia arquivo anterior") - print("Abra novamente a Steam.") if __name__ == "__main__": - main() + raise SystemExit(main()) diff --git a/tools/install-steam-shortcuts.sh b/tools/install-steam-shortcuts.sh old mode 100644 new mode 100755 diff --git a/tools/lib/__init__.py b/tools/lib/__init__.py new file mode 100644 index 0000000..ebad2c9 --- /dev/null +++ b/tools/lib/__init__.py @@ -0,0 +1,13 @@ +from .services import SERVICES, get_service_names +from .steam_users import ( + steam_running, + find_userdata, + choose_users, +) +from .steam_vdf import ( + VDFError, + load_vdf, + save_vdf, + parse_vdf, + encode_vdf, +) diff --git a/tools/lib/services.py b/tools/lib/services.py new file mode 100644 index 0000000..4f54798 --- /dev/null +++ b/tools/lib/services.py @@ -0,0 +1,38 @@ +from __future__ import annotations + + +SERVICES = { + "netflix": { + "name": "Netflix", + "launcher": "netflix.sh", + }, + "prime-video": { + "name": "Prime Video", + "launcher": "prime-video.sh", + }, + "disney-plus": { + "name": "Disney+", + "launcher": "disney-plus.sh", + }, + "max": { + "name": "Max", + "launcher": "max.sh", + }, + "youtube-tv": { + "name": "YouTube TV", + "launcher": "youtube-tv.sh", + }, + "spotify": { + "name": "Spotify", + "launcher": "spotify.sh", + }, +} + + +def get_service_names() -> set[str]: + """Retorna os nomes exibidos na biblioteca Steam.""" + + return { + service["name"] + for service in SERVICES.values() + } diff --git a/tools/lib/steam_users.py b/tools/lib/steam_users.py new file mode 100644 index 0000000..0d4e6db --- /dev/null +++ b/tools/lib/steam_users.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +from pathlib import Path +import subprocess + + +STEAM_USERDATA_DIRS = ( + Path.home() / ".local/share/Steam/userdata", + Path.home() / ".steam/steam/userdata", +) + + +def steam_running() -> bool: + return subprocess.run( + ["pgrep", "-x", "steam"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ).returncode == 0 + + +def find_userdata() -> list[Path]: + found = [] + + seen = set() + + for base in STEAM_USERDATA_DIRS: + + if not base.exists(): + continue + + for user in base.iterdir(): + + if not user.is_dir(): + continue + + real = user.resolve() + + if real in seen: + continue + + seen.add(real) + found.append(real) + + return sorted(found) + + +def choose_users(users: list[Path]) -> list[Path]: + + if not users: + return [] + + if len(users) == 1: + return users + + print() + + print("Usuários Steam encontrados:") + + print("0) Todos") + + for index, user in enumerate(users, start=1): + print(f"{index}) {user.name}") + + print() + + while True: + + option = input("Escolha: ").strip() + + if option == "0": + return users + + if option.isdigit(): + + value = int(option) + + if 1 <= value <= len(users): + return [users[value - 1]] + + print("Opção inválida.") diff --git a/tools/lib/steam_vdf.py b/tools/lib/steam_vdf.py new file mode 100644 index 0000000..f051ab3 --- /dev/null +++ b/tools/lib/steam_vdf.py @@ -0,0 +1,138 @@ +from __future__ import annotations + +import struct +from collections.abc import Mapping +from pathlib import Path +from typing import Any + + +TYPE_OBJECT = 0x00 +TYPE_STRING = 0x01 +TYPE_INT32 = 0x02 +TYPE_END = 0x08 + + +class VDFError(ValueError): + """Erro ao interpretar um arquivo shortcuts.vdf.""" + + +def read_cstring(data: bytes, offset: int) -> tuple[str, int]: + end = data.find(b"\x00", offset) + + if end == -1: + raise VDFError("String VDF sem terminador nulo.") + + try: + value = data[offset:end].decode("utf-8") + except UnicodeDecodeError: + value = data[offset:end].decode("latin-1") + + return value, end + 1 + + +def parse_object(data: bytes, offset: int = 0) -> tuple[dict[str, Any], int]: + result: dict[str, Any] = {} + + while offset < len(data): + value_type = data[offset] + offset += 1 + + if value_type == TYPE_END: + return result, offset + + key, offset = read_cstring(data, offset) + + if value_type == TYPE_OBJECT: + value, offset = parse_object(data, offset) + + elif value_type == TYPE_STRING: + value, offset = read_cstring(data, offset) + + elif value_type == TYPE_INT32: + if offset + 4 > len(data): + raise VDFError("Inteiro VDF incompleto.") + + value = struct.unpack_from(" dict[str, Any]: + result, offset = parse_object(data) + + if offset != len(data): + remaining = data[offset:] + + if remaining.strip(b"\x00"): + raise VDFError("Dados inesperados após o final do VDF.") + + return result + + +def encode_cstring(value: str) -> bytes: + return value.encode("utf-8") + b"\x00" + + +def encode_object(data: Mapping[str, Any]) -> bytes: + output = bytearray() + + for key, value in data.items(): + if isinstance(value, Mapping): + output.append(TYPE_OBJECT) + output.extend(encode_cstring(str(key))) + output.extend(encode_object(value)) + + elif isinstance(value, str): + output.append(TYPE_STRING) + output.extend(encode_cstring(str(key))) + output.extend(encode_cstring(value)) + + elif isinstance(value, int): + output.append(TYPE_INT32) + output.extend(encode_cstring(str(key))) + output.extend(struct.pack(" bytes: + return encode_object(data) + + +def load_vdf(path: Path) -> dict[str, Any]: + try: + return parse_vdf(path.read_bytes()) + except OSError as error: + raise VDFError( + f"Não foi possível ler {path}: {error}" + ) from error + + +def save_vdf(path: Path, data: Mapping[str, Any]) -> None: + temporary_path = path.with_suffix(path.suffix + ".tmp") + + try: + temporary_path.write_bytes(encode_vdf(data)) + temporary_path.replace(path) + except OSError as error: + temporary_path.unlink(missing_ok=True) + + raise VDFError( + f"Não foi possível salvar {path}: {error}" + ) from error diff --git a/tools/remove-steam-shortcuts.py b/tools/remove-steam-shortcuts.py new file mode 100755 index 0000000..f343921 --- /dev/null +++ b/tools/remove-steam-shortcuts.py @@ -0,0 +1,317 @@ +#!/usr/bin/env python3 + +from __future__ import annotations + +import argparse +import shutil +import sys +from pathlib import Path +from typing import Any + +from lib.services import get_service_names +from lib.steam_users import choose_users, find_userdata, steam_running +from lib.steam_vdf import VDFError, load_vdf, save_vdf + + +SHORTCUTS_RELATIVE_PATH = Path("config") / "shortcuts.vdf" +GRID_RELATIVE_PATH = Path("config") / "grid" + +BACKUP_FILENAME = ( + "shortcuts.vdf.before-steam-media-pack-removal" +) + +STEAM_MEDIA_PACK_APPS = get_service_names() + + +def log(message: str) -> None: + print(f"[INFO] {message}") + + +def warning(message: str) -> None: + print(f"[AVISO] {message}") + + +def error(message: str) -> None: + print(f"[ERRO] {message}", file=sys.stderr) + + +def get_shortcuts_container( + document: dict[str, Any], +) -> dict[str, Any]: + shortcuts = document.get("shortcuts") + + if shortcuts is None: + shortcuts = {} + document["shortcuts"] = shortcuts + + if not isinstance(shortcuts, dict): + raise VDFError( + "A chave 'shortcuts' não contém um objeto VDF válido." + ) + + return shortcuts + + +def shortcut_matches( + shortcut: dict[str, Any], +) -> bool: + app_name = str(shortcut.get("appname", "")).strip() + + return any( + app_name.casefold() == service_name.casefold() + for service_name in STEAM_MEDIA_PACK_APPS + ) + + +def normalize_appid(value: Any) -> int | None: + try: + return int(value) & 0xFFFFFFFF + except (TypeError, ValueError): + return None + + +def remove_shortcuts( + shortcuts: dict[str, Any], +) -> tuple[dict[str, Any], list[tuple[str, int | None]]]: + preserved: list[tuple[str, dict[str, Any]]] = [] + removed: list[tuple[str, int | None]] = [] + + for original_index, shortcut in shortcuts.items(): + if not isinstance(shortcut, dict): + preserved.append((str(original_index), shortcut)) + continue + + if shortcut_matches(shortcut): + app_name = str( + shortcut.get("appname", "Desconhecido") + ) + appid = normalize_appid(shortcut.get("appid")) + + removed.append((app_name, appid)) + continue + + preserved.append((str(original_index), shortcut)) + + rebuilt: dict[str, Any] = {} + + for new_index, (_, shortcut) in enumerate(preserved): + rebuilt[str(new_index)] = shortcut + + return rebuilt, removed + + +def artwork_candidates( + grid_directory: Path, + appid: int, +) -> tuple[Path, ...]: + prefixes = { + str(appid), + str(appid & 0xFFFFFFFF), + } + + candidates: list[Path] = [] + + for prefix in prefixes: + candidates.extend( + ( + grid_directory / f"{prefix}.png", + grid_directory / f"{prefix}.jpg", + grid_directory / f"{prefix}.jpeg", + grid_directory / f"{prefix}.webp", + grid_directory / f"{prefix}p.png", + grid_directory / f"{prefix}p.jpg", + grid_directory / f"{prefix}p.jpeg", + grid_directory / f"{prefix}p.webp", + grid_directory / f"{prefix}_hero.png", + grid_directory / f"{prefix}_hero.jpg", + grid_directory / f"{prefix}_hero.jpeg", + grid_directory / f"{prefix}_hero.webp", + grid_directory / f"{prefix}_logo.png", + grid_directory / f"{prefix}_logo.jpg", + grid_directory / f"{prefix}_logo.jpeg", + grid_directory / f"{prefix}_logo.webp", + grid_directory / f"{prefix}_icon.png", + grid_directory / f"{prefix}_icon.jpg", + grid_directory / f"{prefix}_icon.jpeg", + grid_directory / f"{prefix}_icon.webp", + ) + ) + + return tuple(dict.fromkeys(candidates)) + + +def remove_artwork( + grid_directory: Path, + appid: int | None, +) -> int: + if appid is None or not grid_directory.is_dir(): + return 0 + + removed = 0 + + for artwork_path in artwork_candidates( + grid_directory, + appid, + ): + if not artwork_path.is_file(): + continue + + try: + artwork_path.unlink() + except OSError as exc: + warning( + f"Não foi possível remover a arte " + f"{artwork_path}: {exc}" + ) + continue + + removed += 1 + + return removed + + +def create_backup(shortcuts_path: Path) -> Path: + backup_path = shortcuts_path.with_name(BACKUP_FILENAME) + + try: + shutil.copy2(shortcuts_path, backup_path) + except OSError as exc: + raise VDFError( + f"Não foi possível criar o backup {backup_path}: {exc}" + ) from exc + + return backup_path + + +def remove_for_user(user_directory: Path) -> tuple[int, int]: + shortcuts_path = user_directory / SHORTCUTS_RELATIVE_PATH + grid_directory = user_directory / GRID_RELATIVE_PATH + + if not shortcuts_path.is_file(): + warning( + f"Arquivo shortcuts.vdf não encontrado para " + f"o usuário {user_directory.name}." + ) + return 0, 0 + + document = load_vdf(shortcuts_path) + shortcuts = get_shortcuts_container(document) + + rebuilt_shortcuts, removed_shortcuts = remove_shortcuts( + shortcuts + ) + + if not removed_shortcuts: + log( + f"Nenhum atalho do Steam Media Pack encontrado " + f"para {user_directory.name}." + ) + return 0, 0 + + backup_path = create_backup(shortcuts_path) + log(f"Backup criado: {backup_path}") + + document["shortcuts"] = rebuilt_shortcuts + save_vdf(shortcuts_path, document) + + artwork_count = 0 + + for app_name, appid in removed_shortcuts: + log(f"Atalho removido: {app_name}") + + removed_artworks = remove_artwork( + grid_directory, + appid, + ) + + artwork_count += removed_artworks + + if removed_artworks: + log( + f"{removed_artworks} arte(s) removida(s) " + f"para {app_name}." + ) + + return len(removed_shortcuts), artwork_count + + +def parse_arguments() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=( + "Remove os atalhos e artes do Steam Media Pack " + "dos perfis Steam." + ) + ) + + parser.add_argument( + "--all-users", + action="store_true", + help="Remove de todos os usuários Steam sem perguntar.", + ) + + return parser.parse_args() + + +def main() -> int: + args = parse_arguments() + + if steam_running(): + error( + "A Steam está em execução. Feche completamente a Steam " + "antes de remover os atalhos." + ) + return 1 + + users = find_userdata() + + if not users: + warning("Nenhum usuário Steam foi encontrado.") + return 0 + + selected_users = users if args.all_users else choose_users(users) + + if not selected_users: + warning("Nenhum usuário Steam foi selecionado.") + return 0 + + total_shortcuts = 0 + total_artworks = 0 + failures: list[str] = [] + + for user_directory in selected_users: + print() + log(f"Processando usuário Steam: {user_directory.name}") + + try: + shortcuts, artworks = remove_for_user( + user_directory + ) + except (OSError, VDFError, ValueError) as exc: + failures.append(user_directory.name) + error( + f"Falha ao processar o usuário " + f"{user_directory.name}: {exc}" + ) + continue + + total_shortcuts += shortcuts + total_artworks += artworks + + print() + print("Resumo da remoção:") + print(f" Atalhos removidos: {total_shortcuts}") + print(f" Artes removidas: {total_artworks}") + + if failures: + print( + " Usuários com falha: " + + ", ".join(failures) + ) + return 1 + + print(" Remoção concluída com sucesso.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/restore-steam-shortcuts.sh b/tools/restore-steam-shortcuts.sh old mode 100644 new mode 100755 diff --git a/tools/setup-controller-bridge.sh b/tools/setup-controller-bridge.sh old mode 100644 new mode 100755 diff --git a/tools/update-steam-arts.py b/tools/update-steam-arts.py old mode 100644 new mode 100755 diff --git a/tools/update-steam-arts.sh b/tools/update-steam-arts.sh old mode 100644 new mode 100755 diff --git a/uninstall.sh b/uninstall.sh index 05d9f33..4e06629 100755 --- a/uninstall.sh +++ b/uninstall.sh @@ -1,28 +1,423 @@ #!/usr/bin/env bash + set -Eeuo pipefail -DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}" -CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}" +BASE="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" + +APP_NAME="Steam Media Pack" +INSTALL_DIR="$HOME/.local/share/steam-media-pack" +CONFIG_DIR="$HOME/.config/steam-media-pack" +APPLICATIONS_DIR="$HOME/.local/share/applications" +SYSTEMD_USER_DIR="$HOME/.config/systemd/user" + +SHORTCUT_REMOVER="$BASE/tools/remove-steam-shortcuts.py" +SERVICES_LIBRARY="$BASE/tools/lib/services.py" + +CONTROLLER_SERVICE="controller-bridge.service" +CONTROLLER_SERVICE_PATH="$SYSTEMD_USER_DIR/$CONTROLLER_SERVICE" + +ASSUME_YES=false +ALL_USERS=false +REMOVE_CONFIG=false + +SHORTCUTS_REMOVED=false +SERVICE_REMOVED=false +FILES_REMOVED=false +CONFIG_REMOVED=false + + +info() { + printf '[INFO] %s\n' "$*" +} + + +warning() { + printf '[AVISO] %s\n' "$*" >&2 +} + + +error() { + printf '[ERRO] %s\n' "$*" >&2 +} + + +show_help() { + cat < 0)); do + case "$1" in + --yes) + ASSUME_YES=true + ;; + + --all-users) + ALL_USERS=true + ;; + + --remove-config) + REMOVE_CONFIG=true + ;; + + -h|--help) + show_help + exit 0 + ;; + + *) + error "Opção desconhecida: $1" + echo + show_help + exit 2 + ;; + esac + + shift + done +} + + +confirm_uninstallation() { + if [[ "$ASSUME_YES" == true ]]; then + return + fi + + local answer + + read -r -p \ + "Deseja realmente remover o Steam Media Pack? [s/N] " \ + answer + + case "${answer,,}" in + s|sim|y|yes) + ;; + + *) + info "Desinstalação cancelada." + exit 0 + ;; + esac +} + + +confirm_config_removal() { + if [[ "$REMOVE_CONFIG" == true ]]; then + return + fi + + if [[ "$ASSUME_YES" == true ]]; then + return + fi + + local answer + + echo + read -r -p \ + "Deseja remover também as configurações? [s/N] " \ + answer + + case "${answer,,}" in + s|sim|y|yes) + REMOVE_CONFIG=true + ;; + esac +} + + +check_dependencies() { + if ! command -v python3 >/dev/null 2>&1; then + error "Python 3 não foi encontrado." + exit 1 + fi + + if ! command -v systemctl >/dev/null 2>&1; then + warning \ + "systemctl não foi encontrado. " \ + "A remoção do serviço será limitada." + fi +} + + +check_steam_closed() { + if pgrep -x steam >/dev/null 2>&1; then + error "A Steam está em execução." + error "Feche completamente a Steam antes de continuar." + exit 1 + fi +} + + +get_service_ids() { + if [[ ! -f "$SERVICES_LIBRARY" ]]; then + warning \ + "Biblioteca comum de serviços não encontrada: " \ + "$SERVICES_LIBRARY" + return 0 + fi + + PYTHONPATH="$BASE/tools${PYTHONPATH:+:$PYTHONPATH}" \ + python3 - <<'PY' +from lib.services import SERVICES + +for service_id in SERVICES: + print(service_id) +PY +} + + +remove_steam_shortcuts() { + echo + info "Removendo atalhos e artes da Steam..." + + if [[ ! -f "$SHORTCUT_REMOVER" ]]; then + warning \ + "Removedor de atalhos não encontrado: " \ + "$SHORTCUT_REMOVER" + return + fi + + local command=( + python3 + "$SHORTCUT_REMOVER" + ) + + if [[ "$ALL_USERS" == true ]]; then + command+=(--all-users) + fi + + if "${command[@]}"; then + SHORTCUTS_REMOVED=true + else + error "Não foi possível remover os atalhos da Steam." + exit 1 + fi +} + + +remove_controller_service() { + echo + info "Removendo o serviço Controller Bridge..." + + if command -v systemctl >/dev/null 2>&1; then + systemctl --user stop \ + "$CONTROLLER_SERVICE" \ + >/dev/null 2>&1 || true + + systemctl --user disable \ + "$CONTROLLER_SERVICE" \ + >/dev/null 2>&1 || true + fi + + rm -f -- "$CONTROLLER_SERVICE_PATH" + + if command -v systemctl >/dev/null 2>&1; then + systemctl --user daemon-reload \ + >/dev/null 2>&1 || true + + systemctl --user reset-failed \ + "$CONTROLLER_SERVICE" \ + >/dev/null 2>&1 || true + fi + + SERVICE_REMOVED=true +} + + +remove_service_desktop_entries() { + local service_id + local removed=0 + + while IFS= read -r service_id; do + [[ -n "$service_id" ]] || continue + + local candidates=( + "$APPLICATIONS_DIR/${service_id}.desktop" + "$APPLICATIONS_DIR/steam-media-pack-${service_id}.desktop" + ) + + local desktop_file + + for desktop_file in "${candidates[@]}"; do + if [[ -f "$desktop_file" ]]; then + rm -f -- "$desktop_file" + ((removed += 1)) + fi + done + done < <(get_service_ids) + + info "$removed entrada(s) de aplicativo removida(s)." +} + + +remove_legacy_desktop_entries() { + local legacy_files=( + "$APPLICATIONS_DIR/netflix.desktop" + "$APPLICATIONS_DIR/prime-video.desktop" + "$APPLICATIONS_DIR/disney-plus.desktop" + "$APPLICATIONS_DIR/max.desktop" + "$APPLICATIONS_DIR/youtube-tv.desktop" + "$APPLICATIONS_DIR/spotify.desktop" + ) + + rm -f -- "${legacy_files[@]}" +} + + +remove_icons() { + local icon_directories=( + "$HOME/.local/share/icons/steam-media-pack" + "$HOME/.local/share/icons/hicolor/scalable/apps/steam-media-pack" + ) + + rm -rf -- "${icon_directories[@]}" + + local service_id + + while IFS= read -r service_id; do + [[ -n "$service_id" ]] || continue + + rm -f -- \ + "$HOME/.local/share/icons/hicolor/"*/apps/"${service_id}.png" \ + "$HOME/.local/share/icons/hicolor/"*/apps/"steam-media-pack-${service_id}.png" \ + "$HOME/.local/share/icons/hicolor/scalable/apps/${service_id}.svg" \ + "$HOME/.local/share/icons/hicolor/scalable/apps/steam-media-pack-${service_id}.svg" \ + 2>/dev/null || true + done < <(get_service_ids) +} + + +remove_installed_files() { + echo + info "Removendo arquivos instalados..." + + remove_service_desktop_entries + remove_legacy_desktop_entries + remove_icons + + rm -rf -- "$INSTALL_DIR" + + rm -f -- \ + "$HOME/.local/bin/controller-bridge" \ + "$HOME/.local/bin/steam-media-pack" \ + "$HOME/.local/bin/steam-media-pack-controller-bridge" + + if command -v update-desktop-database >/dev/null 2>&1; then + update-desktop-database \ + "$APPLICATIONS_DIR" \ + >/dev/null 2>&1 || true + fi + + if command -v gtk-update-icon-cache >/dev/null 2>&1; then + gtk-update-icon-cache \ + -f \ + -t \ + "$HOME/.local/share/icons/hicolor" \ + >/dev/null 2>&1 || true + fi + + FILES_REMOVED=true +} + + +remove_configuration() { + confirm_config_removal + + if [[ "$REMOVE_CONFIG" != true ]]; then + info "As configurações foram preservadas em: $CONFIG_DIR" + return + fi + + echo + info "Removendo configurações..." + + rm -rf -- "$CONFIG_DIR" + + CONFIG_REMOVED=true +} + + +print_summary() { + echo + echo "==============================================" + echo " Desinstalação concluída" + echo "==============================================" + echo + + if [[ "$SHORTCUTS_REMOVED" == true ]]; then + echo " ✓ Atalhos e artes da Steam processados" + else + echo " - Atalhos da Steam não foram encontrados" + fi + + if [[ "$SERVICE_REMOVED" == true ]]; then + echo " ✓ Serviço Controller Bridge removido" + fi + + if [[ "$FILES_REMOVED" == true ]]; then + echo " ✓ Arquivos do Steam Media Pack removidos" + fi + + if [[ "$CONFIG_REMOVED" == true ]]; then + echo " ✓ Configurações removidas" + else + echo " - Configurações preservadas" + fi + + echo +} -echo "Removendo Controller Bridge..." -systemctl --user disable --now steam-media-controller-bridge.service 2>/dev/null || true +main() { + parse_arguments "$@" -rm -f "$HOME/.config/systemd/user/steam-media-controller-bridge.service" + echo + echo "==============================================" + echo " ${APP_NAME} — Desinstalador" + echo "==============================================" + echo -systemctl --user daemon-reload + confirm_uninstallation + check_dependencies + check_steam_closed -if [ -f /etc/udev/rules.d/99-steam-media-controller-bridge.rules ]; then - sudo rm -f /etc/udev/rules.d/99-steam-media-controller-bridge.rules - sudo udevadm control --reload-rules - sudo udevadm trigger -fi + remove_steam_shortcuts + remove_controller_service + remove_installed_files + remove_configuration -rm -rf "$HOME/.local/share/steam-media-pack/controller-bridge" + print_summary +} -rm -rf "$DATA_HOME/steam-media-pack" -rm -rf "$CONFIG_HOME/steam-media-pack" -rm -f "$DATA_HOME/applications"/steam-media-*.desktop -rm -f "$DATA_HOME/icons/hicolor/scalable/apps"/steam-media-*.svg -echo "Steam Media Pack removido." +main "$@"