Added upgrade features, cat, multi-selector, new-menu

This commit is contained in:
2026-08-26 16:19:38 +01:00
parent 97d9ae202a
commit 9ebb62f13e
4 changed files with 1109 additions and 901 deletions
+110 -444
View File
@@ -9,13 +9,14 @@ Instead of placing everything directly inside `.bashrc`, this project lets you s
The project includes: The project includes:
- an installer - an automated intelligent installer with OS detection and automatic migration
- a command-line management tool - a command-line management tool (`brc-script`)
- a modular directory layout - a modular directory layout (`scripts-available`, `scripts-enabled`, `scripts-needed`, `scripts-removed`)
- default ready-to-use scripts - default ready-to-use scripts (Git highlights, multi-distro bashboard with Cockpit auto-detection, aliases)
- a reusable colored echo utility - a reusable colored echo utility (`ccecho`)
- Gitea update and self-upgrade mechanism
This makes it easier to add, remove, enable, disable, and maintain shell customizations without turning `.bashrc` into a long and messy file. This makes it easier to add, remove, enable, disable, preview, and maintain shell customizations without turning `.bashrc` into a long and messy file.
--- ---
@@ -24,44 +25,40 @@ This makes it easier to add, remove, enable, disable, and maintain shell customi
- **Modular setup** - **Modular setup**
Keep `.bashrc` organized by loading only the scripts you need. Keep `.bashrc` organized by loading only the scripts you need.
- **Script management** - **Intelligent Installer & Migration**
Create, enable, disable, remove, and modify scripts from a single command interface. Automatically migrates your pre-existing `.bashrc` into `00_default.sh` and enables it, cleans `.bashrc` to only contain the loader, and installs required tools (`jq`, `curl`) matching your Linux distribution.
- **Automatic directory structure** - **Multi-Script Management**
The installer creates all required folders for a modular Bash environment. Enable or disable multiple scripts in a single command using numerical IDs or script names (e.g. `brc-script -d 1 5 12 10` or `brc-script -e 01_git-cli-highlitgh 03_bashboard`).
- **Default scripts included** - **Quick Script Preview (`cat`)**
Three scripts are installed by default so users can start immediately. Inspect script content and line numbers directly from the terminal with `brc-script -p <id|name>` without opening text editors.
- **Easy integration** - **Cockpit Auto-Detection**
The project integrates with an existing Bash setup without requiring a full rewrite. `03_bashboard.sh` automatically detects if Cockpit is installed and running, discovers its listening port dynamically (from `/etc/cockpit/cockpit.conf`, systemd sockets, or 9090), and shows the direct URL.
- **Gitea Updates & Upgrades**
Check for project updates directly from Gitea with `brc-script --update` and upgrade core and standard scripts safely with `brc-script --upgrade` without touching your personal customizations.
- **Reusable utility functions** - **Reusable utility functions**
Includes `ccecho`, a colored echo helper for cleaner terminal output. Includes `ccecho`, a colored echo helper for cleaner terminal output.
- **Clean startup behavior**
Only required scripts are loaded at shell startup, keeping startup logic predictable.
--- ---
## How It Works ## How It Works
The system adds a small loader block to your `.bashrc`. The installer backs up your existing `.bashrc`, migrates its content into `~/.bashrc.d/scripts-available/00_default.sh`, enables it, and replaces `.bashrc` with a minimal loader block.
That block sources scripts from the modular directories: That block sources scripts from the modular directories:
- `scripts-needed/` - `scripts-needed/`
Essential scripts required for the system to work. Essential logic scripts required for the system to work (`brc-script.sh`, `ccecho.sh`).
- `scripts-enabled/` - `scripts-enabled/`
Scripts that should be loaded at shell startup. Scripts that should be loaded at shell startup (symlinks to `scripts-available/`).
- `scripts-available/` - `scripts-available/`
Scripts that are present but not automatically loaded. Scripts that are installed and ready to be enabled or customized.
- `scripts-removed/` - `scripts-removed/`
Scripts that were removed and stored as backups. Scripts that were removed and stored as timestamped backups.
The idea is simple: keep `.bashrc` minimal, and move all additional Bash logic into dedicated modular files.
--- ---
@@ -71,216 +68,28 @@ After installation, the system uses the following layout:
```text ```text
~/.bashrc.d/ ~/.bashrc.d/
├── .version
├── scripts-needed/ ├── scripts-needed/
│ ├── brc-script.sh │ ├── brc-script.sh
│ └── ccecho.sh │ └── ccecho.sh
├── scripts-available/ ├── scripts-available/
│ ├── 00_default.sh │ ├── 00_default.sh
│ ├── 01_git-cli-highlitgh.sh │ ├── 01_git-cli-highlitgh.sh
── 02_bashboard.sh ── 02_git-cli-highlitgh-root.sh
│ ├── 03_bashboard.sh
│ └── 04_aliases.sh
├── scripts-enabled/ ├── scripts-enabled/
│ └── 00_default.sh -> ~/.bashrc.d/scripts-available/00_default.sh
└── scripts-removed/ └── scripts-removed/
``` ```
### Folder Purpose
#### `scripts-needed/`
Contains the core scripts required by the project itself. These are loaded automatically and should not normally be disabled.
#### `scripts-available/`
Contains scripts that are installed and ready to be enabled. They are available for use but are not necessarily loaded at shell startup.
#### `scripts-enabled/`
Contains the scripts that are actively enabled and sourced when Bash starts.
#### `scripts-removed/`
Stores removed scripts as backups, usually with timestamps, so they can be restored later if needed.
---
## Default Scripts Included
The installer now copies three scripts into `scripts-available/` by default.
These scripts are included to provide immediate value and to demonstrate how the modular system can be used in practice.
---
### `00_default.sh` Modular Bashrc Introduction and Migration Helper
This script is intended as a starting point for users who are moving from a traditional `.bashrc` file to a modular Bash setup.
It explains the philosophy of the project and reminds the user that the modular loader block has already been added to `.bashrc`.
#### Main purpose
- show a welcome message
- explain the modular system
- remind the user how to keep `.bashrc` clean
- provide a safe place to move old custom Bash configuration
#### What to put in this script
You can move the following content from your old `.bashrc` into `00_default.sh`:
- aliases
- functions
- exports
- prompt customizations
- shell variables
- other custom Bash logic that you want loaded automatically
#### Recommended workflow
1. Open your `.bashrc`
2. Copy your personal customizations from the old file
3. Paste them into:
```bash
~/.bashrc.d/scripts-available/00_default.sh
```
4. Enable the script using:
```bash
brc-script -e
```
#### Important note
Do **not** remove the modular loader block from `.bashrc`.
That block is required so Bash can load the modular scripts at startup.
#### Typical content of `.bashrc`
Your `.bashrc` should stay lightweight and contain mainly the modular loader block plus any absolutely necessary minimal settings.
A typical loader block looks like this:
```bash
# Modular Bashrc
mkdir -p ~/.bashrc.d/scripts-needed
mkdir -p ~/.bashrc.d/scripts-enabled
mkdir -p ~/.bashrc.d/scripts-available
if [ -d ~/.bashrc.d ]; then
for needed in ~/.bashrc.d/scripts-needed/*.sh; do
[ -r "$needed" ] && source "$needed"
done
unset needed
for file in ~/.bashrc.d/scripts-enabled/*.sh; do
[ -r "$file" ] && source "$file"
done
unset file
fi
```
This keeps your shell configuration clean and maintainable.
---
### `01_git-cli-highlitgh.sh` Git-Aware Prompt Enhancement
This script improves the Bash prompt by showing useful Git repository information directly in the terminal.
It is especially useful for developers who frequently work inside Git repositories and want an immediate visual overview of the repository state.
#### What it does
The script defines a `parse_git_branch()` function that detects whether the current directory is inside a Git repository. If it is, it builds a status summary for the prompt.
#### Information shown in the prompt
- current branch name
- staged changes
- modified files
- untracked files
- remote ahead/behind status
#### Visual behavior
The script uses color-coded output to help distinguish repository states:
- **green** for a clean repository
- **purple** when there are uncommitted changes
- **cyan** for ahead/behind indicators
- additional colors for staged, modified, and untracked changes
#### Example prompt
```text
user@host:~/repo(main ↑1 +2 M:1 N:3)$
```
#### Notes
This script is useful for:
- developers
- DevOps users
- anyone working with Git directly in the terminal
---
### `02_bashboard.sh` Lightweight System Dashboard
This script displays a compact system dashboard directly in the terminal.
It is intended to give a quick overview of the machine without opening additional tools.
#### What it shows
- Linux distribution information
- hostname
- local IP addresses
- public IP address
- CPU usage
- RAM usage
- disk usage
- uptime
- load average
- available updates
- temperature, if available
#### Extra features
- Uses a cache directory in `/tmp` to avoid repeated network calls
- Avoids expensive update checks too frequently
- Can hide temperature information if the machine is a virtual machine
- Works best on Debian-based systems
#### Dependencies
This script requires:
- `curl`
- `lm-sensors`
You can install them with:
```bash
apt update && apt install curl lm-sensors
```
#### Practical use cases
This script is useful for:
- system administration
- quick health checks
- monitoring a remote box in a terminal
- showing a terminal dashboard at login or on demand
--- ---
## Installation ## Installation
The project can be installed using the included installer script.
### Automated Installation ### Automated Installation
1. Clone the repository: 1. Clone the repository from the official Gitea server:
```bash ```bash
git clone https://gitea.sld-server.org/sld-admin/Modular-Bashrc-Manager git clone https://gitea.sld-server.org/sld-admin/Modular-Bashrc-Manager
@@ -294,271 +103,128 @@ chmod +x brc-script-install.sh
./brc-script-install.sh ./brc-script-install.sh
``` ```
### What the installer does ### What the installer does:
- Detects the Linux distribution (`apt`, `dnf`, `yum`, `pacman`, `zypper`, `apk`, `brew`) and automatically installs `jq` and `curl` if missing.
- Creates timestamped backup of your current `.bashrc`.
- Automatically copies your existing `.bashrc` content into `~/.bashrc.d/scripts-available/00_default.sh` and enables it.
- Writes the clean modular loader block to `.bashrc`.
- Copies core scripts to `scripts-needed/` and default scripts to `scripts-available/`.
- Initializes the `.version` file for future update tracking.
The installer will: 3. Reload `.bashrc`:
- detect or ask which user should receive the installation
- create the modular directory structure
- back up the existing `.bashrc`
- append the required loader block to `.bashrc`
- copy the project files into `~/.bashrc.d/`
- copy the three default scripts into `scripts-available/`
- reload the shell configuration
3. Reload `.bashrc` if needed:
```bash ```bash
source ~/.bashrc source ~/.bashrc
# or run: refresh-brc
``` ```
--- ---
### Manual Installation ## Usage (`brc-script`)
If you prefer to install the project manually, you can do it step by step. The main command-line management tool is `brc-script`.
#### 1. Create the directory structure ### Available Commands
```bash | Command | Alias / Flags | Description |
mkdir -p ~/.bashrc.d/scripts-needed | :--- | :--- | :--- |
mkdir -p ~/.bashrc.d/scripts-enabled | **List Scripts** | `brc-script -l` / `--list` | Lists all available scripts and indicates active/enabled status (`-`). |
mkdir -p ~/.bashrc.d/scripts-available | **Preview / Cat Script** | `brc-script -p` / `--cat <id\|name ...>` | Prints script source code with line numbers and status without opening an editor. |
mkdir -p ~/.bashrc.d/scripts-removed | **Enable Script(s)** | `brc-script -e` / `--enable <id\|name ...>` | Enables one or multiple scripts by numeric ID or name. |
``` | **Disable Script(s)** | `brc-script -d` / `--disable <id\|name ...>` | Disables one or multiple scripts by numeric ID or name. |
| **Enable All** | `brc-script -ea` / `--enable-all` | Enables all available scripts. |
#### 2. Copy the core scripts into `scripts-needed/` | **Disable All** | `brc-script -da` / `--disable-all` | Disables all currently enabled scripts. |
| **Create Script** | `brc-script -c` / `--create` | Prompts for a name, generates a template, and opens it in your editor. |
```bash | **Modify Script** | `brc-script -m` / `--modify <id\|name>` | Opens a script in editor and allows renaming. |
cp brc-script.sh ccecho.sh ~/.bashrc.d/scripts-needed/ | **Remove Script** | `brc-script -r` / `--remove <id\|name ...>` | Moves script(s) to `scripts-removed/` with a timestamp. |
chmod 750 ~/.bashrc.d/scripts-needed/brc-script.sh ~/.bashrc.d/scripts-needed/ccecho.sh | **Check Updates** | `brc-script -u` / `--update` | Queries Gitea repository for latest commits and new updates. |
``` | **Upgrade System** | `brc-script --upgrade` | Upgrades core and default scripts from Gitea (never touches `00_default.sh`). |
| **Reload Shell** | `refresh-brc` | Reloads `.bashrc` in current session. |
#### 3. Add the modular loader block to `.bashrc`
Append this block to the end of your `.bashrc` file:
```bash
# Modular Bashrc
mkdir -p ~/.bashrc.d/scripts-needed
mkdir -p ~/.bashrc.d/scripts-enabled
mkdir -p ~/.bashrc.d/scripts-available
if [ -d ~/.bashrc.d ]; then
for needed in ~/.bashrc.d/scripts-needed/*.sh; do
[ -r "$needed" ] && source "$needed"
done
unset needed
for file in ~/.bashrc.d/scripts-enabled/*.sh; do
[ -r "$file" ] && source "$file"
done
unset file
fi
```
#### 4. Copy the default scripts into `scripts-available/`
```bash
cp 00_default.sh 01_git-cli-highlitgh.sh 02_bashboard.sh ~/.bashrc.d/scripts-available/
ln -s ~/.bashrc.d/scripts-available/00_default.sh ~/.bashrc.d/scripts-enabled/00_default.sh
ln -s ~/.bashrc.d/scripts-available/01_git-cli-highlitgh.sh ~/.bashrc.d/scripts-enabled/01_git-cli-highlitgh.sh
ln -s ~/.bashrc.d/scripts-available/02_bashboard.sh ~/.bashrc.d/scripts-enabled/02_bashboard.sh
```
#### 5. Reload the shell
```bash
source ~/.bashrc
```
--- ---
## Usage ### Command Examples
The main management tool is `brc-script.sh`.
It can be used to manage scripts stored in the modular directories.
### Common commands
- `brc-script -c`
Create a new script in `scripts-available/`
- `brc-script -m`
Modify an existing script
- `brc-script -l`
List all available and enabled scripts
- `brc-script -e`
Enable a script from `scripts-available/`
- `brc-script -d`
Disable an enabled script
- `brc-script -r`
Remove a script and store it in `scripts-removed/`
### Example usage
#### 1. Listing scripts
```bash ```bash
brc-script -c
brc-script -l brc-script -l
brc-script -e ```
brc-script -d
brc-script -r #### 2. Enabling multiple scripts at once (by ID or Name)
```bash
# Enable by multiple IDs
brc-script -e 1 3 4
# Enable by script names (with or without .sh)
brc-script -e 01_git-cli-highlitgh 03_bashboard
```
#### 3. Disabling multiple scripts at once
```bash
# Disable multiple IDs
brc-script -d 1 5 12 10
# Disable by name
brc-script -d 03_bashboard 04_aliases
```
#### 4. Quick viewing / catting script contents
```bash
# Preview by name
brc-script -p 03_bashboard
# Preview by numerical ID
brc-script --cat 2
```
#### 5. Checking and applying Gitea updates
```bash
# Check if new versions or commits are available
brc-script --update
# Perform safe self-upgrade from Gitea
brc-script --upgrade
``` ```
--- ---
## How to Use `00_default.sh` Correctly ## Included Default Scripts
`00_default.sh` is the ideal place to move your personal Bash customizations. ### `00_default.sh` Personal Configuration & Migration
Contains all your original aliases, functions, and environment variables migrated during installation. This file is yours and is never overwritten during upgrades.
### Move here from your old `.bashrc` ### `01_git-cli-highlitgh.sh` & `02_git-cli-highlitgh-root.sh` Git Prompt
Shows branch name, uncommitted changes, staged files, untracked files, and ahead/behind remote indicators directly in your prompt.
You can place inside `00_default.sh`: ### `03_bashboard.sh` Terminal System Dashboard
Displays CPU, RAM, disk usage, IP addresses, distro info, uptime, available packages updates, and automatically discovers **Cockpit Web UI** if installed (with dynamic port detection).
- alias definitions ### `04_aliases.sh` Common Aliases
- functions Useful starting aliases such as `alias ls="ls --color"`.
- environment variables
- exports
- shell helpers
- custom startup commands
### Keep out of `.bashrc`
The following should stay out of the main `.bashrc` file as much as possible:
- large alias blocks
- long function definitions
- extra startup logic
- custom prompts
- project-specific utilities
### Recommended structure
Your `.bashrc` should contain:
- the modular loader block
- only the minimum required shell settings
Everything else should live in modular scripts such as `00_default.sh`.
This approach makes your shell configuration:
- easier to read
- easier to debug
- easier to backup
- easier to share between machines
--- ---
## Extra Utilities ## Extra Utilities: `ccecho`
### `ccecho` Colored Echo for Better Terminal Output The project includes `ccecho.sh` in `scripts-needed/` for formatted and colored terminal output.
The project includes a reusable utility script called `ccecho.sh`, located in `scripts-needed/`.
It defines a `ccecho` function for printing styled and colored text to the terminal.
#### Example usage
```bash ```bash
ccecho -t green -b black -s bold "Success!" ccecho -t green -b black -s bold "Success!"
ccecho -t red -s underline "Error!" ccecho -t red -s underline "Error!"
ccecho "Normal message without styling"
``` ```
#### Available text colors **Text colors:** `black`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, `white`, `bblack`, `bred`, `bgreen`, `byellow`, `bblue`, `bmagenta`, `bcyan`, `bwhite`.
**Styles:** `bold`, `dim`, `italic`, `underline`, `blink`, `reverse`, `hidden`, `strike`.
- `black`
- `red`
- `green`
- `yellow`
- `blue`
- `magenta`
- `cyan`
- `white`
- `bblack`
- `bred`
- `bgreen`
- `byellow`
- `bblue`
- `bmagenta`
- `bcyan`
- `bwhite`
#### Background colors
The same color names can be used with `-b`.
#### Styles
- `bold`
- `dim`
- `italic`
- `underline`
- `blink`
- `reverse`
- `hidden`
- `strike`
#### Make `ccecho` available in other sessions
If you want to use `ccecho` in other terminal sessions or scripts, source it from `.bashrc`:
```bash
source ~/.bashrc.d/scripts-needed/ccecho.sh
```
--- ---
## Why Use This System? ## Official Repository & Updates
Managing a large `.bashrc` file can quickly become difficult, especially when multiple aliases, functions, and startup commands are added over time. - **Gitea:** [https://gitea.sld-server.org/sld-admin/Modular-Bashrc-Manager](https://gitea.sld-server.org/sld-admin/Modular-Bashrc-Manager)
- **Author:** Simone Cusano ([https://sld-server.org](https://sld-server.org))
This system solves that problem by separating your Bash configuration into small, focused files.
### Benefits
- **Organization**
Keep your shell configuration structured and easier to understand.
- **Maintainability**
Update one script without editing a huge `.bashrc` file.
- **Safety**
Removed scripts are backed up in `scripts-removed/`.
- **Flexibility**
Enable or disable features without rewriting your shell setup.
- **Reusability**
Share modular scripts across systems more easily.
---
## Contributing
Contributions are welcome.
If you find bugs, edge cases, or improvements, feel free to open an issue or submit a pull request.
Possible improvements include:
- support for more shells
- richer installer feedback
- logging and debug mode
- better script validation
- package-based installation
--- ---
## License ## License
This project is licensed under the GNU General Public License v3.0. This project is licensed under the GNU General Public License v3.0.
For more information, see the [GPL v3 license](https://www.gnu.org/licenses/gpl-3.0.html).
+170 -135
View File
@@ -1,168 +1,204 @@
#!/bin/bash
############# DEPENDENCIES ############# ############# DEPENDENCIES #############
# - Debian Based OS (for now)
# - curl # - curl
# - lm-sensors # - lm-sensors (optional for temp)
# apt update && apt install curl lm-sensors # - jq (optional)
############################################ ############################################
colorize() { colorize() {
local value=$1 local value=$1
local green_limit=$2 local green_limit=$2
local yellow_limit=$3 local yellow_limit=$3
if [ "$value" -lt "$green_limit" ]; then if [ "$value" -lt "$green_limit" ]; then
echo -e "${GREEN}${value}${NC}" echo -e "${GREEN}${value}${NC}"
elif [ "$value" -lt "$yellow_limit" ]; then elif [ "$value" -lt "$yellow_limit" ]; then
echo -e "${YELLOW}${value}${NC}" echo -e "${YELLOW}${value}${NC}"
else else
echo -e "${RED}${value}${NC}" echo -e "${RED}${value}${NC}"
fi fi
} }
function dashboard_fast() { function dashboard_fast() {
#### CHANGABLE OPTIONS #### #### CHANGABLE OPTIONS ####
ISTHISVM=0 # Change to 1 if this is a VM. This will remove the temperature bit. ISTHISVM=0 # Change to 1 if this is a VM. This will remove the temperature bit.
MIN_CHECK_IP=30 # Change this value to set the timing cache for checking the public IP. MIN_CHECK_IP=30 # Timing cache (minutes) for checking the public IP.
MIN_CHECK_UPDATE=120 # Change this value to set the timing cache for checking updates. MIN_CHECK_UPDATE=120 # Timing cache (minutes) for checking updates.
LOCAL_CACHE=1 # Change this value to 1 if you want to create the local cache in the ~/.bashrc.d/.dashboard_cache. LOCAL_CACHE=1 # 1: ~/.bashrc.d/.dashboard_cache, 0: /tmp/.dashboard_cache
UI_SHOWS=1 # Change to 1 if cockpit has been installed. This will shows the IP and port Link.
#### Colors ####
GREEN="\e[32m"
YELLOW="\e[33m"
RED="\e[31m"
CYAN="\e[36m"
BOLD="\e[1m"
NC="\e[0m" # reset
#### Cache ####
if [ $LOCAL_CACHE -ne 1 ]; then
CACHE_DIR="/tmp/.dashboard_cache"
else
CACHE_DIR="${HOME}/.bashrc.d/.dashboard_cache"
fi
mkdir -p "$CACHE_DIR" 2>/dev/null
#### Overview ####
echo -e "${CYAN}========================================${NC}"
echo -e "${BOLD} 🖥️ SYSTEM OVERVIEW${NC}"
echo -e "${CYAN}========================================${NC}"
#### Colors #### #### OS Informations Include ####
GREEN="\e[32m" if [ -f /etc/os-release ]; then
YELLOW="\e[33m" # shellcheck disable=SC1091
RED="\e[31m"
CYAN="\e[36m"
BOLD="\e[1m"
NC="\e[0m" # reset
#### Cache ####
if [ $LOCAL_CACHE -ne 1 ]; then
CACHE_DIR="/tmp/.dashboard_cache"
else
CACHE_DIR="/home/$(whoami)/.bashrc.d/.dashboard_cache"
fi
mkdir -p "$CACHE_DIR"
#### Overview ####
echo -e "${CYAN}========================================${NC}"
echo -e "${BOLD} 🖥️ SYSTEM OVERVIEW${NC}"
echo -e "${CYAN}========================================${NC}"
#### OS Informations Include ####
source /etc/os-release source /etc/os-release
echo -e "${CYAN}DISTRO:${NC} ${PRETTY_NAME:-$ID}"
#### OS info ###
echo -e "${CYAN}DISTRO:${NC} $PRETTY_NAME"
echo -e "${CYAN}ID:${NC} $ID" echo -e "${CYAN}ID:${NC} $ID"
echo -e "${CYAN}VERSION:${NC} $VERSION" [ -n "$VERSION" ] && echo -e "${CYAN}VERSION:${NC} $VERSION"
echo -e "${CYAN}URL:${NC} $HOME_URL" [ -n "$HOME_URL" ] && echo -e "${CYAN}URL:${NC} $HOME_URL"
echo -e "${CYAN}BUGS_URL:${NC} $BUG_REPORT_URL" [ -n "$BUG_REPORT_URL" ] && echo -e "${CYAN}BUGS_URL:${NC} $BUG_REPORT_URL"
echo -e "${CYAN}========================================${NC}" echo -e "${CYAN}========================================${NC}"
fi
#### Hostname #### #### Hostname ####
echo "📛 $(hostname)" echo "📛 $(hostname)"
#### Local IP ####
LOCAL_IPS=$(hostname -I 2>/dev/null | xargs)
PRIMARY_IP=$(echo "$LOCAL_IPS" | awk '{print $1}')
#### Local IP #### if [ -z "$LOCAL_IPS" ]; then
LOCAL_IPS=$(hostname -I 2>/dev/null | xargs) echo "🏠 Local IP: NOT AVAILABLE (no network?)"
PRIMARY_IP=$(echo "$LOCAL_IPS" | awk '{print $1}') else
echo "🏠 Local IP: $LOCAL_IPS"
fi
if [ -z "$LOCAL_IPS" ]; then #### Cockpit Web UI Auto-Detection ####
echo "🏠 Local IP: NOT AVAILABLE (no network?)" COCKPIT_DETECTED=0
if [ $UI_SHOWS -eq 1 ]; then echo "🌐 Web UI: NOT AVAILABLE"; fi COCKPIT_PORT=""
else
echo "🏠 Local IP: $LOCAL_IPS" # Check if cockpit is installed or socket/service exists
if [ $UI_SHOWS -eq 1 ]; then echo "🌐 Web UI: http://$PRIMARY_IP:9090"; fi if command -v cockpit-ws >/dev/null 2>&1 || command -v cockpit-bridge >/dev/null 2>&1 || [ -d /etc/cockpit ] || systemctl list-unit-files 2>/dev/null | grep -q "cockpit.socket"; then
COCKPIT_DETECTED=1
# 1. Search port in /etc/cockpit/cockpit.conf
if [ -f /etc/cockpit/cockpit.conf ]; then
COCKPIT_PORT=$(grep -Ei '^\s*(Port|Listen)\s*=' /etc/cockpit/cockpit.conf 2>/dev/null | head -n1 | awk -F= '{print $2}' | tr -d ' ')
fi fi
# 2. Search port in systemd socket definition
#### Public IP #### if [ -z "$COCKPIT_PORT" ] && command -v systemctl >/dev/null 2>&1; then
if [ -f "$CACHE_DIR/public_ip" ] && find "$CACHE_DIR/public_ip" -mmin -$MIN_CHECK_IP | grep -q .; then COCKPIT_PORT=$(systemctl cat cockpit.socket 2>/dev/null | grep -E '^ListenStream=' | head -n1 | awk -F= '{print $2}' | tr -d ' ')
PUBLIC_IP=$(cat "$CACHE_DIR/public_ip")
else
PUBLIC_IP=$(timeout 2 curl -s ifconfig.me 2>/dev/null)
if [ -n "$PUBLIC_IP" ]; then
echo "$PUBLIC_IP" > "$CACHE_DIR/public_ip"
fi
fi fi
if [ -z "$PUBLIC_IP" ]; then # 3. Search port in listening sockets
echo "🌍 Public IP: NOT AVAILABLE (no internet?)" if [ -z "$COCKPIT_PORT" ] && command -v ss >/dev/null 2>&1; then
else COCKPIT_PORT=$(ss -tlnp 2>/dev/null | grep -E 'cockpit|cockpit-ws' | awk '{print $4}' | awk -F: '{print $NF}' | head -n1)
echo "🌍 Public IP: $PUBLIC_IP"
fi fi
#echo ""
echo -e "${CYAN} .................................. ${NC}"
#### Cpu #### # 4. Default fallback port for Cockpit is 9090
if [ -z "$COCKPIT_PORT" ]; then
COCKPIT_PORT=9090
fi
fi
if [ $COCKPIT_DETECTED -eq 1 ] && [ -n "$PRIMARY_IP" ]; then
echo -e "🌐 Cockpit UI: ${GREEN}https://${PRIMARY_IP}:${COCKPIT_PORT}${NC}"
fi
#### Public IP ####
if [ -f "$CACHE_DIR/public_ip" ] && find "$CACHE_DIR/public_ip" -mmin -$MIN_CHECK_IP | grep -q . 2>/dev/null; then
PUBLIC_IP=$(cat "$CACHE_DIR/public_ip" 2>/dev/null)
else
PUBLIC_IP=$(timeout 2 curl -s ifconfig.me 2>/dev/null)
if [ -n "$PUBLIC_IP" ]; then
echo "$PUBLIC_IP" > "$CACHE_DIR/public_ip" 2>/dev/null
fi
fi
if [ -z "$PUBLIC_IP" ]; then
echo "🌍 Public IP: NOT AVAILABLE (no internet?)"
else
echo "🌍 Public IP: $PUBLIC_IP"
fi
echo -e "${CYAN} .................................. ${NC}"
#### Cpu ####
if [ -r /proc/loadavg ]; then
LOAD=$(awk '{print $1}' /proc/loadavg) LOAD=$(awk '{print $1}' /proc/loadavg)
CPU_PCT=$(awk -v l="$LOAD" -v n="$(nproc)" 'BEGIN {printf "%d", (l*100/n)}') CPU_PCT=$(awk -v l="$LOAD" -v n="$(nproc 2>/dev/null || echo 1)" 'BEGIN {printf "%d", (l*100/n)}')
CPU_COLOR=$(colorize "$CPU_PCT" 50 80) CPU_COLOR=$(colorize "$CPU_PCT" 50 80)
echo -e "🧠 CPU: ${CPU_COLOR}%" echo -e "🧠 CPU: ${CPU_COLOR}%"
fi
#### Ram ####
#### Ram #### if command -v free >/dev/null 2>&1; then
read MEM_TOTAL MEM_USED <<< $(free -m | awk '/Mem:/ {print $2, $3}') read -r MEM_TOTAL MEM_USED <<< "$(free -m | awk '/Mem:/ {print $2, $3}')"
MEM_PCT=$((MEM_USED * 100 / MEM_TOTAL)) if [ -n "$MEM_TOTAL" ] && [ "$MEM_TOTAL" -gt 0 ]; then
MEM_COLOR=$(colorize "$MEM_PCT" 50 80) MEM_PCT=$((MEM_USED * 100 / MEM_TOTAL))
echo -e "💾 RAM: ${MEM_COLOR}% (${MEM_USED}/${MEM_TOTAL}MB)" MEM_COLOR=$(colorize "$MEM_PCT" 50 80)
echo -e "💾 RAM: ${MEM_COLOR}% (${MEM_USED}/${MEM_TOTAL}MB)"
#### Diskspace ####
DISK_PCT=$(df / | awk 'NR==2 {gsub("%",""); print $5}')
DISK_COLOR=$(colorize "$DISK_PCT" 50 80)
DISK=$(df -h / | awk 'NR==2 {print $3 "/" $2}')
echo -e "📦 Disk: ${DISK} (${DISK_COLOR}%)"
#### Uptime ####
echo "⏱️ Uptime: $(awk '{printf "%dd %dh %dm", $1/86400, ($1%86400)/3600, ($1%3600)/60}' /proc/uptime)"
#### Load Avarage ####
echo "📊 Load avg: $(awk '{print $1, $2, $3}' /proc/loadavg)"
#### Updates ####
if command -v apt >/dev/null 2>&1; then
if [ -f "$CACHE_DIR/updates" ] && find "$CACHE_DIR/updates" -mmin -$MIN_CHECK_UPDATE | grep -q .; then
UPDATES=$(cat "$CACHE_DIR/updates")
else
UPDATES=$(apt list --upgradable 2>/dev/null | wc -l)
UPDATES=$((UPDATES - 1))
echo "$UPDATES" > "$CACHE_DIR/updates"
fi
## 🎨 Dinamic Color ##
if [ "$UPDATES" -eq 0 ]; then
UPD_COLOR="${GREEN}${UPDATES}${NC}"
elif [ "$UPDATES" -le 20 ]; then
UPD_COLOR="${YELLOW}${UPDATES}${NC}"
else
UPD_COLOR="${RED}${UPDATES}${NC}"
fi
echo -e "📦 Updates: $UPD_COLOR"
else
echo "📦 Updates: N/A"
fi fi
fi
#### Diskspace ####
if command -v df >/dev/null 2>&1; then
DISK_PCT=$(df / 2>/dev/null | awk 'NR==2 {gsub("%",""); print $5}')
DISK_COLOR=$(colorize "${DISK_PCT:-0}" 50 80)
DISK=$(df -h / 2>/dev/null | awk 'NR==2 {print $3 "/" $2}')
echo -e "📦 Disk: ${DISK} (${DISK_COLOR}%)"
fi
#### Uptime ####
if [ -r /proc/uptime ]; then
echo "⏱️ Uptime: $(awk '{printf "%dd %dh %dm", $1/86400, ($1%86400)/3600, ($1%3600)/60}' /proc/uptime)"
fi
#### Temperature #### #### Load Average ####
if [ $ISTHISVM -ne 1 ]; then if [ -r /proc/loadavg ]; then
if [ -f /sys/class/thermal/thermal_zone0/temp ]; then echo "📊 Load avg: $(awk '{print $1, $2, $3}' /proc/loadavg)"
TEMP_RAW=$(cat /sys/class/thermal/thermal_zone0/temp) fi
#### Updates (Cross-Distro) ####
if [ -f "$CACHE_DIR/updates" ] && find "$CACHE_DIR/updates" -mmin -$MIN_CHECK_UPDATE | grep -q . 2>/dev/null; then
UPDATES=$(cat "$CACHE_DIR/updates" 2>/dev/null)
else
UPDATES=0
if command -v apt >/dev/null 2>&1; then
UPDATES=$(apt list --upgradable 2>/dev/null | grep -c "upgradable from" 2>/dev/null || true)
elif command -v dnf >/dev/null 2>&1; then
UPDATES=$(dnf check-update -q 2>/dev/null | grep -E '\.(x86_64|noarch|aarch64|i686)' | wc -l)
elif command -v pacman >/dev/null 2>&1; then
UPDATES=$(checkupdates 2>/dev/null | wc -l || pacman -Qu 2>/dev/null | wc -l)
elif command -v zypper >/dev/null 2>&1; then
UPDATES=$(zypper list-updates 2>/dev/null | grep -c '^v ' || true)
elif command -v apk >/dev/null 2>&1; then
UPDATES=$(apk version -l '<' 2>/dev/null | wc -l)
else
UPDATES="N/A"
fi
echo "$UPDATES" > "$CACHE_DIR/updates" 2>/dev/null
fi
## Dynamic Color for Updates ##
if [[ "$UPDATES" =~ ^[0-9]+$ ]]; then
if [ "$UPDATES" -eq 0 ]; then
UPD_COLOR="${GREEN}${UPDATES}${NC}"
elif [ "$UPDATES" -le 20 ]; then
UPD_COLOR="${YELLOW}${UPDATES}${NC}"
else
UPD_COLOR="${RED}${UPDATES}${NC}"
fi
echo -e "📦 Updates: $UPD_COLOR"
else
echo "📦 Updates: N/A"
fi
#### Temperature ####
if [ $ISTHISVM -ne 1 ]; then
if [ -f /sys/class/thermal/thermal_zone0/temp ]; then
TEMP_RAW=$(cat /sys/class/thermal/thermal_zone0/temp 2>/dev/null)
if [ -n "$TEMP_RAW" ]; then
TEMP=$((TEMP_RAW/1000)) TEMP=$((TEMP_RAW/1000))
if [ "$TEMP" -lt 50 ]; then if [ "$TEMP" -lt 50 ]; then
@@ -176,12 +212,11 @@ function dashboard_fast() {
echo -e "🌡️ Temp: $TEMP_COLOR" echo -e "🌡️ Temp: $TEMP_COLOR"
fi fi
fi fi
fi
echo -e "${CYAN}========================================${NC}" echo -e "${CYAN}========================================${NC}"
} }
if [[ $- == *i* ]]; then if [[ $- == *i* ]]; then
dashboard_fast dashboard_fast
fi fi
+151 -37
View File
@@ -8,11 +8,75 @@ pause() {
read -rp "Press Enter to continue..." read -rp "Press Enter to continue..."
} }
debmess(){ # ========================
$debdescription="$1" # OS & DEPENDENCIES
echo "DEBUG MESSAGE: $debdescription" # ========================
echo "Press enter to continue..." install_dependencies() {
read debmess echo "============================================="
echo "[ Checking and installing dependencies... ]"
echo "============================================="
local need_jq=0
local need_curl=0
if ! command -v jq >/dev/null 2>&1; then
need_jq=1
fi
if ! command -v curl >/dev/null 2>&1; then
need_curl=1
fi
if [[ $need_jq -eq 0 && $need_curl -eq 0 ]]; then
echo " -> Dependencies (jq, curl) are already installed."
return 0
fi
local sudo_cmd=""
if [[ "$EUID" -ne 0 ]] && command -v sudo >/dev/null 2>&1; then
sudo_cmd="sudo"
fi
# Distro detection
local distro=""
if [[ -f /etc/os-release ]]; then
# shellcheck disable=SC1091
source /etc/os-release
distro="${ID:-unknown}"
echo " -> Detected OS: ${PRETTY_NAME:-$distro}"
fi
echo " -> Installing required packages (jq, curl)..."
if command -v apt-get >/dev/null 2>&1; then
echo " -> Using apt package manager..."
$sudo_cmd apt-get update -qq && $sudo_cmd apt-get install -y jq curl
elif command -v dnf >/dev/null 2>&1; then
echo " -> Using dnf package manager..."
$sudo_cmd dnf install -y jq curl
elif command -v yum >/dev/null 2>&1; then
echo " -> Using yum package manager..."
$sudo_cmd yum install -y jq curl
elif command -v pacman >/dev/null 2>&1; then
echo " -> Using pacman package manager..."
$sudo_cmd pacman -Sy --noconfirm jq curl
elif command -v zypper >/dev/null 2>&1; then
echo " -> Using zypper package manager..."
$sudo_cmd zypper --non-interactive in jq curl
elif command -v apk >/dev/null 2>&1; then
echo " -> Using apk package manager..."
$sudo_cmd apk add --no-cache jq curl
elif command -v brew >/dev/null 2>&1; then
echo " -> Using Homebrew..."
brew install jq curl
else
echo " -> [WARNING] No supported package manager found. Please install 'jq' and 'curl' manually."
fi
if command -v jq >/dev/null 2>&1; then
echo " -> [OK] jq is installed."
else
echo " -> [WARNING] jq could not be installed automatically."
fi
} }
select_user() { select_user() {
@@ -31,7 +95,7 @@ select_user() {
exit 1 exit 1
elif [[ -d "/home/$choice" ]]; then elif [[ -d "/home/$choice" ]]; then
read -rp "Confirm user '$choice'? (y/N): " confirm read -rp "Confirm user '$choice'? (y/N): " confirm
if [[ "$confirm" == "y" ]]; then if [[ "$confirm" == "y" || "$confirm" == "Y" ]]; then
selected_user="$choice" selected_user="$choice"
return return
fi fi
@@ -68,8 +132,8 @@ while true; do
exit 1 exit 1
;; ;;
*) *)
read -rp "Confirm current user '$current_user'? (y/N): " confirm read -rp "Confirm current user '$current_user'? (Y/n): " confirm
if [[ "$confirm" == "y" ]]; then if [[ "$confirm" == "y" || "$confirm" == "Y" || -z "$confirm" ]]; then
selected_user="$current_user" selected_user="$current_user"
break break
fi fi
@@ -79,16 +143,21 @@ while true; do
clear clear
done done
# ========================
# DEPENDENCIES CHECK
# ========================
install_dependencies
# ======================== # ========================
# VARIABLES # VARIABLES
# ======================== # ========================
if [ "$selected_user" == "root" ]; then if [ "$selected_user" == "root" ]; then
home="/root" home="/root"
bashrc="$home/.bashrc" bashrc="$home/.bashrc"
else else
home="/home/$selected_user" home="/home/$selected_user"
bashrc="$home/.bashrc" bashrc="$home/.bashrc"
fi fi
mainfolder="$home/.bashrc.d" mainfolder="$home/.bashrc.d"
@@ -102,30 +171,62 @@ script_dir="$(cd "$(dirname "$0")" && pwd)"
# ======================== # ========================
# CREATE DIRECTORIES # CREATE DIRECTORIES
# ======================== # ========================
echo "[ Creating folders... ]" echo ""
echo "[ Creating modular directories... ]"
#mkdir -p "$neededfolder" mkdir -p "$neededfolder"
mkdir -p "$availablefolder" mkdir -p "$availablefolder"
mkdir -p "$enabledfolder" mkdir -p "$enabledfolder"
mkdir -p "$removedfolder" mkdir -p "$removedfolder"
# ======================== # ========================
# BACKUP .bashrc # BACKUP AND MIGRATE .bashrc
# ======================== # ========================
backup_file="$home/bashrc-backup-$(date +%F_%H-%M-%S)"
if [[ -f "$bashrc" ]]; then if [[ -f "$bashrc" ]]; then
cp "$bashrc" "$home/bashrc-backup-$(date +%F)" cp "$bashrc" "$backup_file"
echo "[ Backup created ]" echo "[ Backup created at $backup_file ]"
# Check if existing bashrc has meaningful content (excluding empty lines and existing modular block)
cleaned_bashrc=$(grep -v "Modular Bashrc" "$bashrc" | grep -v "scripts-needed" | grep -v "scripts-enabled" | grep -v "scripts-available" | tr -d '[:space:]')
if [[ -n "$cleaned_bashrc" ]]; then
echo "[ Migrating existing .bashrc content into 00_default.sh... ]"
cat << 'EOF' > "$availablefolder/00_default.sh"
#!/bin/bash
# ============================================================
# Modular Bashrc - 00_default.sh
# Migrated automatically from your pre-existing ~/.bashrc
# Add your custom exports, aliases and functions here!
# ============================================================
EOF
cat "$bashrc" >> "$availablefolder/00_default.sh"
echo "" >> "$availablefolder/00_default.sh"
# Automatically enable 00_default.sh so user keeps their previous configuration active
ln -sf "$availablefolder/00_default.sh" "$enabledfolder/00_default.sh"
echo " -> [OK] 00_default.sh created and enabled in scripts-enabled/"
else
if [[ -f "$script_dir/00_default.sh" ]]; then
cp "$script_dir/00_default.sh" "$availablefolder/00_default.sh"
echo " -> Copied standard 00_default.sh template"
fi
fi
else else
echo "[ WARNING: .bashrc not found, creating a new one ]" echo "[ WARNING: .bashrc not found, creating modular base ]"
touch "$bashrc" if [[ -f "$script_dir/00_default.sh" ]]; then
cp "$script_dir/00_default.sh" "$availablefolder/00_default.sh"
fi
fi fi
# ======================== # ========================
# MODIFY .bashrc # WRITE CLEAN .bashrc
# ======================== # ========================
if [[ -f "$script_dir/NEEDED-FOR-INSTALLER" ]]; then if [[ -f "$script_dir/NEEDED-FOR-INSTALLER" ]]; then
cat "$script_dir/NEEDED-FOR-INSTALLER" >> "$bashrc" cat "$script_dir/NEEDED-FOR-INSTALLER" > "$bashrc"
echo "[ Updated .bashrc ]" echo "[ Updated .bashrc with clean modular loader ]"
else else
echo "[ ERROR: NEEDED-FOR-INSTALLER missing ]" echo "[ ERROR: NEEDED-FOR-INSTALLER missing ]"
exit 1 exit 1
@@ -135,20 +236,22 @@ fi
# COPY NEEDED SCRIPTS # COPY NEEDED SCRIPTS
# ======================== # ========================
needed_to_copy="$script_dir/scripts-needed" needed_to_copy="$script_dir/scripts-needed"
cp -r $needed_to_copy $mainfolder if [[ -d "$needed_to_copy" ]]; then
echo "[ Main logic scripts installed ]" cp -r "$needed_to_copy"/* "$neededfolder/"
chmod 750 "$neededfolder"/*.sh 2>/dev/null
echo "[ Main logic scripts installed in scripts-needed ]"
fi
# ======================== # ========================
# COPY DEFAULT SCRIPTS # COPY DEFAULT SCRIPTS
# ======================== # ========================
echo "[ Installing default scripts... ]" echo "[ Installing default available scripts... ]"
default_scripts=( default_scripts=(
"00_default.sh"
"01_git-cli-highlitgh.sh" "01_git-cli-highlitgh.sh"
"02_git-cli-highlitgh-root.sh" "02_git-cli-highlitgh-root.sh"
"03_bashboard.sh" "03_bashboard.sh"
"04_aliases" "04_aliases.sh"
) )
for script in "${default_scripts[@]}"; do for script in "${default_scripts[@]}"; do
@@ -160,19 +263,24 @@ for script in "${default_scripts[@]}"; do
fi fi
done done
# ======================== # Save version/commit information if inside git repo
# APPLY CHANGES repo_dir="$(cd "$script_dir/.." && pwd)"
# ======================== if git -C "$repo_dir" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
# shellcheck disable=SC1090 current_commit=$(git -C "$repo_dir" rev-parse HEAD 2>/dev/null)
#source "$bashrc" echo "$current_commit" > "$mainfolder/.version"
source ~/.bashrc else
echo "[ Bashrc reloaded ]" date +%s > "$mainfolder/.version"
fi
# Fix ownership if running as root for a normal user
if [[ "$current_user" == "root" && "$selected_user" != "root" ]]; then
chown -R "$selected_user":"$selected_user" "$mainfolder" "$bashrc" "$backup_file" 2>/dev/null
fi
pause
# ======================== # ========================
# FINAL MESSAGE # FINAL MESSAGE
# ======================== # ========================
clear echo ""
echo "##################################" echo "##################################"
echo " Installation Done " echo " Installation Done "
echo "##################################" echo "##################################"
@@ -182,8 +290,14 @@ echo " $availablefolder"
echo "" echo ""
echo "Use commands:" echo "Use commands:"
echo " brc-script -> manage scripts" echo " brc-script -> manage scripts"
echo " brc-script -l -> list scripts"
echo " brc-script --cat -> preview a script"
echo " brc-script -e -> enable script(s)"
echo " brc-script -d -> disable script(s)"
echo " brc-script --update -> check Gitea updates"
echo " brc-script --upgrade -> upgrade scripts"
echo " refresh-brc -> reload config" echo " refresh-brc -> reload config"
echo "" echo ""
echo "##################################" echo "##################################"
echo " Thanks for using this script! " echo " Thanks for using Modular Bashrc! "
echo "##################################" echo "##################################"
File diff suppressed because it is too large Load Diff