From f65d79fd7ab532ddfe6d2063977e365c07529b1d Mon Sep 17 00:00:00 2001 From: MeghdadFadaee <61308304+MeghdadFadaee@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:51:31 +0330 Subject: [PATCH] Initial public release of ShellGleam --- .gitattributes | 1 + .github/ISSUE_TEMPLATE/bug_report.md | 22 + .github/dependabot.yml | 6 + .github/workflows/ci.yml | 23 + .github/workflows/pages.yml | 41 + .gitignore | 13 + CHANGELOG.md | 8 + CONTRIBUTING.md | 22 + LICENSE | 21 + README.md | 157 +++ SECURITY.md | 13 + VERSION | 1 + config/default.json | 23 + deploy.sh | 13 + docs/configuration.md | 54 + docs/operations.md | 81 ++ docs/publishing.md | 52 + scripts/bootstrap.sh | 98 ++ scripts/build_site.py | 64 ++ setup.sh | 4 + site/app.js | 100 ++ site/favicon.svg | 1 + site/index.html | 75 ++ site/social.svg | 1 + site/style.css | 1414 ++++++++++++++++++++++++++ src/install.py | 263 +++++ src/server_status.py | 294 ++++++ tests/test_public_release.py | 138 +++ tests/test_server_status.py | 137 +++ 29 files changed, 3140 insertions(+) create mode 100644 .gitattributes create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/pages.yml create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 SECURITY.md create mode 100644 VERSION create mode 100644 config/default.json create mode 100755 deploy.sh create mode 100644 docs/configuration.md create mode 100644 docs/operations.md create mode 100644 docs/publishing.md create mode 100755 scripts/bootstrap.sh create mode 100755 scripts/build_site.py create mode 100755 setup.sh create mode 100644 site/app.js create mode 100644 site/favicon.svg create mode 100644 site/index.html create mode 100644 site/social.svg create mode 100644 site/style.css create mode 100644 src/install.py create mode 100755 src/server_status.py create mode 100644 tests/test_public_release.py create mode 100644 tests/test_server_status.py diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6313b56 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..1163c03 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,22 @@ +--- +name: Bug report +about: Report unexpected dashboard or installer behavior +title: '' +labels: bug +assignees: '' +--- + +**What happened?** + +**What did you expect?** + +**Steps to reproduce** + +**Environment** +- Distribution/version: +- Python version: +- Shell/terminal: +- ShellGleam version: + +**Sanitized output** +Remove real hostnames, IPs, usernames, container names and credentials before posting. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..3a626c3 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,6 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: monthly diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..dc93c5f --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,23 @@ +name: CI +on: + push: + branches: [main] + pull_request: +permissions: + contents: read +jobs: + test: + runs-on: ubuntu-latest + strategy: + matrix: + python: ['3.9', '3.13'] + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: actions/setup-python@v7 + with: + python-version: ${{ matrix.python }} + - run: python -m unittest discover -s tests -v + - run: bash -n scripts/bootstrap.sh deploy.sh && sh -n setup.sh + - run: python scripts/build_site.py diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 0000000..16f7e07 --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,41 @@ +name: Pages +on: + push: + branches: [main] + workflow_dispatch: +permissions: + contents: read +concurrency: + group: pages + cancel-in-progress: false +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: actions/setup-python@v7 + with: + python-version: '3.13' + - run: python -m unittest discover -s tests -v + - name: Build website and installer + env: + SITE_URL: https://${{ github.repository_owner }}.github.io/${{ github.event.repository.name }} + run: python scripts/build_site.py --site-url "$SITE_URL" + - uses: actions/upload-pages-artifact@v4 + with: + path: _site + deploy: + needs: build + runs-on: ubuntu-latest + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - name: Deploy GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7a458bd --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +__pycache__/ +*.py[cod] +.idea/ +.vscode/ +.venv/ +_site/ +.env +.env.* +*.pem +*.key +*.tar.gz +*.log +.DS_Store diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..86695ab --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,8 @@ +# Changelog + +## 1.0.0 + +- Configurable system, runtime and health dashboard for Linux login sessions. +- Independent per-login rendering with bounded probes and ASCII support. +- Validated setup, original backups, exception rollback and uninstall. +- Static documentation site and checksum-verified remote installer. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..cfb209d --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,22 @@ +# Contributing + +Small, focused pull requests are welcome. Explain the behavior being changed, +include meaningful regression tests, and keep login fast and failure-tolerant. + +Use Python 3.9+ and the standard library. Run: + +```bash +python3 -m unittest discover -s tests -v +bash -n scripts/bootstrap.sh deploy.sh +sh -n setup.sh +python3 scripts/build_site.py +``` + +Website source lives in `site/`; generated output belongs in `_site/` and is +not committed. Please use fictional hostnames and addresses from documentation +ranges in examples. Never submit credentials, live server output, private +addresses or customer deployment notes. Review both source and built artifacts. + +Installer tests operate in temporary filesystem roots. Test real SSH/PAM changes +only on a disposable VM with a second recovery session. Preserve rollback, +symlink metadata and concurrent-session behavior when changing installation. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a53ae02 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 ShellGleam contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..c84b041 --- /dev/null +++ b/README.md @@ -0,0 +1,157 @@ +
+ +# ✦ ShellGleam + +**A brighter first look at your Linux server.** + +A beautiful, configurable login dashboard for Ubuntu and Debian. +System metrics, services, containers, and health checks — before your first command. + +[Website & installer](https://meghdadfadaee.github.io/shell-gleam/) · [Configuration](docs/configuration.md) · [Operations](docs/operations.md) · [MIT license](LICENSE) + +
+ +```text + ╭────────────────────────────────────────────────────────────────────────╮ + │ ◆ ORBIT ● HEALTHY │ + │ Ubuntu 24.04 LTS · 192.0.2.10 │ + ├─ SYSTEM ───────────────────────────────────────────────────────────────┤ + │ │ + │ ↑ Uptime 12d 4h ≋ Load average 0.24 (8 cores) │ + │ Memory ████░░░░░░░░░░░░░░ 23% · 3.7 / 16.0 GiB │ + │ Disk / ██████░░░░░░░░░░░░ 34% · 68.0 / 200.0 GiB │ + │ │ + ├─ RUNTIME ──────────────────────────────────────────────────────────────┤ + │ ● Nginx is online │ + │ ● Docker is online │ + │ 4 containers running · 4 healthchecked │ + ├─ HEALTH ───────────────────────────────────────────────────────────────┤ + │ ✓ No failed systemd units │ + │ ✓ Packages current (cached) │ + │ ✓ No reboot needed │ + ╰────────────────────────────────────────────────────────────────────────╯ +``` + +*Illustrative output. Hostnames, addresses and metrics above are fictional.* + +## Install in one command + +```bash +curl -fsSL https://meghdadfadaee.github.io/shell-gleam/setup.sh | bash +``` + +The bootstrap downloads a versioned package, verifies its embedded SHA-256, +and requests `sudo` if needed. It retains setup at `/opt/shell-gleam`. + +Pass options after `bash -s --`: + +```bash +curl -fsSL https://meghdadfadaee.github.io/shell-gleam/setup.sh | bash -s -- install --title ORBIT +curl -fsSL https://meghdadfadaee.github.io/shell-gleam/setup.sh | bash -s -- install --wizard +curl -fsSL https://meghdadfadaee.github.io/shell-gleam/setup.sh | bash -s -- install --dry-run +``` + +Prefer to inspect first? Download the generated script, read it, then execute: + +```bash +curl -fsSLo shell-gleam-setup.sh https://meghdadfadaee.github.io/shell-gleam/setup.sh +less shell-gleam-setup.sh +bash shell-gleam-setup.sh install --wizard +``` + +For automation, enable `set -o pipefail` in your calling Bash shell to propagate +curl failures through the pipeline. The checksum detects payload corruption or a +script/package mismatch; it is not an independent signature of the publisher. + +## What you get + +- **A useful first glance:** uptime, CPU load, memory and disk bars. +- **Runtime visibility:** configurable systemd services and local Docker state. +- **Honest health checks:** failed units, cached update age, reboot and firmware notices. + Containers without healthchecks are never described as healthy. +- **All login users:** optional PAM session display, independent rendering for concurrent logins. +- **Your style:** JSON configuration, Unicode or ASCII, colors, sections and thresholds. +- **Reversible setup:** original backups, rollback on handled errors, uninstall and reinstall support. +- **Small footprint:** Python's standard library; no network requests during login. + +## Requirements + +Ubuntu/Debian with Python **3.9+**, systemd, GNU `timeout`, Debian `run-parts`, +OpenSSH server and the standard `pam_motd`/`pam_exec` modules. SSH must already use +`UsePAM yes` and `PrintMotd no`. Both `/etc/pam.d/sshd` and `/etc/pam.d/login` +must have the normal dynamic MOTD entry. Preflight checks reject unsupported +setups before making system changes. Other distributions are not supported yet. +The bootstrap also needs Bash and curl; it does not install packages. + +## Install from source + +```bash +git clone https://github.com/meghdadfadaee/shell-gleam.git +cd shell-gleam +sudo ./setup.sh install --wizard +``` + +Or copy this directory to the server. `./deploy.sh root@your-server` copies it +to `/opt/shell-gleam` over SSH and installs it; set `SSH_CONFIG` if needed. + +## Make it yours + +```bash +sudoedit /etc/server-status/config.json +server-status --check +sudo server-status --no-color +``` + +The repository is named `shell-gleam`; the installed preview command and settings +path remain `server-status`. Configuration changes apply on the next login. +See [all options and examples](docs/configuration.md). + +```json +{ + "title": "ORBIT", + "services": [{"unit": "nginx.service", "label": "Nginx", "required": true}], + "disks": ["/", "/srv"], + "docker": false, + "disk_warning": 70, + "disk_critical": 85, + "footer": "Welcome aboard." +} +``` + +A supplied config overlays built-in defaults. Reinstalling without overrides +preserves the server's existing config. Missing optional services are neutral; +missing required services and unavailable probes raise ATTENTION. + +## Undo + +```bash +sudo /opt/shell-gleam/setup.sh uninstall --dry-run +sudo /opt/shell-gleam/setup.sh uninstall +``` + +If installed from a checkout, run `sudo ./setup.sh uninstall` there instead. +Backups remain root-only in `/var/lib/server-status`. Uninstall restores original +PAM display entries, stock hooks and static/dynamic messages. [Details and limitations](docs/operations.md). + +## Website and releases + +The [website](https://meghdadfadaee.github.io/shell-gleam/) provides an interactive +dashboard preview, command builder and remote installer. GitHub Actions tests +changes and publishes the site and a checksum-verified setup package from `main`. + +For release maintenance, custom domains and forks, see the +[publishing guide](docs/publishing.md). + +## Development + +```bash +python3 -m unittest discover -s tests -v +python3 src/server_status.py --config config/default.json --no-color +python3 scripts/build_site.py +python3 -m http.server 8000 --directory _site +``` + +Open `http://localhost:8000`. The site has no package manager, framework, +external fonts, trackers or third-party runtime assets. See [CONTRIBUTING.md](CONTRIBUTING.md). + +MIT licensed. Demo content uses fictional hostnames and documentation-only IP addresses. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..e023905 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,13 @@ +# Security + +ShellGleam changes privileged login message-display configuration. Review the +installer before running it. Its PAM entry is optional; authentication and +authorization rules are not changed. Keep installed code and config root-owned. + +Do not include credentials, live hostnames or sensitive logs in public issues. +For a vulnerability, use GitHub's **Security → Report a vulnerability** if private +reporting is enabled. Otherwise, open a minimal issue requesting a private +reporting channel without publishing exploit details or secrets. + +The bootstrap checksum detects corruption and script/package mismatch. It does +not provide independent publisher authentication. No telemetry is collected. diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..3eefcb9 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +1.0.0 diff --git a/config/default.json b/config/default.json new file mode 100644 index 0000000..9ee07ac --- /dev/null +++ b/config/default.json @@ -0,0 +1,23 @@ +{ + "title": "", + "address": "auto", + "width": 72, + "color": true, + "ascii": false, + "sections": ["system", "runtime", "health"], + "services": [ + {"unit": "nginx.service", "label": "Nginx", "required": false}, + {"unit": "docker.service", "label": "Docker", "required": false} + ], + "disks": ["/"], + "docker": true, + "command_timeout": 1.0, + "memory_warning": 75, + "memory_critical": 90, + "disk_warning": 75, + "disk_critical": 90, + "load_warning": 0.7, + "load_critical": 1.0, + "updates_max_age_hours": 48, + "footer": "" +} diff --git a/deploy.sh b/deploy.sh new file mode 100755 index 0000000..4a7dead --- /dev/null +++ b/deploy.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -euo pipefail +if [[ $# != 1 || $1 == -* ]]; then + echo "Usage: [SSH_CONFIG=path] $0 root@server" >&2 + exit 2 +fi +project_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +ssh_args=() +if [[ -n ${SSH_CONFIG:-} ]]; then + ssh_args+=(-F "$SSH_CONFIG") +fi +tar -C "$project_dir" --exclude='__pycache__' -czf - setup.sh deploy.sh README.md src config tests docs reference | + ssh "${ssh_args[@]}" "$1" 'mkdir -p /opt/shell-gleam && tar -xzf - -C /opt/shell-gleam && cd /opt/shell-gleam && ./setup.sh install' diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 0000000..13f1126 --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,54 @@ +# Configuration + +Live file: `/etc/server-status/config.json`. Validate with `server-status --check`; +preview with `sudo server-status --no-color`. Changes appear on the next login. + +`config/default.json` lists every setting. For an alternate file use +`sudo ./setup.sh install --config /absolute/path/config.json`. A supplied file +overlays built-in defaults, rather than merging with existing settings. Unknown +keys and invalid types are rejected before installation. `--wizard` prompts for +a title, address, services and disks; remote wizard setup reads `/dev/tty`. + +| Key | Default / accepted values | +| --- | --- | +| `title` | Empty: automatic uppercase short hostname | +| `address` | `auto`: first IPv4 from `hostname -I`; override for multiple interfaces | +| `width` | `72`; integer 52–120, interior columns | +| `color` | `true`; manual previews honor `NO_COLOR` | +| `ascii` | `false`; use plain ASCII borders, bars and symbols | +| `sections` | `["system", "runtime", "health"]`; reorder or omit | +| `services` | Nginx and Docker, optional; up to 16 `{unit,label,required}` objects | +| `disks` | `["/"]`; 1–8 absolute filesystem paths | +| `docker` | `true`; query the local Unix socket if CLI is installed | +| `command_timeout` | `1.0`; 0.1–2 seconds per concurrent subprocess | +| `memory_warning`, `memory_critical` | `75`, `90` percent | +| `disk_warning`, `disk_critical` | `75`, `90` percent | +| `load_warning`, `load_critical` | `0.7`, `1.0` load per CPU | +| `updates_max_age_hours` | `48`; age limit for Ubuntu update-notifier data | +| `footer` | Empty; optional message | + +Resource thresholds, failed units, inactive installed services, required missing +services, unknown/stale updates and unhealthy containers affect the summary. +Checks still affect the summary when their display section is hidden. +Missing optional services are neutral. A systemd active state is not an +application readiness check; configure the actual unit for your workload. + +Example database configuration: + +```json +{ + "title": "DATABASE", + "services": [ + {"unit": "postgresql.service", "label": "PostgreSQL", "required": true}, + {"unit": "ssh.service", "label": "SSH", "required": true} + ], + "disks": ["/", "/var/lib/postgresql"], + "docker": false, + "disk_warning": 70, + "disk_critical": 85 +} +``` + +The PostgreSQL umbrella service may be active when a cluster is down; select +its specific cluster unit if needed. Settings and rendered container names are +visible to login users. Do not place secrets in the configuration. diff --git a/docs/operations.md b/docs/operations.md new file mode 100644 index 0000000..2f0ca3f --- /dev/null +++ b/docs/operations.md @@ -0,0 +1,81 @@ +# Operations and implementation + +## System-wide login + +The installer writes a root-owned renderer at `/usr/local/bin/server-status`, +JSON settings at `/etc/server-status/config.json` and a bounded shell wrapper at +`/etc/update-motd.d/00-server-status`. + +It replaces only the dynamic MOTD session-display entry in `/etc/pam.d/sshd` +and `/etc/pam.d/login` with optional `pam_exec.so stdout type=open_session`. +Every session receives independent output, avoiding the shared dynamic MOTD +cache race during concurrent logins. Authentication and authorization rules and +SSH daemon settings are unchanged. The second static MOTD entry remains intact; +`/etc/motd` is emptied with its original content backed up. No daemon restart is +needed. SSH's normal `Last login` line remains. + +Standard executable MOTD scripts are renamed with `~server-status-disabled`. +The installer checks `run-parts --lsbsysinit --test /etc/update-motd.d` to ensure +only the managed hook remains selected. The tilde matters: ordinary run-parts +and PAM's LSB mode accept different filenames. Renaming in place preserves +relative symlinks and avoids changing a linked package-owned file's mode. + +## Bounded probes + +External probes run concurrently with configurable individual timeouts. The +wrapper adds a six-second overall timeout and one-second kill grace period. +It shows an unavailable notice on failure and returns success to PAM. Kernel +uninterruptible I/O cannot be forcibly timed out by normal userspace tools. +Python runs with `-I`, the command PATH is fixed, and text control characters +are removed. Only root should be able to modify installed code and settings. + +Login does not access the network, run apt, or install dependencies. Package +updates come from Ubuntu's existing update-notifier cache; missing or old data +is unknown/stale. `/run/reboot-required` is an OS hint, not an independent audit. +Docker queries the local socket regardless of caller Docker context; containers +without healthchecks are not labeled healthy. A manual preview runs with the +caller's permissions and may show Docker unavailable without sudo. + +## Backup, reinstall, uninstall + +Original content, mode, ownership and symlink targets are recorded once per path +in `/var/lib/server-status/manifest.json`; the directory is root-only. Each +operation also snapshots its current touched files for exception rollback. +`flock` serializes installation changes; replacement writes are atomic per file. + +Reinstall preserves current settings unless overrides are supplied. It also +disables new package MOTD hooks. After package upgrades, rerun setup if stock +messages or PAM display entries reappear. + +Uninstall restores pre-install content, including both PAM files, and retains +backups. Save later manual edits you want to keep before uninstalling. File +replacement and exception rollback are not a multi-file power-loss transaction. +After SIGKILL or power loss, inspect the newest backup folder and manifest before +proceeding. VM snapshots provide a stronger recovery boundary. + +## Troubleshooting + +Check `server-status --check`, `sudo server-status`, `sudo sshd -T`, executable +hook permissions and the two PAM session-display entries. User MOTD opt-outs, +non-login shells, `su`/`sudo`, and SSH command/SFTP sessions do not necessarily +show a login message. Noninteractive SSH command output should remain clean. + +Extra messages may come from `/etc/motd.d`, `/run/motd.d`, `/usr/lib/motd.d`, user +shell files or SSH `Banner`; those sources are not removed. Fixed-width Unicode +output depends on your terminal font. Select ASCII mode and a smaller width for +limited terminals. + +## Remote bootstrap + +GitHub Pages serves a generated Bash bootstrap and a versioned archive whose +SHA-256 is embedded in that script. Download and verification happen before +sudo and installation. The extractor rejects links, traversal paths and large +unexpected archives. The package is built from an explicit file allowlist; +local dotfiles, deployment notes, credentials and arbitrary files cannot enter +it by a recursive copy. Checksums detect mismatches and corruption, not a +compromised publisher. The website makes no requests to visitors' servers. + +The verified source is retained in `/opt/shell-gleam` for future uninstall. Dry +runs execute from the temporary package without copying it into `/opt`. +Temporary downloads are removed on exit. For local integration tests only, +`SHELL_GLEAM_BASE_URL=http://127.0.0.1:PORT` can point to a local build. diff --git a/docs/publishing.md b/docs/publishing.md new file mode 100644 index 0000000..a7da26a --- /dev/null +++ b/docs/publishing.md @@ -0,0 +1,52 @@ +# Website and release maintenance + +ShellGleam is maintained in +[`meghdadfadaee/shell-gleam`](https://github.com/meghdadfadaee/shell-gleam). + +- Website: `https://meghdadfadaee.github.io/shell-gleam/` +- Bootstrap: `https://meghdadfadaee.github.io/shell-gleam/setup.sh` +- License: MIT + +## GitHub Pages + +The **Pages** workflow tests the source, builds the static website and installer +package, and deploys `_site` from `main`. Repository Settings → Pages must use +**GitHub Actions** as the source. Run the workflow manually to redeploy the +current version without a source change. + +Only the built `_site` directory is published. Do not enable branch publishing +from the repository root, where `setup.sh` is the local source installer. + +## Build and inspect locally + +```bash +python3 -m unittest discover -s tests -v +python3 scripts/build_site.py +python3 -m http.server 8000 --directory _site +``` + +The build creates a content-addressed payload, embedded-checksum bootstrap, +`release.json` and a checksum list under `_site/downloads`. The payload uses an +explicit source allowlist, normalized metadata and reproducible compression. +Public demo data is fictional and uses documentation-only IP addresses. + +No live server deployment records or captured production outputs belong in +this repository. Sanitize screenshots and examples before committing them. +Use a GitHub no-reply commit email to keep your personal email private. + +## Releases + +Update `VERSION` and `CHANGELOG.md`, run tests, and push to `main` to redeploy. +Previously downloaded bootstrap scripts refer to their exact package; after a +later site deployment replaces that package, fetch a fresh bootstrap. A missing +old package fails safely rather than silently installing another version. + +## Forks and custom domains + +For another account or repository, update links in the README and `site/`. +The workflow passes its own account/repository URL to `scripts/build_site.py`. +For a custom domain, change the workflow's `SITE_URL` and the website's +`BASE_URL` in `site/app.js` together. + +The landing page has no external fonts, analytics, trackers or runtime assets. +Its customization form only changes a local preview and generated command. diff --git a/scripts/bootstrap.sh b/scripts/bootstrap.sh new file mode 100755 index 0000000..187b555 --- /dev/null +++ b/scripts/bootstrap.sh @@ -0,0 +1,98 @@ +#!/usr/bin/env bash +# ShellGleam remote installer. Published by scripts/build_site.py. +set -euo pipefail + +main() { + if [[ ${1:-} == --help || ${1:-} == -h ]]; then + cat <<'HELP' +ShellGleam — a brighter first look at your Linux server. +Usage: curl -fsSL https://meghdadfadaee.github.io/shell-gleam/setup.sh | bash -s -- [options] + +Setup options: install (default), uninstall, status, --dry-run, --wizard, + --title NAME, --address IP, --config FILE, --no-color, --ascii +Downloads and verifies a versioned package before requesting sudo. +Persistent project: /opt/shell-gleam. Live config: /etc/server-status/config.json. +HELP + return + fi + local base_url=${SHELL_GLEAM_BASE_URL:-@@SITE_URL@@} + local expected='@@SHA256@@' + local artifact='@@ARCHIVE@@' + local work_dir + case "$base_url" in + https://*) ;; + http://127.0.0.1:*|http://localhost:*) ;; + *) echo 'ShellGleam: download URL must use HTTPS (loopback HTTP is allowed for local testing).' >&2; return 1 ;; + esac + for dependency in curl python3 bash; do + command -v "$dependency" >/dev/null || { echo "ShellGleam: install $dependency first." >&2; return 1; } + done + python3 -c 'import sys; sys.exit(0 if sys.version_info >= (3, 9) else "ShellGleam requires Python 3.9+")' + work_dir=$(mktemp -d "${TMPDIR:-/tmp}/shell-gleam.XXXXXXXX") + shell_gleam_temp_dir=$work_dir + trap '[[ -z ${shell_gleam_temp_dir:-} ]] || rm -rf -- "$shell_gleam_temp_dir"' EXIT + echo 'ShellGleam: downloading the verified setup package…' + curl --fail --silent --show-error --location --retry 2 --connect-timeout 15 --max-time 120 \ + --proto '=https,http' --proto-redir '=https' "$base_url/$artifact" -o "$work_dir/package.tar.gz" + python3 - "$work_dir/package.tar.gz" "$expected" "$work_dir" <<'PY' +import hashlib +from pathlib import Path, PurePosixPath +import shutil +import sys +import tarfile +archive, expected, directory = sys.argv[1:] +if hashlib.sha256(Path(archive).read_bytes()).hexdigest() != expected: + sys.exit('ShellGleam: checksum mismatch; nothing installed.') +root = Path(directory) +with tarfile.open(archive, 'r:gz') as package: + members = package.getmembers() + if len(members) > 1000 or sum(m.size for m in members) > 20 * 1024 * 1024: + sys.exit('ShellGleam: unexpected package size.') + for member in members: + path = PurePosixPath(member.name) + if (path.is_absolute() or '..' in path.parts or not path.parts + or path.parts[0] != 'shell-gleam' or not (member.isfile() or member.isdir())): + sys.exit('ShellGleam: unsafe package member; nothing installed.') + for member in members: + target = root / member.name + if member.isdir(): + target.mkdir(parents=True, exist_ok=True) + else: + target.parent.mkdir(parents=True, exist_ok=True) + with package.extractfile(member) as source, target.open('wb') as destination: + shutil.copyfileobj(source, destination) + target.chmod(0o755 if member.mode & 0o111 else 0o644) +print('ShellGleam: SHA-256 verified.') +PY + local dry_run=false wizard=false + for argument in "$@"; do + [[ $argument != --dry-run && $argument != status ]] || dry_run=true + [[ $argument != --wizard ]] || wizard=true + done + local -a elevation=() + if [[ $(id -u) != 0 ]]; then + command -v sudo >/dev/null || { echo 'ShellGleam: run as root or install sudo.' >&2; return 1; } + elevation=(sudo) + fi + # Absolute --config paths remain valid after changing the project directory. + # The argument array is forwarded unchanged; never evaluate user arguments. + if $wizard && ! { : /dev/null; then + echo 'ShellGleam: --wizard requires an interactive terminal.' >&2 + return 1 + fi + if $dry_run; then + if $wizard; then + "${elevation[@]}" bash "$work_dir/shell-gleam/setup.sh" "$@" (ascii ? '#' : '█').repeat(filled) + (ascii ? '-' : '░').repeat(18 - filled); + dashboard.replaceChildren(); + add((ascii ? '+' : '╭') + horizontal.repeat(width) + (ascii ? '+' : '╮'), 'term-border'); + const right = symbol.dot + ' ' + (warning ? 'ATTENTION' : 'HEALTHY'); + const left = symbol.diamond + ' ' + Array.from(title.toUpperCase()).slice(0, 32).join(''); + line(left + ' '.repeat(Math.max(2, width - 2 - Array.from(left).length - right.length)) + right, warning ? 'term-warning' : 'term-good'); + line(' Ubuntu 24.04 LTS / 192.0.2.10', 'term-dim'); + divider('SYSTEM'); line(); + line(` ${symbol.up} Uptime 12d 4h ${ascii ? '~' : '≋'} Load average 0.24 (8 cores)`, 'term-title'); + line(` Memory ${bar(4)} 23% / 3.7 / 16.0 GiB`, 'term-good'); + line(` Disk / ${bar(warning ? 16 : 6)} ${warning ? '91%' : '34%'} / ${warning ? '182' : '68'} / 200 GiB`, warning ? 'term-warning' : 'term-good'); line(); + divider('RUNTIME'); line(); + line(` ${symbol.dot} Nginx is online`, 'term-good'); + line(` ${symbol.dot} Docker is online`, 'term-good'); + line(warning ? ' 4 running / 1 unhealthy / 0 failed' : ' 4 containers running / 4 healthchecked', warning ? 'term-warning' : 'term-good'); line(); + divider('HEALTH'); line(); + line(warning ? ` ${symbol.warn} 1 unit failed / worker.service` : ` ${symbol.tick} No failed systemd units`, warning ? 'term-warning' : 'term-good'); + line(` ${symbol.tick} Packages current (cached)`, 'term-good'); + line(` ${symbol.tick} No reboot needed`, 'term-good'); line(); + add((ascii ? '+' : '╰') + horizontal.repeat(width) + (ascii ? '+' : '╯'), 'term-border'); + commandNode.textContent = commandFor({ title, ascii, color, wizard }); + statusNode.textContent = ''; +} +form.addEventListener('input', render); +form.addEventListener('submit', (event) => event.preventDefault()); +document.querySelectorAll('[data-state]').forEach(button => { + button.addEventListener('click', () => { + health = button.dataset.state; + document.querySelectorAll('[data-state]').forEach(item => { + const selected = item === button; + item.classList.toggle('selected', selected); + item.setAttribute('aria-pressed', String(selected)); + }); + render(); + }); +}); +document.querySelector('#wizard-toggle').addEventListener('click', event => { + wizard = !wizard; + event.currentTarget.setAttribute('aria-pressed', String(wizard)); + event.currentTarget.textContent = wizard ? 'Setup wizard included ✓' : 'Use the setup wizard →'; + render(); +}); +document.querySelector('#copy-command').addEventListener('click', async () => { + try { + await navigator.clipboard.writeText(commandNode.textContent); + statusNode.textContent = 'Copied. Your next login is looking brighter.'; + } catch { + const range = document.createRange(); + range.selectNodeContents(commandNode); + const selection = window.getSelection(); + selection.removeAllRanges(); selection.addRange(range); + statusNode.textContent = 'Command selected. Press Ctrl+C (or Cmd+C) to copy.'; + } +}); +render(); diff --git a/site/favicon.svg b/site/favicon.svg new file mode 100644 index 0000000..d3fd2b0 --- /dev/null +++ b/site/favicon.svg @@ -0,0 +1 @@ + diff --git a/site/index.html b/site/index.html new file mode 100644 index 0000000..ef5e3f6 --- /dev/null +++ b/site/index.html @@ -0,0 +1,75 @@ + + + + + + + + + + + + + ShellGleam — a brighter first look + + + + + + + +
+
+
+

A SMALL UPGRADE TO YOUR EVERYDAY SSH

+

A better hello
from your
server.

+

All the signs of life, right when you log in.
A beautiful little dashboard. A much better first glance.

+ +

OPEN SOURCE / PYTHON STDLIB / MADE FOR LINUX

+
+
+
01 / YOUR NEXT LOGINLIVE PREVIEW
+
+
orbit — ssh
+

~ ❯ ssh orbit

orbit:~$

+ +
+
Demo data. Real possibility.
+ + +
+
+
01 Install once02 Every login user03 Your rules, your look04 Undo anytime
+
+

LESS DIGGING. MORE KNOWING.

The first ten commands,
in one first glance.

+

Uptime. Memory. That container acting up.
ShellGleam brings the useful bits together, so you can spend less time checking in and more time getting on with it.

+
+
+
01 / SYSTEM

A pulse, not a puzzle.

Uptime, CPU load, memory and disks. Clear bars and adjustable thresholds tell you where things stand.

+
02 / RUNTIME

Know what’s running.

Pick the systemd services you care about. See local Docker state and actual healthcheck results.

+
03 / HEALTH

A little peace of mind.

Failed units, cached package updates and reboot notices. Unknown data stays unknown. No false confidence.

+
+
+

FEELS LIKE YOUR PLACE

Your server.
Your kind of hello.

A name, a few preferences, and you’re home.
Make it yours here, then copy your install command.

Explore every JSON setting
Preview only. Nothing here connects to your server.
+
+
YOUR SHELLGLEAM RECIPE
+ +
The small details
+
Services, disks and thresholds? The setup wizard has you covered.
+
+
+
+

FROM BLANK TO BRIGHT

One line.
A better login.

Ubuntu or Debian. Python 3.9+. Bash and curl.
The installer asks for sudo when it needs it.

+
RUN ON YOUR SERVER
curl -fsSL https://meghdadfadaee.github.io/shell-gleam/setup.sh | bash
SHA-256 verified package No login network requestsRead the installer ↗
+

+

Want a guided setup?

Add --wizard to choose a name, services and disks in your terminal.

Easy come. Easy go.

Original login files are backed up. Restore them with one command.

sudo /opt/shell-gleam/setup.sh uninstall
+
The details before you install

Supports Ubuntu/Debian with systemd, Python 3.9+, GNU timeout, Debian run-parts, OpenSSH and standard PAM MOTD/exec modules. Setup checks compatibility before making changes. Docker is optional.

Installation replaces two PAM message-display entries, backs up the originals, and leaves authentication rules and SSH daemon settings unchanged. Additional MOTD snippets may still appear. Checksum verification detects corruption and package mismatch; it is not an independent publisher signature.

Prefer to read before running? Download setup.sh and inspect it. For scripted pipelines, enable set -o pipefail to catch curl failures. Read the operations guide ↗

+
+

A little less noise.
A little more gleam.

Find it on GitHub
+
+ + + diff --git a/site/social.svg b/site/social.svg new file mode 100644 index 0000000..6bc71df --- /dev/null +++ b/site/social.svg @@ -0,0 +1 @@ +✳ ShellGleam.A better hellofrom your server.A beautiful, configurable Linux login dashboard.OPEN SOURCE / PYTHON STDLIB / MADE FOR LINUX diff --git a/site/style.css b/site/style.css new file mode 100644 index 0000000..8be73d9 --- /dev/null +++ b/site/style.css @@ -0,0 +1,1414 @@ +:root { + --paper:#f5f3eb; + --ink:#242b29; + --muted:#68716c; + --line:#d9ddd2; + --accent:#d85531; + --mint:#a4d5ac; + --green:#39704b; + --mono:ui-monospace,SFMono-Regular,Consolas,"Liberation Mono",monospace; + --sans:Inter,"Helvetica Neue",Arial,sans-serif +} +* { + box-sizing:border-box +} +html { + scroll-behavior:smooth; + scroll-padding-top:25px +} +body { + margin:0; + background:var(--paper); + color:var(--ink); + font-family:var(--sans); + -webkit-font-smoothing:antialiased +} +button,input { + font:inherit +} +button,a { + -webkit-tap-highlight-color:transparent +} +a { + color:inherit; + text-decoration:none +} +button { + cursor:pointer +} +button:focus-visible,a:focus-visible,input:focus-visible,summary:focus-visible { + outline:3px solid var(--accent); + outline-offset:5px +} +::selection { + background:#e9a086; + color:#202925 +} +.wrap { + width:min(1280px,calc(100% - 112px)); + margin-inline:auto +} +.skip { + position:fixed; + top:-70px; + left:20px; + z-index:20; + background:var(--ink); + color:white; + padding:15px +} +.skip:focus { + top:10px +} +.site-header { + height:108px; + display:flex; + align-items:center; + justify-content:space-between; + border-bottom:1px solid var(--line) +} +.brand { + display:inline-flex; + align-items:center; + font-size:25px; + letter-spacing:-1.1px; + font-weight:750 +} +.brand-mark { + font-size:40px; + line-height:1; + color:var(--accent); + margin-right:10px +} +.brand-dot { + color:var(--accent) +} +nav { + display:flex; + align-items:center; + gap:32px; + font-size:13px; + font-weight:600 +} +.nav-github { + padding:11px 18px; + border:1px solid #bcc4b7; + border-radius:5px +} +nav a:hover,.text-link:hover { + color:var(--accent) +} +.hero { + display:grid; + grid-template-columns:1fr 1.12fr; + gap:40px; + padding-top:78px; + padding-bottom:85px; + align-items:center +} +.eyebrow { + font:10px/1.5 var(--mono); + font-weight:600; + letter-spacing:1.4px; + margin:0 0 27px; + display:flex; + gap:9px; + align-items:center +} +.live-dot { + width:6px; + height:6px; + border-radius:50%; + display:inline-block; + background:#638e57; + flex-shrink:0 +} +.hero .eyebrow { + color:var(--muted); + font-size:9px; + white-space:nowrap +} +h1 { + font-size:clamp(64px,6.9vw,100px); + line-height:.98; + letter-spacing:-6px; + margin:0 0 30px; + font-weight:550; + position:relative +} +em { + font-family:Georgia,"Times New Roman",serif; + font-weight:400; + letter-spacing:-.055em +} +h1 em { + color:var(--accent); + font-size:1.12em +} +.hero-spark { + font-size:80px; + color:var(--accent); + position:absolute; + margin-left:25px; + bottom:6px; + font-weight:400 +} +.hero-description { + font-size:16px; + line-height:1.8; + color:var(--muted); + margin:0 0 30px +} +.hero-actions { + display:flex; + align-items:center; + gap:24px +} +.button { + display:inline-flex; + align-items:center; + justify-content:space-between; + gap:30px; + border-radius:4px; + padding:18px 22px; + font-size:13px; + font-weight:600; + transition:background .2s,transform .2s +} +.button:hover { + transform:translateY(-2px) +} +.button-dark { + background:var(--ink); + color:var(--paper) +} +.button-dark:hover { + background:#3e4942 +} +.text-link { + display:inline-flex; + align-items:center; + gap:16px; + font-size:12px; + font-weight:600; + background:none; + border:0; + padding:0 +} +.hero-meta { + font:9px var(--mono); + color:var(--muted); + letter-spacing:.3px; + margin:30px 0 0 +} +.hero-meta span { + padding:0 10px; + color:#a4aaa1 +} +.hero-visual { + min-width:0; + padding-top:14px; + position:relative +} +.visual-label { + display:flex; + justify-content:space-between; + font:9px var(--mono); + letter-spacing:.7px; + color:#6e7a70; + margin:0 2px 14px +} +.visual-label>span:last-child { + display:flex; + align-items:center; + gap:7px +} +.terminal { + background:#202a25; + border:1px solid #16221a; + border-radius:9px; + box-shadow:0 23px 55px -23px #1f3d304a,0 3px 8px #192e1e12; + transform:rotate(-1.3deg); + position:relative; + color:#d3dacf; + overflow:hidden +} +.terminal-chrome { + height:42px; + border-bottom:1px solid #3a453c; + display:flex; + align-items:center; + justify-content:space-between; + padding:0 17px; + color:#8c9d8c; + font:10px var(--mono); + background:#26322a +} +.traffic { + display:flex; + gap:5px +} +.traffic i { + display:block; + width:7px; + height:7px; + border-radius:50%; + background:#66735e +} +.traffic i:first-child { + background:#cc775e +} +.traffic i:nth-child(2) { + background:#b9a66a +} +.traffic i:nth-child(3) { + background:#88a66b +} +.terminal-body { + padding:19px 17px 12px; + overflow-x:auto +} +.terminal-command,.terminal-prompt { + font:11px var(--mono); + margin:0 +} +.terminal-command { + color:#c8cfc7; + margin-bottom:16px +} +.terminal-command span { + color:#a4d5ac; + margin-right:6px +} +#dashboard { + font:clamp(8px,.97vw,13.5px)/1.5 var(--mono); + letter-spacing:-.15px; + white-space:pre; + overflow:visible; + margin:0 0 15px; + min-width:max-content +} +.term-border { + color:#6e9d7c +} +.term-good { + color:#a5d1a3 +} +.term-warning { + color:#e8b970 +} +.term-title { + color:#ecefe5 +} +.term-dim { + color:#91a291 +} +.terminal-prompt { + color:#92c09d +} +.cursor { + display:inline-block; + width:6px; + height:12px; + background:#9dc69f; + vertical-align:middle; + animation:blink 1.5s step-end infinite +} +.terminal-footer { + border-top:1px solid #37463a; + padding:11px 15px; + display:flex; + justify-content:space-between; + font:7px var(--mono); + letter-spacing:.3px; + color:#92a28f +} +.terminal-footer>span:first-child { + display:flex; + gap:6px; + align-items:center +} +.terminal-footer .live-dot { + background:#a2c38f; + width:4px; + height:4px +} +.preview-controls { + display:flex; + justify-content:space-between; + align-items:center; + margin-top:25px +} +.preview-controls>span { + font:9px var(--mono); + color:var(--muted) +} +.segmented { + display:flex; + background:#e7e9df; + padding:3px; + border-radius:5px; + gap:2px +} +.segmented button { + border:0; + background:transparent; + padding:8px 12px; + border-radius:3px; + font:10px var(--mono); + color:var(--muted) +} +.segmented .selected { + background:var(--paper); + box-shadow:0 1px 4px #182b1715; + color:var(--ink) +} +.hand-note { + font:italic 17px Georgia,serif; + text-align:right; + transform:rotate(-5deg); + margin-right:30px; + margin-top:26px; + color:#707c69 +} +.hand-note span { + font:30px Georgia; + display:inline-block; + transform:rotate(-15deg); + position:relative; + top:-6px; + margin-left:8px +} +.spec-strip { + border-block:1px solid var(--line); + background:#eceee4 +} +.spec-inner { + display:flex; + justify-content:space-between; + padding-block:23px; + font:11px var(--mono) +} +.spec-inner b { + font-size:10px; + color:var(--accent); + margin-right:12px; + font-weight:400 +} +.intro { + display:grid; + grid-template-columns:1.2fr 1fr; + gap:60px; + align-items:end; + padding-block:85px 45px +} +.intro .eyebrow { + color:var(--accent); + margin-bottom:17px +} +h2 { + font-size:clamp(36px,3.5vw,50px); + line-height:1.1; + letter-spacing:-1.7px; + font-weight:500; + margin:0 +} +h2 em { + font-size:1.05em; + letter-spacing:-1.6px +} +.intro>p { + color:var(--muted); + font-size:15px; + line-height:1.8; + margin:0; + max-width:420px +} +.features { + display:grid; + grid-template-columns:repeat(3,1fr); + gap:35px; + padding-bottom:87px +} +.features article { + border-top:1px solid #c8d1c1; + padding-top:18px +} +.feature-number { + font:9px var(--mono); + color:#6e7c69; + letter-spacing:1.2px +} +.feature-graphic { + height:125px; + display:flex; + justify-content:center; + margin-block:15px 5px +} +.metric-graphic { + flex-direction:column; + padding-inline:22px; + gap:12px +} +.metric-graphic span { + display:flex; + justify-content:space-between; + font:10px var(--mono); + color:var(--muted) +} +.metric-graphic strong { + font-weight:500; + color:var(--ink) +} +.metric-graphic>div { + height:14px; + background:repeating-linear-gradient(90deg,#dfe5d6 0,#dfe5d6 7px,transparent 7px,transparent 10px) +} +.metric-graphic i { + display:block; + width:23%; + height:100%; + background:repeating-linear-gradient(90deg,#6e9269 0,#6e9269 7px,transparent 7px,transparent 10px) +} +.runtime-graphic { + flex-direction:column; + gap:14px; + padding-inline:23px +} +.runtime-graphic>span { + font:13px var(--mono); + display:flex; + align-items:center; + gap:10px +} +.runtime-graphic small { + margin-left:auto; + font-size:9px; + border:1px solid #d0dac7; + background:#e9eedf; + padding:5px 8px; + border-radius:4px; + color:#57724f +} +.health-graphic { + gap:16px; + align-items:center +} +.health-icon { + width:44px; + height:44px; + border:1px solid #c7d6bb; + background:#e6eddd; + border-radius:50%; + display:flex; + align-items:center; + justify-content:center; + font:22px var(--mono); + color:#67845b +} +.health-graphic>span:last-child { + font-size:16px +} +.health-graphic small { + display:block; + font:8px var(--mono); + letter-spacing:.6px; + color:var(--muted); + margin-top:9px +} +h3 { + font-size:19px; + font-weight:500; + letter-spacing:-.5px; + margin:15px 0 10px +} +.features p { + font-size:13px; + line-height:1.85; + color:var(--muted); + margin:0; + max-width:310px +} +.config-section { + background:#e9ede2; + border-block:1px solid #d7dfd0; + padding-block:70px +} +.config-layout { + display:grid; + grid-template-columns:1fr 1fr; + gap:100px; + align-items:center +} +.config-copy .eyebrow { + color:#687d5f +} +.config-copy h2 { + font-size:51px +} +.config-copy p:not(.eyebrow) { + font-size:14px; + color:var(--muted); + line-height:1.8; + margin:24px 0 +} +.config-copy .text-link { + margin-top:10px +} +.config-footnote { + font:10px var(--mono); + color:#7a8672; + margin-top:38px; + line-height:1.6 +} +.config-footnote span { + margin-right:8px +} +.config-card { + background:var(--paper); + border:1px solid #cfd8c5; + border-radius:6px; + padding:26px 30px; + box-shadow:0 9px 18px -15px #29402c30 +} +.card-caption { + display:flex; + justify-content:space-between; + border-bottom:1px solid var(--line); + padding-bottom:20px; + margin-bottom:23px; + font:9px var(--mono); + letter-spacing:1.2px; + color:var(--muted) +} +.card-caption>span:last-child { + color:var(--accent); + font-size:21px; + line-height:10px +} +.config-card>label { + font-size:12px; + display:block; + margin-bottom:12px +} +.config-card>input { + width:100%; + background:#f9f8f2; + border:1px solid #d5dacc; + border-radius:4px; + padding:13px 15px; + font:15px var(--mono); + color:var(--ink) +} +fieldset { + border:0; + padding:0; + margin:24px 0 0 +} +legend { + font:9px var(--mono); + text-transform:uppercase; + color:#7b8573; + letter-spacing:1px; + padding:0; + margin-bottom:12px +} +.switch-row { + display:flex; + align-items:center; + position:relative; + gap:16px; + padding:13px 0; + font-size:13px +} +.switch-row small { + display:block; + font-size:10px; + color:var(--muted); + margin-top:5px +} +.switch-row>input { + position:absolute; + right:0; + opacity:0; + width:36px; + height:23px; + cursor:pointer +} +.switch { + margin-left:auto; + display:block; + width:32px; + height:19px; + border-radius:20px; + background:#d8ddcf; + padding:3px; + pointer-events:none; + transition:background .2s +} +.switch:after { + content:""; + display:block; + width:13px; + height:13px; + border-radius:50%; + background:var(--paper); + box-shadow:0 1px 3px #1a231e20; + transition:transform .2s +} +.switch-row input:checked+.switch { + background:#6f8665 +} +.switch-row input:checked+.switch:after { + transform:translateX(13px) +} +.switch-row input:focus-visible+.switch { + outline:3px solid var(--accent); + outline-offset:4px +} +.config-tip { + border-top:1px solid var(--line); + margin-top:14px; + padding-top:20px; + font:9px/1.7 var(--mono); + color:var(--muted) +} +.config-tip>span { + margin-right:4px +} +.install-section { + padding-block:90px 75px +} +.install-heading { + display:flex; + align-items:end; + justify-content:space-between; + margin-bottom:35px +} +.install-heading .eyebrow { + color:var(--accent); + margin-bottom:18px +} +.install-heading>p { + font-size:13px; + line-height:1.9; + color:var(--muted); + margin-bottom:0 +} +.install-box { + border:1px solid #cbd1c4; + border-radius:5px; + overflow:hidden; + background:#fbfaf5 +} +.install-box-top { + display:flex; + align-items:center; + justify-content:space-between; + padding:16px 23px; + border-bottom:1px solid var(--line); + font:9px var(--mono); + letter-spacing:1px +} +.install-box-top>span { + display:flex; + align-items:center; + gap:8px; + color:var(--muted) +} +.tiny-square { + width:5px; + height:5px; + background:var(--accent) +} +.copy-button { + border:0; + background:none; + font:11px var(--mono); + color:var(--ink); + padding:3px +} +.copy-button span { + margin-left:8px +} +.install-box pre { + font:13px/1.8 var(--mono); + padding:27px 24px; + margin:0; + overflow-x:auto; + white-space:pre-wrap; + overflow-wrap:anywhere +} +.install-box-bottom { + padding:12px 23px; + background:#efeee5; + display:flex; + justify-content:space-between; + font:9px/1.6 var(--mono); + color:var(--muted); + gap:10px +} +.install-box-bottom>span span { + margin-inline:8px +} +.install-box-bottom a { + text-decoration:underline; + text-underline-offset:3px +} +.copy-status { + font:11px var(--mono); + color:var(--green); + height:17px; + margin:10px 0 0 +} +.install-details { + display:grid; + grid-template-columns:1fr 1fr; + gap:70px; + margin-top:34px +} +.detail-icon { + font:27px Georgia; + color:var(--accent) +} +.install-details h3 { + margin-top:12px; + font-size:17px +} +.install-details p { + font-size:13px; + line-height:1.8; + color:var(--muted); + max-width:365px; + margin-bottom:18px +} +code { + font-family:var(--mono) +} +.install-details p code { + font-size:11px; + color:var(--ink) +} +.undo-code { + font-size:11px; + background:#ebece3; + padding:9px 11px; + display:inline-block; + border-radius:3px +} +.requirements { + border-block:1px solid var(--line); + margin-top:45px; + font-size:12px +} +.requirements summary { + display:flex; + justify-content:space-between; + list-style:none; + padding:19px 0; + cursor:pointer +} +.requirements summary::-webkit-details-marker { + display:none +} +.requirements summary span { + font-size:17px +} +.requirements[open] summary span { + transform:rotate(45deg) +} +.requirements>div { + max-width:850px; + font-size:12px; + line-height:1.9; + color:var(--muted); + padding-bottom:15px +} +.requirements a { + text-decoration:underline; + text-underline-offset:3px +} +.closing { + display:flex; + align-items:center; + gap:24px; + border-bottom:1px solid var(--line); + padding-bottom:70px +} +.closing-mark { + font-size:82px; + line-height:1; + color:var(--accent) +} +.closing>p { + font-size:26px; + line-height:1.25; + letter-spacing:-.7px; + margin:0 +} +.closing em { + font-size:31px +} +.closing .button { + margin-left:auto +} +.button-outline { + border:1px solid #b7c1ad; + background:transparent +} +.button-outline:hover { + background:#e8ecdf +} +.site-footer { + display:flex; + justify-content:space-between; + align-items:center; + gap:15px; + padding-block:35px +} +.site-footer .brand { + font-size:19px +} +.site-footer .brand-mark { + font-size:29px; + margin-right:6px +} +.site-footer p { + font:9px var(--mono); + color:var(--muted) +} +.site-footer>div { + display:flex; + gap:20px; + font:10px var(--mono); + color:var(--muted) +} +@keyframes blink { + 50% { + opacity:0 + } +} +@media(min-width:1500px) { + .hero { + gap:70px + } + #dashboard { + font-size:13.5px + } +} +@media(max-width:1100px) { + .wrap { + width:calc(100% - 64px) + } + .hero { + gap:27px + } + h1 { + letter-spacing:-4px + } + .hero-spark { + font-size:60px; + margin-left:15px + } + .hero .eyebrow { + font-size:8px; + letter-spacing:.7px + } + .hero-description { + font-size:14px + } + .hero-actions { + gap:17px + } + .hero-actions .button { + font-size:11px; + padding:16px; + gap:14px + } + .hero-meta { + font-size:8px + } + .hero-meta span { + padding-inline:5px + } + .terminal-footer { + font-size:6px + } + .terminal-body { + padding:17px 11px 10px + } + .preview-controls>span { + font-size:8px + } + .segmented button { + font-size:9px; + padding:7px 8px + } + .config-layout { + gap:55px + } + .config-copy h2 { + font-size:44px + } + .config-card { + padding:25px + } + .site-footer p { + font-size:8px + } +} +@media(max-width:820px) { + .hero { + grid-template-columns:1fr; + gap:45px; + padding-block:50px 55px + } + .hero-copy { + max-width:600px + } + .hero h1 { + font-size:84px; + letter-spacing:-4.8px + } + .hero h1 br:nth-of-type(2) { + display:none + } + .hero-spark { + font-size:68px; + margin-left:26px; + bottom:4px + } + .hero .eyebrow { + font-size:9px + } + .hero-description { + font-size:16px + } + .hero-actions .button { + font-size:13px; + padding:17px 21px + } + .hero-meta { + font-size:9px + } + .hero-visual { + max-width:650px; + width:100%; + margin-inline:auto + } + .terminal { + transform:rotate(-.7deg) + } + #dashboard { + font-size:clamp(8px,1.3vw,10.6px) + } + .terminal-body { + padding:22px + } + .terminal-footer { + font-size:8px + } + .preview-controls>span { + font-size:10px + } + .segmented button { + font-size:11px + } + .hand-note { + display:none + } + .intro { + grid-template-columns:1fr; + gap:25px; + padding-top:55px + } + .intro>p { + max-width:100% + } + .features { + gap:22px; + padding-bottom:55px + } + .feature-graphic { + padding-inline:3px; + height:105px + } + .features h3 { + font-size:17px + } + .features p { + font-size:12px + } + .runtime-graphic small { + font-size:8px; + padding:4px + } + .runtime-graphic>span { + font-size:11px + } + .health-graphic { + gap:10px + } + .health-icon { + width:31px; + height:31px; + flex-shrink:0; + font-size:17px + } + .health-graphic>span:last-child { + font-size:13px + } + .health-graphic small { + font-size:6px + } + .config-layout { + gap:35px + } + .config-copy h2 { + font-size:36px + } + .config-copy p:not(.eyebrow) { + font-size:12px + } + .config-copy p br { + display:none + } + .config-card { + padding:22px + } + .config-tip { + font-size:8px + } + .config-footnote { + font-size:9px + } + .install-section { + padding-block:60px + } + .install-heading>p { + font-size:11px + } + .install-details { + gap:30px + } + .site-footer p { + display:none + } +} +@media(max-width:560px) { + .wrap { + width:calc(100% - 40px) + } + .site-header { + height:80px + } + .brand { + font-size:22px + } + .brand-mark { + font-size:33px + } + nav { + gap:0 + } + nav>a:not(.nav-github) { + display:none + } + .nav-github { + font-size:11px; + padding:9px 13px + } + .hero { + padding-top:35px; + gap:35px + } + .hero .eyebrow { + font-size:7px; + letter-spacing:.9px; + margin-bottom:22px + } + h1,.hero h1 { + font-size:69px; + letter-spacing:-4px + } + .hero h1 br:nth-of-type(2) { + display:block + } + .hero-spark { + font-size:62px; + bottom:3px; + margin-left:26px + } + .hero-description { + font-size:14px + } + .hero-actions { + gap:22px + } + .hero-actions .button { + font-size:11px; + padding:15px; + gap:15px + } + .text-link { + font-size:11px + } + .hero-meta { + font-size:7px; + margin-top:24px + } + .hero-meta span { + padding-inline:6px + } + .visual-label { + font-size:7px + } + .terminal-chrome { + height:33px; + font-size:8px + } + .terminal-body { + padding:16px 10px 10px + } + .terminal-command,.terminal-prompt { + font-size:9px + } + #dashboard { + font-size:clamp(5px,1.95vw,8.5px); + line-height:1.8; + letter-spacing:-.1px + } + .terminal-footer { + font-size:5.5px; + padding:10px + } + .terminal-footer>span:last-child { + font-size:5px + } + .preview-controls { + margin-top:18px + } + .preview-controls>span { + font-size:7px + } + .segmented button { + font-size:9px; + padding:7px 9px + } + .spec-inner { + display:grid; + grid-template-columns:1fr 1fr; + gap:17px; + font-size:9px; + padding-block:21px + } + .spec-inner b { + font-size:8px; + margin-right:8px + } + .intro { + padding-block:44px 30px + } + .intro .eyebrow { + font-size:8px + } + h2 { + font-size:34px; + letter-spacing:-1.4px + } + .intro>p { + font-size:13px; + line-height:1.8 + } + .features { + grid-template-columns:1fr; + gap:30px; + padding-bottom:45px + } + .features article { + position:relative; + min-height:152px; + padding-right:135px + } + .feature-number { + font-size:8px + } + .feature-graphic { + position:absolute; + right:0; + top:20px; + width:115px; + margin:0; + height:110px + } + .features h3 { + font-size:18px; + margin-top:19px + } + .features p { + font-size:12px + } + .runtime-graphic>span { + font-size:9px; + gap:5px + } + .runtime-graphic small { + font-size:7px; + padding:4px + } + .health-graphic { + flex-direction:column; + gap:8px; + text-align:center + } + .health-graphic>span:last-child { + font-size:11px + } + .health-graphic small { + font-size:6px; + margin-top:5px + } + .metric-graphic span { + font-size:9px + } + .metric-graphic>div { + height:12px + } + .config-section { + padding-block:42px + } + .config-layout { + grid-template-columns:1fr; + gap:28px + } + .config-copy .eyebrow { + font-size:8px; + margin-bottom:18px + } + .config-copy h2 { + font-size:37px + } + .config-copy p:not(.eyebrow) { + font-size:13px; + margin:19px 0 + } + .config-footnote { + display:none + } + .config-card { + padding:24px + } + .config-tip { + font-size:9px + } + .install-section { + padding-block:45px + } + .install-heading { + display:block; + margin-bottom:26px + } + .install-heading .eyebrow { + font-size:8px + } + .install-heading>p { + font-size:12px; + margin-top:22px + } + .install-box-top { + padding:14px; + font-size:7px; + letter-spacing:.6px + } + .copy-button { + font-size:9px + } + .install-box pre { + padding:22px 15px; + font-size:11px + } + .install-box-bottom { + font-size:7px; + padding:12px 14px; + flex-wrap:wrap + } + .install-box-bottom>span span { + margin-inline:4px + } + .install-details { + grid-template-columns:1fr; + gap:27px; + margin-top:20px + } + .install-details h3 { + font-size:17px + } + .install-details p { + font-size:12px; + margin-top:8px; + max-width:100% + } + .detail-icon { + font-size:24px + } + .undo-code { + font-size:10px + } + .requirements { + margin-top:35px + } + .requirements summary { + font-size:11px + } + .closing { + gap:15px; + flex-wrap:wrap; + padding-bottom:38px + } + .closing-mark { + font-size:60px + } + .closing>p { + font-size:22px + } + .closing em { + font-size:26px + } + .closing .button { + margin-left:0; + width:100%; + margin-top:10px; + font-size:12px; + padding:15px 19px + } + .site-footer { + padding-block:25px + } + .site-footer .brand { + font-size:16px + } + .site-footer .brand-mark { + font-size:24px + } + .site-footer>div { + font-size:8px; + gap:16px + } +} +@media(prefers-reduced-motion:reduce) { + html { + scroll-behavior:auto + } + *,*:before,*:after { + animation:none!important; + transition:none!important + } +} +.brand-mark svg,.hero-spark svg,.closing-mark svg { + width:1em; + height:1em; + display:block +} +.brand-mark,.hero-spark,.closing-mark { + display:inline-block +} diff --git a/src/install.py b/src/install.py new file mode 100644 index 0000000..d5d7ff3 --- /dev/null +++ b/src/install.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +"""Install a system-wide Ubuntu/Debian MOTD with transactional backup/restore.""" +import argparse +import fcntl +import importlib.util +import json +import os +from pathlib import Path +import re +import shutil +import stat +import subprocess +import sys +import tempfile + +PROJECT = Path(__file__).resolve().parents[1] +HOOK = '/etc/update-motd.d/00-server-status' +BINARY = '/usr/local/bin/server-status' +CONFIG = '/etc/server-status/config.json' +STATE = '/var/lib/server-status' +SUFFIX = '~server-status-disabled' +PAM_FILES = ('/etc/pam.d/sshd', '/etc/pam.d/login') +PAM_LINE = 'session optional pam_exec.so stdout type=open_session quiet /etc/update-motd.d/00-server-status' +PAM_PATTERN = re.compile(r'^session[^\n]*pam_motd\.so[^\n]*motd=/run/motd\.dynamic[^\n]*$', re.MULTILINE) +WRAPPER = '''#!/bin/sh +# Managed by server-status. PAM invokes this for all users. +# Keep login working even if probes, disks or configuration fail. +PATH=/usr/sbin:/usr/bin:/sbin:/bin +export PATH +export PYTHONIOENCODING=utf-8 +if ! /usr/bin/timeout --kill-after=1 6 /usr/bin/python3 -I /usr/local/bin/server-status 2>/dev/null; then + printf '\\n Server status unavailable; run server-status to diagnose.\\n\\n' +fi +exit 0 +''' + + +def renderer(): + spec = importlib.util.spec_from_file_location('server_status', PROJECT / 'src/server_status.py') + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def atomic(path, data, mode=0o644): + path.parent.mkdir(parents=True, exist_ok=True) + fd, temporary = tempfile.mkstemp(prefix='.server-status-', dir=path.parent) + try: + with os.fdopen(fd, 'wb') as stream: + stream.write(data) + stream.flush() + os.fsync(stream.fileno()) + os.chmod(temporary, mode) + os.replace(temporary, path) + finally: + if os.path.exists(temporary): + os.unlink(temporary) + + +class Installation: + def __init__(self, root): + self.root = root + self.state = self.path(STATE) + self.manifest = self.state / 'manifest.json' + + def path(self, absolute): + return self.root / absolute.lstrip('/') + + def snapshot(self, names, folder): + folder.mkdir(parents=True, exist_ok=True, mode=0o700) + records = {} + for i, name in enumerate(names): + path = self.path(name) + if path.is_symlink(): + records[name] = {'kind': 'symlink', 'target': os.readlink(path), 'uid': path.lstat().st_uid, 'gid': path.lstat().st_gid} + elif path.exists(): + if not path.is_file(): + raise ValueError(f'refusing to replace non-file: {name}') + backup = folder / str(i) + shutil.copy2(path, backup) + info = path.stat() + records[name] = {'kind': 'file', 'backup': str(backup.relative_to(self.state)), 'mode': stat.S_IMODE(info.st_mode), 'uid': info.st_uid, 'gid': info.st_gid} + else: + records[name] = {'kind': 'absent'} + return records + + def restore(self, records): + for name, record in records.items(): + path = self.path(name) + if path.is_symlink() or path.is_file(): + path.unlink() + elif path.exists(): + raise ValueError(f'refusing to overwrite directory during restore: {name}') + if record['kind'] != 'absent': + path.parent.mkdir(parents=True, exist_ok=True) + if record['kind'] == 'symlink': + path.symlink_to(record['target']) + os.lchown(path, record['uid'], record['gid']) + else: + shutil.copy2(self.state / record['backup'], path) + os.chmod(path, record['mode']) + os.chown(path, record['uid'], record['gid']) + + def hooks(self): + directory = self.path('/etc/update-motd.d') + if shutil.which('run-parts'): + selected = subprocess.run(['run-parts', '--lsbsysinit', '--test', str(directory)], capture_output=True, text=True, check=True, timeout=5) + return sorted('/etc/update-motd.d/' + Path(line).name for line in selected.stdout.splitlines() if Path(line).name != Path(HOOK).name) + return sorted('/etc/update-motd.d/' + p.name for p in directory.iterdir() + if p.name != Path(HOOK).name and re.fullmatch(r'[A-Za-z0-9_-]+', p.name) + and (p.is_file() or p.is_symlink()) and os.access(p, os.X_OK)) + + def install(self, cfg, dry_run): + hooks = self.hooks() + names = [BINARY, CONFIG, HOOK, '/etc/motd', '/run/motd.dynamic', *PAM_FILES] + for name in hooks: + if self.path(name + SUFFIX).exists() or self.path(name + SUFFIX).is_symlink(): + raise ValueError('disabled-hook name collision: ' + name + SUFFIX) + names.extend([name, name + SUFFIX]) + print('Install system-wide banner; disable ' + str(len(hooks)) + ' Ubuntu MOTD hooks.') + print('Configuration: ' + str(self.path(CONFIG))) + if dry_run: + print('Dry run: no files changed.') + return + existing = json.loads(self.manifest.read_text()) if self.manifest.exists() else {} + transaction = Path(tempfile.mkdtemp(prefix='backup-', dir=self.state)) + before = self.snapshot(names, transaction) + baseline = dict(existing) + for name, record in before.items(): + baseline.setdefault(name, record) + try: + for name in hooks: + os.replace(self.path(name), self.path(name + SUFFIX)) + atomic(self.path(BINARY), (PROJECT / 'src/server_status.py').read_bytes(), 0o755) + atomic(self.path(CONFIG), (json.dumps(cfg, indent=2, ensure_ascii=False) + '\n').encode()) + atomic(self.path(HOOK), WRAPPER.encode(), 0o755) + for name in PAM_FILES: + pam = self.path(name) + content = pam.read_text() + if PAM_LINE not in content: + updated, count = PAM_PATTERN.subn(PAM_LINE, content) + if count != 1: + raise ValueError('expected one dynamic MOTD session entry in ' + name) + atomic(pam, updated.encode(), stat.S_IMODE(pam.stat().st_mode)) + # Empty rather than remove a symlink: restore() has the original target. + atomic(self.path('/etc/motd'), b'') + if self.root == Path('/'): + selected = subprocess.run(['/usr/bin/run-parts', '--lsbsysinit', '--test', '/etc/update-motd.d'], capture_output=True, text=True, check=True, timeout=5) + if selected.stdout.splitlines() != [HOOK]: + raise ValueError('unexpected executable MOTD hooks: ' + selected.stdout) + refresh = subprocess.run(['/usr/bin/timeout', '--kill-after=1', '8', '/usr/bin/python3', '-I', BINARY], capture_output=True, timeout=10) + if refresh.returncode: + raise ValueError('initial rendering failed: ' + refresh.stderr.decode(errors='replace')) + atomic(self.path('/run/motd.dynamic'), refresh.stdout) + atomic(self.manifest, (json.dumps(baseline, indent=2) + '\n').encode(), 0o600) + except BaseException: + self.restore(before) + raise + print('Installed. Existing config preserved unless --config or customization flags were supplied.') + print('Undo: sudo ./setup.sh uninstall') + + def uninstall(self, dry_run): + if not self.manifest.exists(): + print('No managed installation found.') + return + original = json.loads(self.manifest.read_text()) + print('Restore ' + str(len(original)) + ' paths from the original installation backup.') + if dry_run: + print('Dry run: no files changed.') + return + transaction = Path(tempfile.mkdtemp(prefix='uninstall-', dir=self.state)) + before = self.snapshot(list(original), transaction) + try: + self.restore(original) + self.manifest.rename(self.state / 'last-uninstall.json') + except BaseException: + self.restore(before) + raise + print('Original login messages restored. Backups retained in ' + str(self.state)) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('action', choices=('install', 'uninstall', 'status'), nargs='?', default='install') + parser.add_argument('--config', type=Path, help='JSON configuration; validated before changes') + parser.add_argument('--title', help='display name (default: hostname)') + parser.add_argument('--address', help='display address (default: auto)') + parser.add_argument('--no-color', action='store_true') + parser.add_argument('--ascii', action='store_true') + parser.add_argument('--wizard', action='store_true', help='interactive title, address, services and disk customization') + parser.add_argument('--dry-run', action='store_true') + parser.add_argument('--root', type=Path, default=Path('/'), help=argparse.SUPPRESS) + args = parser.parse_args() + installation = Installation(args.root.resolve()) + if args.action == 'status': + print('Installed' if installation.manifest.exists() else 'Not installed') + print('Backup directory: ' + str(installation.state)) + return 0 + if installation.root == Path('/'): + if any(not Path(p).exists() for p in ('/usr/bin/python3', '/usr/bin/timeout', '/usr/bin/run-parts')): + raise ValueError('requires python3, GNU coreutils timeout and Debian run-parts') + if args.action == 'install': + for pam in ('sshd', 'login'): + content = Path('/etc/pam.d/' + pam).read_text() + if PAM_LINE not in content and not any('pam_motd.so' in line and not line.lstrip().startswith('#') and 'noupdate' not in line and 'motd=/run/motd.dynamic' in line for line in content.splitlines()): + raise ValueError('requires existing dynamic pam_motd configuration in /etc/pam.d/' + pam) + if not list(Path('/usr/lib').glob('**/security/pam_exec.so')) and not Path('/lib/security/pam_exec.so').exists(): + raise ValueError('requires the standard pam_exec.so session module') + check = subprocess.run(['/usr/sbin/sshd', '-T'], capture_output=True, text=True, timeout=5) + if check.returncode or 'usepam yes' not in check.stdout or 'printmotd no' not in check.stdout: + raise ValueError('SSH must already have UsePAM yes and PrintMotd no; only MOTD session-display lines are managed') + if args.action == 'install': + source = args.config or (installation.path(CONFIG) if installation.path(CONFIG).exists() else PROJECT / 'config/default.json') + if not source.is_file(): + raise ValueError('configuration file not found: ' + str(source)) + cfg = renderer().config(source) + if args.title is not None: + cfg['title'] = args.title + if args.address is not None: + cfg['address'] = args.address + if args.no_color: + cfg['color'] = False + if args.ascii: + cfg['ascii'] = True + if args.wizard: + cfg['title'] = input(f'Display title [{cfg["title"] or "automatic hostname"}]: ').strip() or cfg['title'] + cfg['address'] = input(f'IP address [{cfg["address"]}]: ').strip() or cfg['address'] + units = input('Service units, comma separated (blank: keep current; none: no services): ').strip() + if units: + cfg['services'] = [] if units == 'none' else [{'unit': unit.strip(), 'label': unit.strip().removesuffix('.service'), 'required': True} for unit in units.split(',')] + disks = input('Disk paths, comma separated (blank: keep current): ').strip() + if disks: + cfg['disks'] = [d.strip() for d in disks.split(',')] + # Validate CLI/wizard values before touching the system. + with tempfile.TemporaryDirectory() as directory: + candidate = Path(directory) / 'config.json' + candidate.write_text(json.dumps(cfg)) + cfg = renderer().config(candidate) + if args.dry_run: + if args.action == 'install': + installation.install(cfg, True) + else: + installation.uninstall(True) + return 0 + if os.geteuid() != 0: + raise ValueError('run installation/uninstallation with sudo (or use --dry-run)') + installation.state.mkdir(parents=True, exist_ok=True, mode=0o700) + os.chmod(installation.state, 0o700) + with (installation.state / 'lock').open('w') as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + if args.action == 'install': + installation.install(cfg, False) + else: + installation.uninstall(False) + return 0 + + +if __name__ == '__main__': + try: + sys.exit(main()) + except (ValueError, OSError, subprocess.SubprocessError) as exc: + print('setup: ' + str(exc), file=sys.stderr) + sys.exit(1) diff --git a/src/server_status.py b/src/server_status.py new file mode 100755 index 0000000..5f83260 --- /dev/null +++ b/src/server_status.py @@ -0,0 +1,294 @@ +#!/usr/bin/python3 +"""A bounded, dependency-free system status MOTD for Linux.""" +import argparse +import concurrent.futures +import json +import os +from pathlib import Path +import re +import shutil +import socket +import subprocess +import sys +import time +import unicodedata + +DEFAULTS = { + 'title': '', 'address': 'auto', 'width': 72, 'color': True, 'ascii': False, + 'sections': ['system', 'runtime', 'health'], + 'services': [{'unit': 'nginx.service', 'label': 'Nginx', 'required': False}, + {'unit': 'docker.service', 'label': 'Docker', 'required': False}], + 'disks': ['/'], 'docker': True, 'command_timeout': 1.0, + 'memory_warning': 75, 'memory_critical': 90, 'disk_warning': 75, + 'disk_critical': 90, 'load_warning': .7, 'load_critical': 1., + 'updates_max_age_hours': 48, 'footer': '', +} +ANSI = re.compile(r'\x1b\[[0-9;]*m') + + +def clean(value): + return ''.join(c for c in str(value) if unicodedata.category(c)[0] != 'C') + + +def cells(value): + return sum(0 if unicodedata.combining(c) else + 2 if unicodedata.east_asian_width(c) in ('W', 'F') else 1 + for c in ANSI.sub('', value)) + + +def clip(value, width): + result = '' + for char in clean(value): + if cells(result + char) > width: + break + result += char + return result + + +def config(path): + cfg = dict(DEFAULTS) + if path and Path(path).exists(): + overrides = json.loads(Path(path).read_text()) + if not isinstance(overrides, dict): + raise ValueError('configuration must be a JSON object') + unknown = set(overrides) - set(DEFAULTS) + if unknown: + raise ValueError('unknown settings: ' + ', '.join(sorted(unknown))) + cfg.update(overrides) + for key in ('title', 'address', 'footer'): + if not isinstance(cfg[key], str): + raise ValueError(key + ' must be a string') + for key in ('color', 'ascii', 'docker'): + if type(cfg[key]) is not bool: + raise ValueError(key + ' must be true or false') + if type(cfg['width']) is not int or not 52 <= cfg['width'] <= 120: + raise ValueError('width must be an integer from 52 to 120') + for key in ('command_timeout', 'updates_max_age_hours', 'memory_warning', + 'memory_critical', 'disk_warning', 'disk_critical', 'load_warning', 'load_critical'): + if type(cfg[key]) not in (int, float) or not 0 < cfg[key] < float('inf'): + raise ValueError(key + ' must be a positive finite number') + if not .1 <= cfg['command_timeout'] <= 2: + raise ValueError('command_timeout must be between 0.1 and 2 seconds') + for metric in ('memory', 'disk', 'load'): + if cfg[metric + '_warning'] >= cfg[metric + '_critical']: + raise ValueError(metric + ': warning must be below critical') + for metric in ('memory', 'disk'): + if cfg[metric + '_critical'] > 100: + raise ValueError(metric + '_critical must be at most 100') + if not isinstance(cfg['sections'], list) or any(s not in ('system', 'runtime', 'health') for s in cfg['sections']): + raise ValueError('sections must contain system, runtime or health') + if not isinstance(cfg['disks'], list) or not 1 <= len(cfg['disks']) <= 8 or any(not isinstance(d, str) or not d.startswith('/') for d in cfg['disks']): + raise ValueError('disks must contain 1-8 absolute paths') + if not isinstance(cfg['services'], list) or len(cfg['services']) > 16: + raise ValueError('services must be a list of at most 16 entries') + for service in cfg['services']: + if not isinstance(service, dict) or set(service) - {'unit', 'label', 'required'}: + raise ValueError('each service accepts unit, label and required') + if not re.fullmatch(r'[A-Za-z0-9_][A-Za-z0-9_@.:-]*', service.get('unit', '')): + raise ValueError('invalid service unit') + if not isinstance(service.get('label', ''), str) or type(service.get('required', False)) is not bool: + raise ValueError('invalid service label or required flag') + return cfg + + +def command(args, timeout): + try: + p = subprocess.run(args, capture_output=True, text=True, timeout=timeout, + env={**os.environ, 'LC_ALL': 'C', 'PATH': '/usr/sbin:/usr/bin:/sbin:/bin'}) + return p.returncode, p.stdout.strip() + except (OSError, subprocess.TimeoutExpired, UnicodeError): + return -1, '' + + +def read(path): + try: + return Path(path).read_text() + except OSError: + return '' + + +def update_status(path, max_age, now=None): + source = Path(path) + try: + age = (time.time() if now is None else now) - source.stat().st_mtime + text = source.read_text() + except OSError: + return 'Package updates unknown (no cached data)', True + match = re.search(r'(?m)^\s*(\d+)\s+(?:updates? (?:can be applied|available)|packages? can be updated)', text) + if not match: + return 'Package updates unknown (unrecognized cache)', True + count = int(match[1]) + if age > max_age * 3600: + return f'Package cache stale ({count} updates last reported)', True + return (f'{count} package updates available' if count else 'Packages current (cached)'), bool(count) + + +def docker_status(result): + code, output = result + if code: + return 'Container status unavailable', True + rows = [r.split('|', 2) for r in output.splitlines() if len(r.split('|', 2)) == 3] + running = sum(r[1] == 'running' for r in rows) + unhealthy = sum('(unhealthy)' in r[2] for r in rows) + starting = sum('(health: starting)' in r[2] for r in rows) + healthy = sum('(healthy)' in r[2] for r in rows) + failed = sum(r[1] in ('dead', 'restarting') or (r[1] == 'exited' and not r[2].startswith('Exited (0)')) for r in rows) + text = f'{running} containers running' + if unhealthy or failed or starting: + text += f' · {unhealthy} unhealthy · {failed} failed · {starting} starting' + elif running: + text += f' · {healthy} healthchecked' if healthy else ' · no healthchecks' + return text, bool(unhealthy or failed or starting) + + +def collect(cfg): + jobs = {'failed': ['systemctl', '--failed', '--no-legend', '--plain', '--no-pager'], + 'ip': ['hostname', '-I']} + for i, service in enumerate(cfg['services']): + jobs[f'service{i}'] = ['systemctl', 'show', service['unit'], '--property=LoadState,ActiveState', '--no-pager'] + if cfg['docker'] and shutil.which('docker'): + # Pin the local daemon: never inherit a user's remote Docker context. + jobs['docker'] = ['docker', '--host', 'unix:///var/run/docker.sock', 'ps', '-a', '--format', '{{.Names}}|{{.State}}|{{.Status}}'] + with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor: + futures = {k: executor.submit(command, args, cfg['command_timeout']) for k, args in jobs.items()} + results = {k: future.result() for k, future in futures.items()} + return results + + +def render(cfg, results): + rows = [] + attention = False + def add(section, text, level='normal'): + nonlocal attention + rows.append((section, clean(text), level)) + attention |= level in ('warning', 'critical') + def level(value, metric): + return 'critical' if value >= cfg[metric + '_critical'] else 'warning' if value >= cfg[metric + '_warning'] else 'good' + try: + seconds = int(float(read('/proc/uptime').split()[0])) + uptime = f'{seconds // 86400}d {seconds % 86400 // 3600}h' if seconds >= 86400 else f'{seconds // 3600}h {seconds % 3600 // 60}m' + load = float(read('/proc/loadavg').split()[0]) + cores = os.cpu_count() or 1 + add('system', f'↑ Uptime {uptime} ≋ Load average {load:.2f} ({cores} cores)', level(load / cores, 'load')) + memory = {k: int(v.split()[0]) for k, v in (line.split(':', 1) for line in read('/proc/meminfo').splitlines())} + total = memory['MemTotal']; used = total - memory['MemAvailable'] + percent = used / total * 100 + add('system', f'Memory {bar(percent, cfg)} {percent:.0f}% · {used / 1048576:.1f} / {total / 1048576:.1f} GiB', level(percent, 'memory')) + except (ValueError, KeyError, IndexError, ZeroDivisionError): + add('system', 'System metrics unavailable', 'warning') + for disk in cfg['disks']: + try: + usage = shutil.disk_usage(disk) + stat = os.statvfs(disk) + # Match df: percentage uses space available to non-root, excluding reserved blocks. + denominator = usage.used + stat.f_bavail * stat.f_frsize + percent = usage.used / denominator * 100 if denominator else 0 + add('system', f'Disk {disk} {bar(percent, cfg)} {percent:.0f}% · {usage.used / 1073741824:.1f} / {usage.total / 1073741824:.1f} GiB', level(percent, 'disk')) + except OSError: + add('system', f'Disk {disk}: unavailable', 'warning') + for i, service in enumerate(cfg['services']): + code, output = results[f'service{i}'] + properties = dict(line.split('=', 1) for line in output.splitlines() if '=' in line) + label = service.get('label') or service['unit'] + if code or properties.get('LoadState') in (None, 'not-found'): + missing = properties.get('LoadState') == 'not-found' + add('runtime', f'● {label}: {"not installed" if missing else "status unavailable"}', 'warning' if service.get('required') or not missing else 'normal') + elif properties.get('ActiveState') == 'active': + add('runtime', f'● {label} is online', 'good') + else: + add('runtime', f'● {label} is {properties.get("ActiveState", "unknown")}', 'warning') + if cfg['docker']: + if 'docker' in results: + text, warning = docker_status(results['docker']) + add('runtime', ' ' + text, 'warning' if warning else 'good') + else: + add('runtime', ' Docker CLI not installed') + code, output = results['failed'] + if code: + add('health', '⚠ Failed services: status unavailable', 'warning') + else: + failed = [line.split()[0] for line in output.splitlines() if line.strip()] + add('health', f'⚠ {len(failed)} units failed · ' + ', '.join(failed[:3]) if failed else '✓ No failed systemd units', 'warning' if failed else 'good') + updates, warning = update_status('/var/lib/update-notifier/updates-available', cfg['updates_max_age_hours']) + add('health', ('↑ ' if warning else '✓ ') + updates, 'warning' if warning else 'good') + reboot = Path('/run/reboot-required').exists() + add('health', '↻ Reboot required' if reboot else '✓ No reboot needed', 'warning' if reboot else 'good') + firmware = read('/run/motd.d/85-fwupd') + match = re.search(r'(\d+) devices? have a firmware upgrade available', firmware) + if match and int(match[1]): + add('health', f'↑ {match[1]} firmware upgrades available', 'warning') + os_name = 'Linux' + for line in read('/etc/os-release').splitlines(): + if line.startswith('PRETTY_NAME='): + os_name = line.split('=', 1)[1].strip('"') + ip = cfg['address'] + if ip == 'auto': + addresses = results['ip'][1].split() + ip = next((a for a in addresses if ':' not in a), addresses[0] if addresses else 'address unavailable') + title = cfg['title'] or socket.gethostname().split('.')[0].upper() + return box(cfg, title, os_name + ' · ' + ip, rows, attention) + + +def bar(percent, cfg): + filled = max(0, min(18, int(percent * 18 / 100 + .5))) + return ('#' if cfg['ascii'] else '█') * filled + ('-' if cfg['ascii'] else '░') * (18 - filled) + + +def box(cfg, title, subtitle, rows, attention): + width = cfg['width'] + color = cfg['color'] and 'NO_COLOR' not in os.environ + colors = {'normal': '', 'good': '\033[32m', 'warning': '\033[33m', 'critical': '\033[31m', 'border': '\033[36m'} + def paint(text, kind): + return colors[kind] + text + '\033[0m' if color and colors[kind] else text + ascii_mode = cfg['ascii'] + h, v = ('-', '|') if ascii_mode else ('─', '│') + tl, tr, bl, br, ml, mr = ('+',) * 6 if ascii_mode else ('╭', '╮', '╰', '╯', '├', '┤') + def plain(text): + if ascii_mode: + for a, b in {'◆': '*', '●': '*', '↑': '^', '≋': '~', '✓': '+', '⚠': '!', '↻': '*', '·': '/'}.items(): + text = text.replace(a, b) + text = text.encode('ascii', 'replace').decode() + return clean(text) + def line(text='', kind='normal'): + text = clip(plain(text), width - 2) + return ' ' + paint(v, 'border') + ' ' + paint(text, kind) + ' ' * (width - 1 - cells(text)) + paint(v, 'border') + status = ('● ATTENTION' if attention else '● HEALTHY') + left = clip(plain('◆ ' + title), width - cells(plain(status)) - 4) + header = left + ' ' * (width - 2 - cells(left) - cells(plain(status))) + status + output = ['', ' ' + paint(tl + h * width + tr, 'border'), line(header, 'warning' if attention else 'good'), line(' ' + subtitle)] + for section in cfg['sections']: + label = h + ' ' + section.upper() + ' ' + output.append(' ' + paint(ml + label + h * (width - cells(label)) + mr, 'border')) + output.append(line()) + for row_section, text, kind in rows: + if row_section == section: + output.append(line(' ' + text, kind)) + output.append(line()) + if cfg['footer']: + output.append(line(cfg['footer'])) + output.extend([' ' + paint(bl + h * width + br, 'border'), '']) + return '\n'.join(output) + '\n' + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--config', default='/etc/server-status/config.json') + parser.add_argument('--check', action='store_true', help='validate configuration without running probes') + parser.add_argument('--no-color', action='store_true') + args = parser.parse_args() + try: + cfg = config(args.config) + if args.no_color: + cfg['color'] = False + if args.check: + print('Configuration valid') + return 0 + print(render(cfg, collect(cfg)), end='') + return 0 + except (ValueError, OSError, TypeError) as exc: + print('server-status: ' + str(exc), file=sys.stderr) + return 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/test_public_release.py b/tests/test_public_release.py new file mode 100644 index 0000000..6c2357d --- /dev/null +++ b/tests/test_public_release.py @@ -0,0 +1,138 @@ +import hashlib +import importlib.util +import io +import json +import os +from pathlib import Path +import shutil +import subprocess +import tarfile +import tempfile +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location('build_site', ROOT / 'scripts/build_site.py') +builder = importlib.util.module_from_spec(spec) +spec.loader.exec_module(builder) + + +class BuildTests(unittest.TestCase): + def test_reproducible_payload_exact_allowlist_and_rendered_bootstrap(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + first = builder.build(root / 'first', 'https://example.github.io/shell-gleam') + second = builder.build(root / 'second', 'https://example.github.io/shell-gleam') + self.assertEqual(first, second) + archive = root / 'first' / first['archive'] + self.assertEqual(hashlib.sha256(archive.read_bytes()).hexdigest(), first['sha256']) + with tarfile.open(archive) as package: + self.assertEqual(set(package.getnames()), {'shell-gleam/' + name for name in builder.PACKAGE_FILES}) + self.assertTrue(all(member.isfile() for member in package)) + bootstrap = (root / 'first/setup.sh').read_text() + self.assertNotIn('@@', bootstrap) + self.assertIn(first['sha256'], bootstrap) + self.assertIn('https://example.github.io/shell-gleam', bootstrap) + subprocess.run(['bash', '-n', str(root / 'first/setup.sh')], check=True) + + def test_unlisted_local_file_never_enters_package(self): + with tempfile.TemporaryDirectory() as directory: + fixture = Path(directory) / 'source' + for name in (*builder.PACKAGE_FILES, 'scripts/bootstrap.sh', *('site/' + a for a in builder.ASSETS)): + destination = fixture / name + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(ROOT / name, destination) + (fixture / 'config/local-secret.json').write_text('{"token":"do-not-package"}') + with patch.object(builder, 'ROOT', fixture): + release = builder.build(Path(directory) / 'output', 'https://example.github.io/shell-gleam') + with tarfile.open(Path(directory) / 'output' / release['archive']) as package: + self.assertFalse(any('local-secret' in name for name in package.getnames())) + + def test_source_root_cannot_be_output(self): + with self.assertRaises(ValueError): + builder.build(ROOT, 'https://example.github.io/shell-gleam') + + +class BootstrapTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.bin = self.root / 'bin' + self.bin.mkdir() + self.tmp = self.root / 'tmp' + self.tmp.mkdir() + self.archive = self.root / 'payload.tar.gz' + for name, content in { + 'id': '#!/bin/sh\necho 0\n', + 'curl': '#!/usr/bin/env python3\nimport os,shutil,sys\nif os.environ.get("TEST_CURL_FAIL"): sys.exit(22)\nshutil.copyfile(os.environ["TEST_ARCHIVE"], sys.argv[sys.argv.index("-o")+1])\n', + }.items(): + path = self.bin / name + path.write_text(content) + path.chmod(0o755) + self.env = {**os.environ, 'PATH': str(self.bin) + ':' + os.environ['PATH'], + 'TEST_ARCHIVE': str(self.archive), 'TMPDIR': str(self.tmp), + 'SHELL_GLEAM_BASE_URL': 'http://127.0.0.1:8000'} + + def package(self, name='shell-gleam/setup.sh', symlink=False): + with tarfile.open(self.archive, 'w:gz') as package: + data = b'#!/bin/sh\nprintf "ARG=<%s>\\n" "$@"\n' + member = tarfile.TarInfo(name) + member.mode = 0o755 + if symlink: + member.type = tarfile.SYMTYPE + member.linkname = '/etc/passwd' + package.addfile(member) + else: + member.size = len(data) + package.addfile(member, io.BytesIO(data)) + + def run_bootstrap(self, *args, wrong_checksum=False): + checksum = hashlib.sha256(self.archive.read_bytes()).hexdigest() + template = (ROOT / 'scripts/bootstrap.sh').read_text() + script = template.replace('@@SHA256@@', '0' * 64 if wrong_checksum else checksum).replace('@@ARCHIVE@@', 'downloads/test.tar.gz').replace('@@SITE_URL@@', 'https://example.github.io/shell-gleam') + return subprocess.run(['bash', '-s', '--', *args], input=script, capture_output=True, text=True, env=self.env) + + def test_piped_execution_argument_forwarding_and_cleanup(self): + self.package() + result = self.run_bootstrap('install', '--dry-run', '--title', "O'Brien $(touch nope); *") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("ARG=", result.stdout) + self.assertIn('SHA-256 verified', result.stdout) + self.assertEqual(list(self.tmp.iterdir()), []) + + def test_checksum_failure_stops_before_setup(self): + self.package() + result = self.run_bootstrap('--dry-run', wrong_checksum=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn('checksum mismatch', result.stderr) + self.assertNotIn('ARG=', result.stdout) + self.assertEqual(list(self.tmp.iterdir()), []) + + def test_traversal_and_symlinks_rejected(self): + for name, symlink in [('shell-gleam/../../escape', False), ('shell-gleam/link', True)]: + with self.subTest(name=name): + self.package(name, symlink) + result = self.run_bootstrap('--dry-run') + self.assertNotEqual(result.returncode, 0) + self.assertIn('unsafe package', result.stderr) + self.assertFalse((self.root / 'escape').exists()) + + def test_download_failure_stops_before_setup(self): + self.package() + self.env['TEST_CURL_FAIL'] = '1' + result = self.run_bootstrap('--dry-run') + self.assertEqual(result.returncode, 22) + self.assertNotIn('ARG=', result.stdout) + self.assertEqual(list(self.tmp.iterdir()), []) + + def test_non_https_remote_override_rejected(self): + self.package() + self.env['SHELL_GLEAM_BASE_URL'] = 'http://example.com' + result = self.run_bootstrap('--dry-run') + self.assertNotEqual(result.returncode, 0) + self.assertIn('must use HTTPS', result.stderr) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_server_status.py b/tests/test_server_status.py new file mode 100644 index 0000000..6bd44b4 --- /dev/null +++ b/tests/test_server_status.py @@ -0,0 +1,137 @@ +import importlib.util +import json +import os +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch +import sys +import shutil +import subprocess + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src')) +import server_status as status +import install + + +class RendererTests(unittest.TestCase): + def test_cache_fresh_stale_missing_and_actual_ubuntu_format(self): + with tempfile.TemporaryDirectory() as directory: + cache = Path(directory) / 'updates' + self.assertTrue(status.update_status(cache, 48)[1]) + cache.write_text('Expanded Security Maintenance is not enabled.\n\n0 updates can be applied immediately.\n') + self.assertFalse(status.update_status(cache, 48)[1]) + self.assertTrue(status.update_status(cache, 48, cache.stat().st_mtime + 49 * 3600)[1]) + cache.write_text('12 updates can be applied immediately.\n') + self.assertIn('12 package', status.update_status(cache, 48)[0]) + cache.write_text('unknown output') + self.assertIn('unknown', status.update_status(cache, 48)[0]) + + def test_docker_health_is_not_invented(self): + self.assertIn('no healthchecks', status.docker_status((0, 'web|running|Up 2 days'))[0]) + text, warning = status.docker_status((0, 'web|running|Up 2 days (healthy)\nworker|exited|Exited (1) 2 days ago')) + self.assertTrue(warning) + self.assertIn('1 failed', text) + self.assertTrue(status.docker_status((-1, ''))[1]) + self.assertFalse(status.docker_status((0, 'job|exited|Exited (0) 1 day ago'))[1]) + + def test_border_alignment_truncation_control_codes_and_ascii(self): + cfg = dict(status.DEFAULTS, color=False) + for ascii_mode in (False, True): + cfg['ascii'] = ascii_mode + output = status.box(cfg, '測試' * 60 + '\x1b[31m', 'Ubuntu', [('system', 'x' * 200, 'normal')], True) + lines = [line for line in output.splitlines() if line] + self.assertEqual({status.cells(line) for line in lines}, {76}) + self.assertNotIn('\x1b', output) + if ascii_mode: + output.encode('ascii') + + def test_invalid_configuration_rejected(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'config.json' + for invalid in ({'width': 4}, {'command_timeout': 9}, {'services': [{'unit': '--help'}]}, {'sections': ['mystery']}, {'disk_warning': 95, 'disk_critical': 80}, {'color': 'yes'}, {'typo': True}, {'command_timeout': float('nan')}): + path.write_text(json.dumps(invalid)) + with self.subTest(invalid=invalid), self.assertRaises(ValueError): + status.config(path) + + +class InstallerTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.instance = install.Installation(self.root) + self.instance.state.mkdir(parents=True) + for name in install.PAM_FILES: + pam = self.instance.path(name) + pam.parent.mkdir(parents=True, exist_ok=True) + pam.write_text('# authentication unchanged\n@include common-auth\nsession optional pam_motd.so motd=/run/motd.dynamic\nsession optional pam_motd.so noupdate\n') + hooks = self.root / 'etc/update-motd.d' + hooks.mkdir(parents=True) + self.header = hooks / '00-header' + self.header.write_text('#!/bin/sh\necho old\n') + self.header.chmod(0o751) + (hooks / '50-landscape').symlink_to('/usr/share/landscape/wrapper') + # A relative executable symlink must be preserved as a symlink. + (hooks / '10-link').symlink_to('00-header') + (self.root / 'etc/motd').write_text('original static MOTD') + + def test_reinstall_new_package_hooks_and_uninstall_restore(self): + self.instance.install(dict(status.DEFAULTS), False) + self.assertIn(install.PAM_LINE, self.instance.path(install.PAM_FILES[0]).read_text()) + self.assertFalse(self.header.exists()) + self.assertTrue(Path(str(self.header) + install.SUFFIX).exists()) + config = self.instance.path(install.CONFIG) + customized = dict(status.DEFAULTS, title='CUSTOM') + config.write_text(json.dumps(customized)) + new_hook = self.root / 'etc/update-motd.d/90-new-package' + new_hook.write_text('new') + new_hook.chmod(0o755) + self.instance.install(customized, False) + self.assertEqual(json.loads(config.read_text())['title'], 'CUSTOM') + self.assertFalse(new_hook.exists()) + self.instance.uninstall(False) + for name in install.PAM_FILES: + content = self.instance.path(name).read_text() + self.assertIn('pam_motd.so motd=/run/motd.dynamic', content) + self.assertNotIn('pam_exec.so', content) + self.assertIn('@include common-auth', content) + self.assertEqual(self.header.read_text(), '#!/bin/sh\necho old\n') + self.assertEqual(self.header.stat().st_mode & 0o777, 0o751) + self.assertEqual(os.readlink(self.root / 'etc/update-motd.d/10-link'), '00-header') + self.assertEqual((self.root / 'etc/motd').read_text(), 'original static MOTD') + self.assertTrue(new_hook.exists()) + self.assertFalse(self.instance.path(install.HOOK).exists()) + self.assertFalse(config.exists()) + self.instance.uninstall(False) + + @unittest.skipUnless(shutil.which('run-parts'), 'Debian run-parts unavailable') + def test_pam_lsbsysinit_selects_only_managed_hook(self): + self.instance.install(dict(status.DEFAULTS), False) + selected = subprocess.check_output(['run-parts', '--lsbsysinit', '--test', str(self.root / 'etc/update-motd.d')], text=True) + self.assertEqual(selected.splitlines(), [str(self.instance.path(install.HOOK))]) + + def test_failure_restores_previous_files(self): + real_atomic = install.atomic + def fail_static(path, data, mode=0o644): + if path == self.instance.path('/etc/motd'): + raise OSError('simulated disk error') + real_atomic(path, data, mode) + with patch.object(install, 'atomic', fail_static), self.assertRaises(OSError): + self.instance.install(dict(status.DEFAULTS), False) + self.assertTrue(self.header.exists()) + self.assertEqual((self.root / 'etc/motd').read_text(), 'original static MOTD') + self.assertFalse(self.instance.path(install.BINARY).exists()) + self.assertFalse(self.instance.manifest.exists()) + for name in install.PAM_FILES: + self.assertIn('pam_motd.so motd=/run/motd.dynamic', self.instance.path(name).read_text()) + self.assertNotIn('pam_exec.so', self.instance.path(name).read_text()) + + def test_dry_run_changes_nothing(self): + self.instance.install(dict(status.DEFAULTS), True) + self.assertTrue(self.header.exists()) + self.assertFalse(self.instance.manifest.exists()) + + +if __name__ == '__main__': + unittest.main()