initial commit

This commit is contained in:
pik4li 2024-12-26 00:29:38 +01:00
parent 212a05d71a
commit e1427912f5
80 changed files with 8684 additions and 0 deletions

128
.github/CODE_OF_CONDUCT.md vendored Normal file
View file

@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
contact@christitus.com.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

70
.github/CONTRIBUTING.md vendored Normal file
View file

@ -0,0 +1,70 @@
# Contributing Guidelines for Linutil
Thank you for considering contributing to Linutil! We appreciate your effort in helping improve this project. To ensure that your contributions align with the goals and quality standards of Linutil, please follow these guidelines:
## 1. **Install Rust**:
Make sure you have Rust installed on your machine. You can install it by following the instructions at [rust-lang.org](https://www.rust-lang.org/tools/install).
## 2. **Fork and Clone the repo**
1. Make a fork of the repo in GitHub
2. Clone the fork
```bash
git clone https://github.com/YOUR_USERNAME_HERE/linutil.git
cd linutil
```
## 3. Make your changes
- **Edit the files you want to change**: Make your changes to the relevant files.
- **Test your changes**: Run `cargo run` to test your modifications in a local environment and ensure everything works as expected.
## 4. Understand the existing code
- **Have a clear reason**: Dont change the way things are done without a valid reason. If you propose an alteration, be prepared to explain why its necessary and how it improves the project.
- **Respect existing conventions**: Changes should align with the existing code style, design patterns, and overall project philosophy. If you want to introduce a new way of doing things, justify it clearly.
## 5. Learn from Past Pull Requests (PRs)
- **Check merged PRs**: Reviewing merged pull requests can give you an idea of what kind of contributions are accepted and how they are implemented.
- **Study rejected PRs**: This is especially important as it helps you avoid making similar mistakes or proposing changes that have already been considered and declined.
## 6. Write Clean, Descriptive Commit Messages
- **Be descriptive**: Your commit messages should clearly describe what the change does and why it was made.
- **Use the imperative mood**: For example, "Add feature X" or "Fix bug in Y", rather than "Added feature X" or "Fixed bug in Y".
- **Keep commits clean**: Avoid committing a change and then immediately following it with a fix for that change. Instead, amend your commit or squash it if needed.
## 7. Keep Your Pull Requests (PRs) Small and Focused
- **Make small, targeted PRs**: Focus on one feature or fix per pull request. This makes it easier to review and increases the likelihood of acceptance.
- **Avoid combining unrelated changes**: PRs that tackle multiple unrelated issues are harder to review and might be rejected because of a single problem.
## 8. Understand and Test the Code You Write
- **Review your code**: Before submitting your changes, take the time to review your code for readability, efficiency and performance. Consider how your changes affect the project.
- **Avoid using LLMs**: Don't submit AI-generated code without reviewing and testing it first. Ensure that any code you submit is thoroughly understood and meets the project's standards.
- **Testing Requirements**: Failure to conduct testing after multiple requests may result in the closure of your Pull Request.
## 9. Code Review and Feedback
- **Expect feedback**: PRs will undergo code review. Be open to feedback and willing to make adjustments as needed.
- **Participate in reviews**: If you feel comfortable, review other contributors' PRs as well. Peer review is a great way to learn and ensure high-quality contributions.
## 10. Contributing Is More Than Just Code
- **Test the tool**: Running tests and providing feedback on how the tool works in different environments is a valuable contribution.
- **Write well-formed issues**: Clearly describe bugs or problems you encounter, providing as much detail as possible, including steps to reproduce the issue.
- **Propose reasonable feature requests**: When suggesting new features, ensure they fit within the scope, style, and design of the project. Provide clear reasoning and use cases.
## 11. Documentation
- **Update the documentation**: If your change affects the functionality, please update the relevant documentation files to reflect this.
- **Automatic generation**: If you decide to add functionality through a new shell script, make sure to fill out all fields in `tab_data.toml` and run `cargo xtask docgen`.
## 12. License
- **Agree to the license**: By contributing to Linutil, you agree that your contributions will be licensed under the project's MIT license.
We appreciate your contributions and look forward to collaborating with you to make Linutil better!

32
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View file

@ -0,0 +1,32 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: 'bug'
assignees: ''
---
## Describe the bug
A clear and concise description of what the bug is.
## To Reproduce
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
## Expected behavior
A clear and concise description of what you expected to happen.
## Screenshots
If applicable, add screenshots to help explain your problem.
## Additional context
Add any other context about the problem here.
## Checklist
- [ ] I checked for duplicate issues.
- [ ] I checked already existing discussions.
- [ ] This issue is not included in the roadmap.
- [ ] This issue is present on both stable and development branches.

View file

@ -0,0 +1,24 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: 'enhancement'
assignees: ''
---
## Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
## Describe the solution you'd like
A clear and concise description of what you want to happen.
## Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.
## Additional context
Add any other context or screenshots about the feature request here.
## Checklist
- [ ] I checked for duplicate issues.
- [ ] I checked already existing discussions.
- [ ] This feature is not included in the roadmap.

36
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View file

@ -0,0 +1,36 @@
<!--
Read Contributing Guidelines before opening a PR.
https://github.com/ChrisTitusTech/linutil/blob/main/.github/CONTRIBUTING.md
-->
## Type of Change
- [ ] New feature
- [ ] Bug fix
- [ ] Documentation update
- [ ] Refactoring
- [ ] Hotfix
- [ ] Security patch
- [ ] UI/UX improvement
## Description
<!--[Provide a detailed explanation of the changes you have made. Include the reasons behind these changes and any relevant context. Link any related issues.]-->
## Testing
<!--[Detail the testing you have performed to ensure that these changes function as intended. Include information about any added tests.]-->
## Impact
<!--[Discuss the impact of your changes on the project. This might include effects on performance, new dependencies, or changes in behaviour.]-->
## Issues / other PRs related
<!--[What issue/discussion is related to this PR (if any)]-->
- Resolves #
## Additional Information
<!--[Any additional information that reviewers should be aware of.]-->
## Checklist
- [ ] My code adheres to the coding and style guidelines of the project.
- [ ] I have performed a self-review of my own code.
- [ ] I have commented my code, particularly in hard-to-understand areas.
- [ ] I have made corresponding changes to the documentation.
- [ ] My changes generate no errors/warnings/merge conflicts.

14
.github/SECURITY.md vendored Normal file
View file

@ -0,0 +1,14 @@
# Security Policy
## Supported Versions
It is recommended that you run the stable version as this is more tested and used by most. The dev branch is bleed-edge commits that are not well tested and aren't meant to be used in production environments
| Version | Supported |
| ------- | ------------------ |
| latest | :white_check_mark: |
| dev | :x: |
## Reporting a Vulnerability
I'd recommend making an Issue for reporting a bug. If you would like privately submit the bug you can email me at contact@christitus.com

17
.github/dependabot.yml vendored Normal file
View file

@ -0,0 +1,17 @@
version: 2
updates:
- package-ecosystem: "cargo"
directory: "/"
schedule:
interval: "weekly"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
ignore:
- dependency-name: "actions/stale"
versions: '>= 9'
- dependency-name: "actions/setup-python"
versions: '> 4'
- dependency-name: "crossterm"
versions: '> 0.27.0'

89
.github/mkdocs.yml vendored Normal file
View file

@ -0,0 +1,89 @@
site_name: Chris Titus LinUtil Official Documentation
repo_url: https://github.com/ChrisTitusTech/linutil
docs_dir: '../docs'
nav:
- Introduction: 'index.md'
- User Guide: 'userguide.md'
- Contributing:
- Contributing Guide: 'contributing.md'
- Roadmap: 'roadmap.md'
- Documentation:
- Known Issues: 'KnownIssues.md'
- FAQ: 'faq.md'
theme:
name: material
custom_dir: '../overrides'
features:
- navigation.tabs
- navigation.sections
- toc.integrate
- navigation.top
- search.suggest
- search.highlight
- content.tabs.link
- content.code.annotation
- content.code.copy
language: en
logo: assets/favicon.png
favicon: assets/favicon.png
palette:
# Palette toggle for automatic mode
- media: "(prefers-color-scheme)"
toggle:
icon: material/brightness-auto
name: Switch to light mode
# Palette toggle for light mode
- media: "(prefers-color-scheme: light)"
scheme: default
accent: blue
toggle:
icon: material/brightness-7
name: Switch to dark mode
# Palette toggle for dark mode
- media: "(prefers-color-scheme: dark)"
scheme: slate
primary: black
accent: blue
toggle:
icon: material/weather-night
name: Switch to light mode
markdown_extensions:
- admonition
- pymdownx.details
- pymdownx.superfences
- pymdownx.superfences:
custom_fences:
- name: mermaid
class: mermaid
format: !!python/name:pymdownx.superfences.fence_code_format
- abbr
- attr_list
- pymdownx.snippets
- md_in_html
- pymdownx.superfences
- pymdownx.tabbed:
alternate_style: true
- pymdownx.highlight:
anchor_linenums: true
line_spans: __span
pygments_lang_class: true
- pymdownx.inlinehilite
- def_list
- pymdownx.tasklist:
custom_checkbox: true
- toc:
permalink: true
plugins:
- search
- awesome-pages
- git-revision-date-localized
- minify:
minify_html: true
htmlmin_opts:
remove_comments: true
cache_safe: true

23
.github/release.yml vendored Normal file
View file

@ -0,0 +1,23 @@
changelog:
categories:
- title: '🚀 Features'
label: 'enhancement'
- title: '🐛 Bug Fixes'
label: 'bug'
- title: '⚙️ Refactoring'
label: 'refactor'
- title: '🧩 UI/UX'
label: 'UI/UX'
- title: '📚 Documentation'
label: 'documentation'
- title: '🔒 Security'
label: 'security'
- title: '🧰 GitHub Actions'
label: 'github_actions'
- title: '🦀 Rust'
label: 'rust'
- title: '📃 Scripting'
label: 'script'
exclude:
labels:
- 'skip-changelog'

51
.github/requirements.txt vendored Normal file
View file

@ -0,0 +1,51 @@
Babel==2.15.0
bracex==2.5
cairocffi==1.7.1
CairoSVG==2.7.1
certifi==2024.7.4
cffi==1.17.0
charset-normalizer==3.3.2
click==8.1.7
colorama==0.4.6
csscompressor==0.9.5
cssselect2==0.7.0
defusedxml==0.7.1
ghp-import==2.1.0
gitdb==4.0.11
GitPython==3.1.43
htmlmin2==0.1.13
idna==3.7
Jinja2==3.1.4
jsmin==3.0.1
Markdown==3.6
MarkupSafe==2.1.5
mergedeep==1.3.4
mkdocs==1.6.0
mkdocs-awesome-pages-plugin==2.9.3
mkdocs-get-deps==0.2.0
mkdocs-git-revision-date-localized-plugin==1.2.6
mkdocs-material==9.5.31
mkdocs-material-extensions==1.3.1
mkdocs-minify-plugin==0.8.0
natsort==8.4.0
packaging==24.1
paginate==0.5.6
pathspec==0.12.1
pillow==10.4.0
platformdirs==4.2.2
pycparser==2.22
Pygments==2.18.0
pymdown-extensions==10.9
python-dateutil==2.9.0.post0
pytz==2024.1
PyYAML==6.0.2
pyyaml_env_tag==0.1
regex==2024.7.24
requests==2.32.3
six==1.16.0
smmap==5.0.1
tinycss2==1.3.0
urllib3==2.2.2
watchdog==4.0.1
wcmatch==9.0
webencodings==0.5.1

45
.github/workflows/bashisms.yml vendored Normal file
View file

@ -0,0 +1,45 @@
name: Check for bashisms
on:
pull_request:
paths:
- core/tabs/**
merge_group:
workflow_dispatch:
jobs:
check-bashisms:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: git fetch origin ${{ github.base_ref }}
- name: Get a list of changed script files
id: get_sh_files
run: |
sh_files=$(git diff --name-only origin/${{ github.base_ref }} HEAD core/tabs | grep '\.sh$' || true)
if [ -n "$sh_files" ]; then
echo "$sh_files" > changed_files
echo "changed=1" >> $GITHUB_OUTPUT
else
echo "changed=0" >> $GITHUB_OUTPUT
fi
- name: Install devscripts
if: steps.get_sh_files.outputs.changed == 1
run: sudo apt-get update && sudo apt-get install devscripts
- name: Check for bashisms
if: steps.get_sh_files.outputs.changed == 1
run: |
echo "Running for:\n$(cat changed_files)\n"
for file in $(cat changed_files); do
if [[ -f "$file" ]]; then
checkbashisms "$file"
fi
done
- name: Remove the created file
if: steps.get_sh_files.outputs.changed == 1
run: rm changed_files

88
.github/workflows/linutil.yml vendored Normal file
View file

@ -0,0 +1,88 @@
name: LinUtil Release
on:
workflow_dispatch:
permissions:
contents: write
packages: write
env:
CARGO_TERM_COLOR: always
jobs:
linutil_build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install musl-tools
run: sudo apt-get update && sudo apt-get install musl-tools
- name: Cache Cargo registry
uses: actions/cache@v4
with:
path: ~/.cargo/registry
key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
restore-keys: ${{ runner.os }}-cargo-registry-
- name: Cache Cargo index
uses: actions/cache@v4
with:
path: ~/.cargo/git
key: ${{ runner.os }}-cargo-index-${{ hashFiles('**/Cargo.lock') }}
restore-keys: ${{ runner.os }}-cargo-index-
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
with:
targets: x86_64-unknown-linux-musl
- name: Install cross-rs for cross-compilation
run: cargo install cross
- name: Build x86_64 binary
run: cargo build --target-dir=build --release --verbose --target=x86_64-unknown-linux-musl --all-features
- name: Build aarch64 binary
run: cross build --target-dir=build --release --verbose --target=aarch64-unknown-linux-musl --all-features
- name: Move binaries to build directory
run: |
mv build/x86_64-unknown-linux-musl/release/linutil build/linutil
mv build/aarch64-unknown-linux-musl/release/linutil build/linutil-aarch64
- uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: Commit Linutil
file_pattern: "build/linutil build/linutil-aarch64"
add_options: '--force'
if: success()
- name: Extract Version
id: extract_version
run: |
version=$(date +"%Y.%m.%d")
echo "version=$version" >> $GITHUB_ENV
shell: bash
- name: Build linutil binary
run: cargo build --release
- name: Create and Upload Release
id: create_release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ env.version }}
name: Pre-Release ${{ env.version }}
body: |
Latest linutil binary release
append_body: true
generate_release_notes: true
files: |
./target/release/linutil
prerelease: true
env:
version: ${{ env.version }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

44
.github/workflows/rust.yml vendored Normal file
View file

@ -0,0 +1,44 @@
name: Rust Checks
on:
pull_request:
branches: ["main"]
paths:
- '**/*.rs'
- 'Cargo.toml'
- 'Cargo.lock'
env:
CARGO_TERM_COLOR: always
jobs:
lints:
name: Lints
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v4
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- name: Cache Cargo registry
uses: actions/cache@v4
with:
path: ~/.cargo/registry
key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
restore-keys: ${{ runner.os }}-cargo-registry-
- name: Cache Cargo index
uses: actions/cache@v4
with:
path: ~/.cargo/git
key: ${{ runner.os }}-cargo-index-${{ hashFiles('**/Cargo.lock') }}
restore-keys: ${{ runner.os }}-cargo-index-
- name: Run cargo clippy
run: cargo clippy -- -Dwarnings
- name: Run cargo fmt
run: cargo fmt --all --check

55
.github/workflows/shellcheck.yml vendored Normal file
View file

@ -0,0 +1,55 @@
name: ShellCheck
on:
pull_request:
paths:
- 'core/tabs/**/*.sh'
workflow_dispatch:
jobs:
shellcheck:
name: Shellcheck
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: git fetch origin ${{ github.base_ref }}
- name: Download, setup, and run ShellCheck
shell: bash {0}
run : |
SC_URL="https://github.com/koalaman/shellcheck/releases/download/v0.10.0/shellcheck-v0.10.0.linux.x86_64.tar.xz"
curl -fsSL "$SC_URL" | tar -Jx
chmod +x "./shellcheck-v0.10.0/shellcheck"
error=0
files_to_check=$(git diff --name-only origin/${{ github.base_ref }} HEAD core/tabs)
for file in $files_to_check; do
if [[ "$file" == *.sh ]] && [[ -f "$file" ]]; then
sc_output=$(./shellcheck-v0.10.0/shellcheck -fgcc -Serror "$file")
iter_safe_parsed_errors=$(echo -e "$sc_output" | sed -n 's/\(.\+\)\:\([0-9]\+\)\:\([0-9]\+\)\: \(.*\)/::error file=\1,line=\2,col=\3::\4/p' | sed 's/ /:space:/g')
for error in $iter_safe_parsed_errors; do
echo "$error" | sed 's/:space:/ /g'
error=1
done
tabs_detected=$(grep -nP '^\t+\S+' "$file")
# fast fail on the action runner would fail immediately if there weren't any tabs found
# this check makes sure that we don't continue if there's something really weird going on
if [ "$?" = "2" ]; then
echo "::error file=$file::There was a critical error while grepping $file, aborting"
exit 1
fi
iter_safe_parsed_tabs_detected=$(echo "$tabs_detected" | sed -n 's,\([0-9]\+\).*,::error file='"$file"'\,line=\1::Found tab indentations,p' | sed 's/ /:space:/g')
for error in $iter_safe_parsed_tabs_detected; do
echo "$error" | sed 's/:space:/ /g'
error=1
done
fi
done
exit $error

15
.github/workflows/typos.yml vendored Normal file
View file

@ -0,0 +1,15 @@
name: Check for typos
on:
[push, pull_request, workflow_dispatch]
jobs:
check-typos:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: git fetch origin ${{ github.base_ref }}
- name: Run spellcheck
uses: crate-ci/typos@v1.25.0

58
.github/workflows/xtask.yml vendored Normal file
View file

@ -0,0 +1,58 @@
name: XTasks
on:
pull_request:
paths:
- "xtask"
- "Cargo.toml"
- "Cargo.lock"
- ".cargo"
- "core/tabs"
- "docs"
push:
paths:
- "xtask"
- "Cargo.toml"
- "Cargo.lock"
- ".cargo"
- "core/tabs"
- "docs"
env:
CARGO_TERM_COLOR: always
jobs:
docgen:
name: DocGen
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v4
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- name: Cache Cargo registry
uses: actions/cache@v4
with:
path: ~/.cargo/registry
key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
restore-keys: ${{ runner.os }}-cargo-registry-
- name: Cache Cargo index
uses: actions/cache@v4
with:
path: ~/.cargo/git
key: ${{ runner.os }}-cargo-index-${{ hashFiles('**/Cargo.lock') }}
restore-keys: ${{ runner.os }}-cargo-index-
- name: Run cargo xtask docgen
run: cargo xtask docgen
- name: Check uncommitted documentation changes
run: |
git diff
git diff-files --quiet \
|| (echo "Run 'cargo xtask docgen' and push the changes" \
&& exit 1)

5
.gitignore vendored Normal file
View file

@ -0,0 +1,5 @@
/target
/build
rust/target
rust/build
/build/linutil

1458
Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

24
Cargo.toml Normal file
View file

@ -0,0 +1,24 @@
[workspace.package]
license = "MIT"
version = "24.9.28"
edition = "2021"
[workspace.dependencies]
ego-tree = "0.6.2"
[workspace]
members = ["tui", "core", "xtask"]
default-members = ["tui", "core"]
resolver = "2"
[patch.crates-io]
vt100 = { git = "https://github.com/ChrisTitusTech/vt100-rust" }
[profile.release]
opt-level = "z"
debug = false
lto = true
codegen-units = 1
panic = "abort"
strip = true
incremental = false

7
_typos.toml Normal file
View file

@ -0,0 +1,7 @@
[files]
extend-exclude = ["tui/cool_tips.txt"]
[default]
extend-ignore-identifiers-re = [
"ratatui",
]

20
core/Cargo.toml Normal file
View file

@ -0,0 +1,20 @@
[package]
name = "linutil_core"
description = "The backend of Linutil."
repository = "https://github.com/ChrisTitusTech/linutil/tree/main/core"
edition = "2021"
version.workspace = true
license.workspace = true
include = [
"src/*.rs",
"Cargo.toml",
"tabs/**",
]
[dependencies]
include_dir = "0.7.4"
temp-dir = "0.1.14"
serde = { version = "1.0.205", features = ["derive"], default-features = false }
toml = { version = "0.8.19", features = ["parse"], default-features = false }
which = "6.0.3"
ego-tree = { workspace = true }

272
core/src/inner.rs Normal file
View file

@ -0,0 +1,272 @@
use std::{
fs::File,
io::{BufRead, BufReader, Read},
os::unix::fs::PermissionsExt,
path::{Path, PathBuf},
rc::Rc,
};
use crate::{Command, ListNode, Tab};
use ego_tree::{NodeMut, Tree};
use include_dir::{include_dir, Dir};
use serde::Deserialize;
use temp_dir::TempDir;
const TAB_DATA: Dir = include_dir!("$CARGO_MANIFEST_DIR/tabs");
pub fn get_tabs(validate: bool) -> (TempDir, Vec<Tab>) {
let (temp_dir, tab_files) = TabList::get_tabs();
let tabs: Vec<_> = tab_files
.into_iter()
.map(|path| {
let directory = path.parent().unwrap().to_owned();
let data = std::fs::read_to_string(path).expect("Failed to read tab data");
let mut tab_data: TabEntry = toml::from_str(&data).expect("Failed to parse tab data");
if validate {
filter_entries(&mut tab_data.data);
}
(tab_data, directory)
})
.collect();
let tabs: Vec<Tab> = tabs
.into_iter()
.map(
|(
TabEntry {
name,
data,
multi_selectable,
},
directory,
)| {
let mut tree = Tree::new(Rc::new(ListNode {
name: "root".to_string(),
description: String::new(),
command: Command::None,
task_list: String::new(),
}));
let mut root = tree.root_mut();
create_directory(data, &mut root, &directory, validate);
Tab {
name,
tree,
multi_selectable,
}
},
)
.collect();
if tabs.is_empty() {
panic!("No tabs found");
}
(temp_dir, tabs)
}
#[derive(Deserialize)]
struct TabList {
directories: Vec<PathBuf>,
}
#[derive(Deserialize)]
struct TabEntry {
name: String,
data: Vec<Entry>,
#[serde(default = "default_multi_selectable")]
multi_selectable: bool,
}
fn default_multi_selectable() -> bool {
true
}
#[derive(Deserialize)]
struct Entry {
name: String,
#[allow(dead_code)]
#[serde(default)]
description: String,
#[serde(default)]
preconditions: Option<Vec<Precondition>>,
#[serde(flatten)]
entry_type: EntryType,
#[serde(default)]
task_list: String,
}
#[derive(Deserialize)]
enum EntryType {
#[serde(rename = "entries")]
Entries(Vec<Entry>),
#[serde(rename = "command")]
Command(String),
#[serde(rename = "script")]
Script(PathBuf),
}
impl Entry {
fn is_supported(&self) -> bool {
self.preconditions.as_deref().map_or(true, |preconditions| {
preconditions.iter().all(
|Precondition {
matches,
data,
values,
}| {
match data {
SystemDataType::Environment(var_name) => std::env::var(var_name)
.map_or(false, |var| values.contains(&var) == *matches),
SystemDataType::File(path) => {
std::fs::read_to_string(path).map_or(false, |data| {
values
.iter()
.any(|matching_value| data.contains(matching_value))
== *matches
})
}
SystemDataType::CommandExists => values
.iter()
.all(|command| which::which(command).is_ok() == *matches),
}
},
)
})
}
}
#[derive(Deserialize)]
struct Precondition {
// If true, the data must be contained within the list of values.
// Otherwise, the data must not be contained within the list of values
matches: bool,
data: SystemDataType,
values: Vec<String>,
}
#[derive(Deserialize)]
enum SystemDataType {
#[serde(rename = "environment")]
Environment(String),
#[serde(rename = "file")]
File(PathBuf),
#[serde(rename = "command_exists")]
CommandExists,
}
fn filter_entries(entries: &mut Vec<Entry>) {
entries.retain_mut(|entry| {
if !entry.is_supported() {
return false;
}
if let EntryType::Entries(entries) = &mut entry.entry_type {
filter_entries(entries);
!entries.is_empty()
} else {
true
}
});
}
fn create_directory(
data: Vec<Entry>,
node: &mut NodeMut<Rc<ListNode>>,
command_dir: &Path,
validate: bool,
) {
for entry in data {
match entry.entry_type {
EntryType::Entries(entries) => {
let mut node = node.append(Rc::new(ListNode {
name: entry.name,
description: entry.description,
command: Command::None,
task_list: String::new(),
}));
create_directory(entries, &mut node, command_dir, validate);
}
EntryType::Command(command) => {
node.append(Rc::new(ListNode {
name: entry.name,
description: entry.description,
command: Command::Raw(command),
task_list: String::new(),
}));
}
EntryType::Script(script) => {
let script = command_dir.join(script);
if !script.exists() {
panic!("Script {} does not exist", script.display());
}
if let Some((executable, args)) = get_shebang(&script, validate) {
node.append(Rc::new(ListNode {
name: entry.name,
description: entry.description,
command: Command::LocalFile {
executable,
args,
file: script,
},
task_list: entry.task_list,
}));
}
}
}
}
}
fn get_shebang(script_path: &Path, validate: bool) -> Option<(String, Vec<String>)> {
let default_executable = || Some(("/bin/sh".into(), vec!["-e".into()]));
let script = File::open(script_path).expect("Failed to open script file");
let mut reader = BufReader::new(script);
// Take the first 2 characters from the reader; check whether it's a shebang
let mut two_chars = [0; 2];
if reader.read_exact(&mut two_chars).is_err() || two_chars != *b"#!" {
return default_executable();
}
let first_line = reader.lines().next().unwrap().unwrap();
let mut parts = first_line.split_whitespace();
let Some(executable) = parts.next() else {
return default_executable();
};
let is_valid = !validate || is_executable(Path::new(executable));
is_valid.then(|| {
let mut args: Vec<String> = parts.map(ToString::to_string).collect();
args.push(script_path.to_string_lossy().to_string());
(executable.to_string(), args)
})
}
fn is_executable(path: &Path) -> bool {
path.metadata()
.map(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)
.unwrap_or(false)
}
impl TabList {
fn get_tabs() -> (TempDir, Vec<PathBuf>) {
let temp_dir = TempDir::new().unwrap();
TAB_DATA
.extract(&temp_dir)
.expect("Failed to extract the saved directory");
let tab_files = std::fs::read_to_string(temp_dir.path().join("tabs.toml"))
.expect("Failed to read tabs.toml");
let data: Self = toml::from_str(&tab_files).expect("Failed to parse tabs.toml");
let tab_paths = data
.directories
.iter()
.map(|path| temp_dir.path().join(path).join("tab_data.toml"))
.collect();
(temp_dir, tab_paths)
}
}

35
core/src/lib.rs Normal file
View file

@ -0,0 +1,35 @@
mod inner;
use std::rc::Rc;
use ego_tree::Tree;
use std::path::PathBuf;
pub use inner::get_tabs;
#[derive(Clone, Hash, Eq, PartialEq)]
pub enum Command {
Raw(String),
LocalFile {
executable: String,
args: Vec<String>,
// The file path is included within the arguments; don't pass this in addition
file: PathBuf,
},
None, // Directory
}
#[derive(Clone, Hash, Eq, PartialEq)]
pub struct Tab {
pub name: String,
pub tree: Tree<Rc<ListNode>>,
pub multi_selectable: bool,
}
#[derive(Clone, Hash, Eq, PartialEq)]
pub struct ListNode {
pub name: String,
pub description: String,
pub command: Command,
pub task_list: String,
}

View file

@ -0,0 +1,87 @@
#!/bin/sh -e
. ../common-script.sh
# Function to prompt the user for installation choice
choose_installation() {
clear
printf "%b\n" "${YELLOW}Choose what to install:${RC}"
printf "%b\n" "1. ${YELLOW}Docker${RC}"
printf "%b\n" "2. ${YELLOW}Docker Compose${RC}"
printf "%b\n" "3. ${YELLOW}Both${RC}"
printf "%b" "Enter your choice [1-3]: "
read -r CHOICE
case "$CHOICE" in
1) INSTALL_DOCKER=1; INSTALL_COMPOSE=0 ;;
2) INSTALL_DOCKER=0; INSTALL_COMPOSE=1 ;;
3) INSTALL_DOCKER=1; INSTALL_COMPOSE=1 ;;
*) printf "%b\n" "${RED}Invalid choice. Exiting.${RC}"; exit 1 ;;
esac
}
install_docker() {
printf "%b\n" "${YELLOW}Installing Docker...${RC}"
case "$PACKAGER" in
apt-get|nala)
curl -fsSL https://get.docker.com | sh
;;
zypper)
"$ESCALATION_TOOL" "$PACKAGER" --non-interactive install docker
"$ESCALATION_TOOL" systemctl enable docker
"$ESCALATION_TOOL" systemctl start docker
;;
pacman)
"$ESCALATION_TOOL" "$PACKAGER" -S --noconfirm docker
"$ESCALATION_TOOL" systemctl enable docker
"$ESCALATION_TOOL" systemctl start docker
;;
*)
printf "%b\n" "${RED}Unsupported package manager: ""$PACKAGER""${RC}"
exit 1
;;
esac
}
install_docker_compose() {
printf "%b\n" "${YELLOW}Installing Docker Compose...${RC}"
case "$PACKAGER" in
apt-get|nala)
"$ESCALATION_TOOL" "$PACKAGER" install -y docker-compose-plugin
;;
zypper)
"$ESCALATION_TOOL" "$PACKAGER" --non-interactive install docker-compose
;;
pacman)
"$ESCALATION_TOOL" "$PACKAGER" -S --needed --noconfirm docker-compose
;;
*)
printf "%b\n" "${RED}Unsupported package manager: ""$PACKAGER""${RC}"
exit 1
;;
esac
}
install_components() {
choose_installation
if [ "$INSTALL_DOCKER" -eq 1 ]; then
if ! command_exists docker; then
install_docker
else
printf "%b\n" "${GREEN}Docker is already installed.${RC}"
fi
fi
if [ "$INSTALL_COMPOSE" -eq 1 ]; then
if ! command_exists docker-compose || ! command_exists docker compose version; then
install_docker_compose
else
printf "%b\n" "${GREEN}Docker Compose is already installed.${RC}"
fi
fi
}
checkEnv
checkEscalationTool
install_components

View file

@ -0,0 +1,38 @@
#!/bin/sh -e
. ../common-script.sh
installFastfetch() {
if ! command_exists fastfetch; then
printf "%b\n" "${YELLOW}Installing Fastfetch...${RC}"
case "$PACKAGER" in
pacman)
"$ESCALATION_TOOL" "$PACKAGER" -S --needed --noconfirm fastfetch
;;
apt-get|nala)
curl -sSLo /tmp/fastfetch.deb https://github.com/fastfetch-cli/fastfetch/releases/latest/download/fastfetch-linux-amd64.deb
"$ESCALATION_TOOL" "$PACKAGER" install -y /tmp/fastfetch.deb
rm /tmp/fastfetch.deb
;;
*)
"$ESCALATION_TOOL" "$PACKAGER" install -y fastfetch
;;
esac
else
printf "%b\n" "${GREEN}Fastfetch is already installed.${RC}"
fi
}
setupFastfetchConfig() {
printf "%b\n" "${YELLOW}Copying Fastfetch config files...${RC}"
if [ -d "${HOME}/.config/fastfetch" ] && [ ! -d "${HOME}/.config/fastfetch-bak" ]; then
cp -r "${HOME}/.config/fastfetch" "${HOME}/.config/fastfetch-bak"
fi
mkdir -p "${HOME}/.config/fastfetch/"
curl -sSLo "${HOME}/.config/fastfetch/config.jsonc" https://raw.githubusercontent.com/ChrisTitusTech/mybash/main/config.jsonc
}
checkEnv
checkEscalationTool
installFastfetch
setupFastfetchConfig

View file

@ -0,0 +1,42 @@
#!/bin/sh -e
. ../common-script.sh
installGithubDesktop() {
if ! command_exists github-desktop; then
printf "%b\n" "${YELLOW}Installing Github Desktop...${RC}"
case "$PACKAGER" in
apt-get | nala)
curl -fsSL https://apt.packages.shiftkey.dev/gpg.key | gpg --dearmor | "$ESCALATION_TOOL" tee /usr/share/keyrings/shiftkey-packages.gpg >/dev/null
printf "%b\n" 'deb [arch=amd64 signed-by=/usr/share/keyrings/shiftkey-packages.gpg] https://apt.packages.shiftkey.dev/ubuntu/ any main\n' | "$ESCALATION_TOOL" tee /etc/apt/sources.list.d/shiftkey-packages.list >/dev/null
"$ESCALATION_TOOL" "$PACKAGER" update
"$ESCALATION_TOOL" "$PACKAGER" install -y github-desktop
;;
zypper)
"$ESCALATION_TOOL" rpm --import https://rpm.packages.shiftkey.dev/gpg.key
printf "%b\n" '[shiftkey-packages]\nname=GitHub Desktop\nbaseurl=https://rpm.packages.shiftkey.dev/rpm/\nenabled=1\ngpgcheck=1\nrepo_gpgcheck=1\ngpgkey=https://rpm.packages.shiftkey.dev/gpg.key\n' | "$ESCALATION_TOOL" tee /etc/zypp/repos.d/shiftkey-packages.repo >/dev/null
"$ESCALATION_TOOL" "$PACKAGER" refresh
"$ESCALATION_TOOL" "$PACKAGER" --non-interactive install github-desktop
;;
pacman)
"$AUR_HELPER" -S --needed --noconfirm github-desktop-bin
;;
dnf)
"$ESCALATION_TOOL" rpm --import https://rpm.packages.shiftkey.dev/gpg.key
printf "%b\n" '[shiftkey-packages]\nname=GitHub Desktop\nbaseurl=https://rpm.packages.shiftkey.dev/rpm/\nenabled=1\ngpgcheck=1\nrepo_gpgcheck=1\ngpgkey=https://rpm.packages.shiftkey.dev/gpg.key\n' | "$ESCALATION_TOOL" tee /etc/yum.repos.d/shiftkey-packages.repo >/dev/null
"$ESCALATION_TOOL" "$PACKAGER" install -y github-desktop
;;
*)
printf "%b\n" "${RED}Unsupported package manager: ""$PACKAGER""${RC}"
exit 1
;;
esac
else
printf "%b\n" "${GREEN}Github Desktop is already installed.${RC}"
fi
}
checkEnv
checkEscalationTool
checkAURHelper
installGithubDesktop

View file

@ -0,0 +1,75 @@
#!/bin/sh -e
. ../common-script.sh
# Used to detect the desktop environment, Only used for the If statement in the setup_flatpak function.
# Perhaps this should be moved to common-script.sh later on?
detect_de() {
if [ -n "$XDG_CURRENT_DESKTOP" ]; then
case "$XDG_CURRENT_DESKTOP" in
*GNOME*)
DE="GNOME"
;;
*KDE*)
DE="KDE"
;;
esac
fi
}
# Install Flatpak if not already installed.
setup_flatpak() {
if ! command_exists flatpak; then
printf "%b\n" "${YELLOW}Installing Flatpak...${RC}"
case "$PACKAGER" in
pacman)
"$ESCALATION_TOOL" "$PACKAGER" -S --needed --noconfirm flatpak
;;
*)
"$ESCALATION_TOOL" "$PACKAGER" install -y flatpak
;;
esac
printf "%b\n" "Adding Flathub remote..."
"$ESCALATION_TOOL" flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
else
if command_exists flatpak; then
if ! flatpak remotes | grep -q "flathub"; then
printf "%b" "${YELLOW}Detected Flatpak package manager but Flathub remote is not added. Would you like to add it? (y/N): ${RC}"
read -r add_remote
case "$add_remote" in
[Yy]*)
printf "%b\n" "Adding Flathub remote..."
"$ESCALATION_TOOL" flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
;;
esac
else
# Needed mostly for systems without a polkit agent running (Error: updating: Unable to connect to system bus)
printf "%b\n" "${GREEN}Flathub already setup. You can quit.${RC}"
fi
fi
fi
if [ "$PACKAGER" = "apt-get" ] || [ "$PACKAGER" = "nala" ]; then
detect_de
# Only used for Ubuntu GNOME. Ubuntu GNOME doesnt allow flathub to be added as a remote to their store.
# So in case the user wants to use a GUI siftware manager they can setup it here
if [ "$DE" = "GNOME" ]; then
printf "%b" "${YELLOW}Detected GNOME desktop environment. Would you like to install GNOME Software plugin for Flatpak? (y/N): ${RC}"
read -r install_gnome
if [ "$install_gnome" = "y" ] || [ "$install_gnome" = "Y" ]; then
"$ESCALATION_TOOL" "$PACKAGER" install -y gnome-software-plugin-flatpak
fi
# Useful for Debian KDE spin as well
elif [ "$DE" = "KDE" ]; then
printf "%b" "${YELLOW}Detected KDE desktop environment. Would you like to install KDE Plasma Discover backend for Flatpak? (y/N): ${RC}"
read -r install_kde
if [ "$install_kde" = "y" ] || [ "$install_kde" = "Y" ]; then
"$ESCALATION_TOOL" "$PACKAGER" install -y plasma-discover-backend-flatpak
fi
fi
fi
}
checkEnv
checkEscalationTool
setup_flatpak

View file

@ -0,0 +1,38 @@
name = "Applications Setup"
multi_selectable = false
[[data]]
name = "Fastfetch"
description = "Fastfetch is a neofetch-like tool for fetching system information and displaying it prettily.\nIt is written mainly in C, with performance and customizability in mind.\nThis command installs fastfetch and configures from CTT's mybash repository.\nhttps://github.com/ChrisTitusTech/mybash"
script = "fastfetch-setup.sh"
task_list = "I"
[[data]]
name = "Flatpak / Flathub"
description = "Flatpak is a universal application sandbox for Linux that uses isolated packages from Flathub to prevent conflicts and system alterations, while alleviating dependency concerns.\nThis command installs Flatpak and adds the Flathub repository"
script = "setup-flatpak.sh"
task_list = "I"
[[data]]
name = "github-desktop"
description = "GitHub Desktop is a free Git client that allows you to manage your GitHub repositories on your desktop."
script = "githubdesktop-setup.sh"
task_list = "I"
[[data]]
name = "xmrig"
description = "xmrig is a CPU miner for the Monero cryptocurrency."
script = "xmrig.sh"
task_list = "I"
[[data]]
name = "yazi"
description = "yazi is a terminal file manager with a minimal UI and a focus on performance."
script = "yazi.sh"
task_list = "I"
[[data]]
name = "ytgo"
description = "ytgo is a command-line tool for searching and watching YouTube videos from the terminal."
script = "ytgo.sh"
task_list = "I"

View file

@ -0,0 +1,185 @@
#!/bin/sh -e
# ANSI color codes
RED='\033[0;31m'
CYAN='\033[0;36m'
YELLOW='\033[0;33m'
LIGHT_GREEN='\033[0;92m'
BOLD='\033[1m'
NC='\033[0m' # No Color
echo_error() {
printf "${BOLD}${RED}ERROR: ${NC}${RED}%s${NC}\n" "$1" >&2
}
echo_info() {
printf "${BOLD}${CYAN}INFO: ${NC}${CYAN}%s${NC}\n" "$1"
}
echo_warning() {
printf "${BOLD}${YELLOW}WARNING: ${NC}${YELLOW}%s${NC}\n" "$1"
}
echo_note() {
printf "${BOLD}${LIGHT_GREEN}NOTE: ${NC}${LIGHT_GREEN}%s${NC}\n" "$1"
}
# Check if the user is root and set sudo variable if necessary
check_root() {
if [ "$(id -u)" -ne 0 ]; then
if command_exists sudo; then
echo_info "User is not root. Using sudo for privileged operations."
_sudo="sudo"
else
echo_error "No sudo found and you're not root! Can't install packages."
return 1
fi
else
echo_info "Root access confirmed."
_sudo=""
fi
}
# < Distribution detection and installation >
get_packager() {
if [ -e /etc/os-release ]; then
echo_info "Detecting distribution..."
. /etc/os-release
# < Convert $ID and $ID_LIKE to lowercase >
ID=$(printf "%s" "$ID" | tr '[:upper:]' '[:lower:]')
ID_LIKE=$(printf "%s" "$ID_LIKE" | tr '[:upper:]' '[:lower:]')
case "$ID" in
ubuntu | pop) _install() {
$_sudo apt-get install "$@" --assume-yes
} ;;
debian) _install() {
$_sudo apt-get install "$@" --assume-yes
} ;;
fedora) _install() {
$_sudo dnf install "$@" -y
} ;;
alpine) _install() {
$_sudo apk add "$@"
} ;;
arch | manjaro | garuda | endeavour) _install() {
$_sudo pacman -S "$@" --noconfirm
} ;;
opensuse*) _install() { $_sudo zypper in "$@" -y; } ;;
*)
if [ "${ID_LIKE#*debian}" != "$ID_LIKE" ]; then
_install() { $_sudo apt-get install "$@" --assume-yes; }
elif [ "${ID_LIKE#*ubuntu}" != "$ID_LIKE" ]; then
_install() { $_sudo apt-get install "$@" --assume-yes; }
elif [ "${ID_LIKE#*arch}" != "$ID_LIKE" ]; then
_install() { $_sudo pacman -S "$@" --noconfirm; }
elif [ "${ID_LIKE#*fedora}" != "$ID_LIKE" ]; then
_install() { $_sudo dnf install "$@" -y; }
elif [ "${ID_LIKE#*suse}" != "$ID_LIKE" ]; then
_install() { $_sudo zypper in "$@" -y; }
else
echo_error "Unsupported distribution: $ID"
exit 1
fi
;;
esac
else
echo_error "Unable to detect distribution. /etc/os-release not found."
exit 1
fi
}
# Check if a command exists
command_exists() {
command -v "$@" >/dev/null 2>&1
}
# Install dependencies
_dependencies() {
tools="git cmake make"
packages="libuv1-dev libssl-dev libhwloc-dev"
for tool in $tools; do
if command_exists "$tool"; then
echo_note "$tool is already installed"
else
echo_info "Installing $tool.."
_install "$tool" || echo_error "Failed to install $tool"
fi
done
for package in $packages; do
echo_info "Installing $package"
_install "$package" || echo_error "Failed to install $package"
done
echo_note "Dependency check completed!"
}
# Clone the repository and prepare build directory
_git() {
xmrig_dir="$HOME/.bin/xmrig"
if [ -d "$xmrig_dir" ]; then
echo_warning "$xmrig_dir already exists. Skipping clone."
else
echo_info "Cloning xmrig repository to $xmrig_dir"
mkdir -p "$HOME/.bin"
if ! git clone --depth=1 https://github.com/xmrig/xmrig.git "$xmrig_dir"; then
echo_error "Failed to clone xmrig repository."
return 1
fi
fi
build_dir="$xmrig_dir/build"
mkdir -p "$build_dir" || {
echo_error "Failed to create build directory: $build_dir"
return 1
}
cd "$build_dir" || {
echo_error "Failed to navigate to build directory: $build_dir"
return 1
}
}
# Initialize and build the application
_appinit() {
echo_info "Running cmake .."
if ! cmake ..; then
echo_error "CMake failed."
return 1
fi
echo_info "Running make (this could take a while)"
if ! make; then
echo_error "Make failed."
return 1
fi
$_sudo ln -s ./xmrig /usr/bin/xmrig || "Link of application failed hard! Is not accessible at /usr/bin/xmrig"
}
# Main function
main() {
if ! check_root; then
echo_error "Root check failed. Exiting."
return 1
fi
if ! get_packager; then
echo_error "Failed to detect distribution or set packager."
return 1
fi
_dependencies || return 1
if _git; then
_appinit || echo_error "Build initialization failed."
else
echo_error "Failed during Git operations."
fi
}
main

View file

@ -0,0 +1,135 @@
#!/bin/sh -e
# ─< ANSI color codes >───────────────────────────────────────────────────────────────────
RED='\033[0;31m'
CYAN='\033[0;36m'
YELLOW='\033[0;33m'
LIGHT_GREEN='\033[0;92m'
BOLD='\033[1m'
NC='\033[0m' # No Color
echo_error() {
printf "${BOLD}${RED}ERROR: ${NC}${RED}%s${NC}\n" "$1" >&2
}
echo_info() {
printf "${BOLD}${CYAN}INFO: ${NC}${CYAN}%s${NC}\n" "$1"
}
echo_warning() {
printf "${BOLD}${YELLOW}WARNING: ${NC}${YELLOW}%s${NC}\n" "$1"
}
echo_note() {
printf "${BOLD}${LIGHT_GREEN}NOTE: ${NC}${LIGHT_GREEN}%s${NC}\n" "$1"
}
# ─< Check if the given command exists silently >─────────────────────────────────────────
command_exists() {
command -v "$@" >/dev/null 2>&1
}
# ─< Check if the user is root and set sudo variable if necessary >───────────────────────
check_root() {
if [ "$(id -u)" -ne 0 ]; then
if command_exists sudo; then
echo_info "User is not root. Using sudo for privileged operations."
_sudo="sudo"
else
echo_error "No sudo found and you're not root! Can't install packages."
return 1
fi
else
echo_info "Root access confirmed."
_sudo=""
fi
}
i_cargo() {
# if ! command_exists make || ! command_exists gcc; then
# echo_error "The script might run into issues, because of make and gcc not being installed. Please install it, and run the script again, if it fails!"
# fi
if command_exists cargo; then
echo_info "Installing yazi through cargo"
cargo install --locked yazi-fm yazi-cli
elif command_exists curl; then
echo_note "no cargo found, using curl to install rustup"
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
rustup update
echo_info "Installing yazi through cargo"
cargo install --locked yazi-fm yazi-cli
else
echo_warning "neither cargo, nor curl were found. Cannot continue!"
fi
c_yazi
}
i_arch() {
$_sudo pacman -S yazi --noconfirm
c_yazi
}
i_opensuse() {
$_sudo zypper install yazi
c_yazi
}
c_yazi() {
if [ -e "$HOME/.config/yazi/package.toml" ]; then
if command_exists ya; then
ya pack -i
fi
else
echo_warning "There was no yazi config found.. "
fi
}
# ─< Distribution detection and installation >────────────────────────────────────────
get_packager() {
if [ -e /etc/os-release ]; then
echo_info "Detecting distribution..."
. /etc/os-release
# ─< Convert $ID and $ID_LIKE to lowercase >──────────────────────────────────────────────
ID=$(printf "%s" "$ID" | tr '[:upper:]' '[:lower:]')
ID_LIKE=$(printf "%s" "$ID_LIKE" | tr '[:upper:]' '[:lower:]')
case "$ID" in
ubuntu | pop) i_cargo ;;
debian) i_cargo ;;
fedora) i_cargo ;;
alpine) i_cargo ;;
arch | manjaro | garuda | endeavour) i_arch ;;
opensuse*) i_opensuse ;;
*)
if [ "${ID_LIKE#*debian}" != "$ID_LIKE" ]; then
i_cargo
elif [ "${ID_LIKE#*ubuntu}" != "$ID_LIKE" ]; then
i_cargo
elif [ "${ID_LIKE#*arch}" != "$ID_LIKE" ]; then
i_arch
elif [ "${ID_LIKE#*fedora}" != "$ID_LIKE" ]; then
i_cargo
elif [ "${ID_LIKE#*suse}" != "$ID_LIKE" ]; then
i_opensuse
else
echo_error "Unsupported distribution: $ID"
exit 1
fi
;;
esac
else
echo_error "Unable to detect distribution. /etc/os-release not found."
exit 1
fi
}
main() {
if check_root; then
get_packager
fi
}
main

View file

@ -0,0 +1,153 @@
#!/bin/sh -e
# ╭───────────────╮
# │ env functions │
# ╰───────────────╯
# ───────────────────────────────────< ANSI color codes >───────────────────────────────────
RED='\033[0;31m'
CYAN='\033[0;36m'
YELLOW='\033[0;33m'
LIGHT_GREEN='\033[0;92m'
BOLD='\033[1m'
NC='\033[0m' # No Color
echo_error() {
printf "${BOLD}${RED}ERROR: ${NC}${RED}%s${NC}\n" "$1" >&2
}
echo_info() {
printf "${BOLD}${CYAN}INFO: ${NC}${CYAN}%s${NC}\n" "$1"
}
echo_warning() {
printf "${BOLD}${YELLOW}WARNING: ${NC}${YELLOW}%s${NC}\n" "$1"
}
echo_note() {
printf "${BOLD}${LIGHT_GREEN}NOTE: ${NC}${LIGHT_GREEN}%s${NC}\n" "$1"
}
command_exists() {
command -v "$@" >/dev/null 2>&1
}
# ─────────────< Check if the user is root and set sudo variable if necessary >─────────────
check_root() {
if [ "$(id -u)" -ne 0 ]; then
if command_exists sudo; then
echo_info "User is not root. Using sudo for privileged operations."
_sudo="sudo"
else
echo_error "No sudo found and you're not root! Can't install packages."
return 1
fi
else
echo_info "Root access confirmed."
_sudo=""
fi
}
# ──────────────────────< Check if the given command exists silently >──────────────────────
command_exists() {
command -v "$@" >/dev/null 2>&1
}
# ╭────────────────────────────────────╮
# │ insert your scripts/functions here │
# ╰────────────────────────────────────╯
# ─< Distribution detection and installation >────────────────────────────────────────
get_packager() {
if [ -e /etc/os-release ]; then
echo_info "Detecting distribution..."
. /etc/os-release
# ─< Convert $ID and $ID_LIKE to lowercase >──────────────────────────────────────────────
ID=$(printf "%s" "$ID" | tr '[:upper:]' '[:lower:]')
ID_LIKE=$(printf "%s" "$ID_LIKE" | tr '[:upper:]' '[:lower:]')
case "$ID" in
ubuntu | pop) _install() {
$_sudo apt-get install --assume-yes "$@"
} ;;
debian) _install() {
$_sudo apt-get install --assume-yes "$@"
} ;;
fedora) _install() {
$_sudo dnf install -y "$@"
} ;;
alpine) inst_alpine ;;
arch | manjaro | garuda | endeavour) _install() {
$_sudo pacman -S --noconfirm "$@"
} ;;
opensuse*) inst_opensuse ;;
*)
if [ "${ID_LIKE#*debian}" != "$ID_LIKE" ]; then
_install() {
$_sudo apt-get install --assume-yes "$@"
}
elif [ "${ID_LIKE#*ubuntu}" != "$ID_LIKE" ]; then
_install() {
$_sudo apt-get install --assume-yes "$@"
}
elif [ "${ID_LIKE#*arch}" != "$ID_LIKE" ]; then
_install() {
$_sudo pacman -S --noconfirm "$@"
}
elif [ "${ID_LIKE#*fedora}" != "$ID_LIKE" ]; then
_install() {
$_sudo dnf install -y "$@"
}
elif [ "${ID_LIKE#*suse}" != "$ID_LIKE" ]; then
inst_opensuse
else
echo_error "Unsupported distribution: $ID"
exit 1
fi
;;
esac
else
echo_error "Unable to detect distribution. /etc/os-release not found."
exit 1
fi
}
_dependencies() {
get_packager
_deps="golang git mpv"
for dependency in $_deps; do
if ! command_exists "$dependency"; then
echo_info "Installing $dependency"
_install "$dependency" || echo_error "$dependency could not be installed!"
else
echo_note "$dependency - was already installed."
fi
done
}
_clone() {
tmpdir="$(mktemp --dir)"
repo="https://git.k4li.de/pika/ytgo.git"
cd "$tmpdir" || echo_error "$tmpdir is not a valid directory!"
git clone --depth=1 "$repo"
cd ytgo || echo_error "$tmpdir/ytgo is not a valid directory!"
}
_build() {
$_sudo make install
}
# ───────────────────────────────< main function to execute >───────────────────────────────
main() {
if check_root; then
_dependencies || echo_error "dependency function failed hard!"
_clone || echo_error "clone function failed hard!"
_build || echo_error "build function failed hard!"
else
echo_error "Something went terribly wrong!"
fi
}
main

135
core/tabs/common-script.sh Normal file
View file

@ -0,0 +1,135 @@
#!/bin/sh -e
# shellcheck disable=SC2034
RC='\033[0m'
RED='\033[31m'
YELLOW='\033[33m'
CYAN='\033[36m'
GREEN='\033[32m'
command_exists() {
command -v "$1" >/dev/null 2>&1
}
checkAURHelper() {
## Check & Install AUR helper
if [ "$PACKAGER" = "pacman" ]; then
if [ -z "$AUR_HELPER_CHECKED" ]; then
AUR_HELPERS="yay paru"
for helper in ${AUR_HELPERS}; do
if command_exists "${helper}"; then
AUR_HELPER=${helper}
printf "%b\n" "${CYAN}Using ${helper} as AUR helper${RC}"
AUR_HELPER_CHECKED=true
return 0
fi
done
printf "%b\n" "${YELLOW}Installing yay as AUR helper...${RC}"
"$ESCALATION_TOOL" "$PACKAGER" -S --needed --noconfirm base-devel git
cd /opt && "$ESCALATION_TOOL" git clone https://aur.archlinux.org/yay-bin.git && "$ESCALATION_TOOL" chown -R "$USER":"$USER" ./yay-bin
cd yay-bin && makepkg --noconfirm -si
if command_exists yay; then
AUR_HELPER="yay"
AUR_HELPER_CHECKED=true
else
printf "%b\n" "${RED}Failed to install AUR helper.${RC}"
exit 1
fi
fi
fi
}
checkEscalationTool() {
## Check for escalation tools.
if [ -z "$ESCALATION_TOOL_CHECKED" ]; then
ESCALATION_TOOLS='sudo doas'
for tool in ${ESCALATION_TOOLS}; do
if command_exists "${tool}"; then
ESCALATION_TOOL=${tool}
printf "%b\n" "${CYAN}Using ${tool} for privilege escalation${RC}"
ESCALATION_TOOL_CHECKED=true
return 0
fi
done
printf "%b\n" "${RED}Can't find a supported escalation tool${RC}"
exit 1
fi
}
checkCommandRequirements() {
## Check for requirements.
REQUIREMENTS=$1
for req in ${REQUIREMENTS}; do
if ! command_exists "${req}"; then
printf "%b\n" "${RED}To run me, you need: ${REQUIREMENTS}${RC}"
exit 1
fi
done
}
checkPackageManager() {
## Check Package Manager
PACKAGEMANAGER=$1
for pgm in ${PACKAGEMANAGER}; do
if command_exists "${pgm}"; then
PACKAGER=${pgm}
printf "%b\n" "${CYAN}Using ${pgm} as package manager${RC}"
break
fi
done
if [ -z "$PACKAGER" ]; then
printf "%b\n" "${RED}Can't find a supported package manager${RC}"
exit 1
fi
}
checkSuperUser() {
## Check SuperUser Group
SUPERUSERGROUP='wheel sudo root'
for sug in ${SUPERUSERGROUP}; do
if groups | grep -q "${sug}"; then
SUGROUP=${sug}
printf "%b\n" "${CYAN}Super user group ${SUGROUP}${RC}"
break
fi
done
## Check if member of the sudo group.
if ! groups | grep -q "${SUGROUP}"; then
printf "%b\n" "${RED}You need to be a member of the sudo group to run me!${RC}"
exit 1
fi
}
checkCurrentDirectoryWritable() {
## Check if the current directory is writable.
GITPATH="$(dirname "$(realpath "$0")")"
if [ ! -w "$GITPATH" ]; then
printf "%b\n" "${RED}Can't write to $GITPATH${RC}"
exit 1
fi
}
checkDistro() {
DTYPE="unknown" # Default to unknown
# Use /etc/os-release for modern distro identification
if [ -f /etc/os-release ]; then
. /etc/os-release
DTYPE=$ID
fi
}
checkEnv() {
checkEscalationTool
checkCommandRequirements "curl groups $ESCALATION_TOOL"
checkPackageManager 'nala apt-get dnf pacman zypper'
checkCurrentDirectoryWritable
checkSuperUser
checkDistro
checkAURHelper
}

View file

@ -0,0 +1,26 @@
#!/bin/sh -e
. ../../common-script.sh
installDepend() {
case "$PACKAGER" in
pacman)
if ! command_exists paru; then
printf "%b\n" "${YELLOW}Installing paru as AUR helper...${RC}"
"$ESCALATION_TOOL" "$PACKAGER" -S --needed --noconfirm base-devel git
cd /opt && "$ESCALATION_TOOL" git clone https://aur.archlinux.org/paru.git && "$ESCALATION_TOOL" chown -R "$USER": ./paru
cd paru && makepkg --noconfirm -si
printf "%b\n" "${GREEN}Paru installed${RC}"
else
printf "%b\n" "${GREEN}Paru already installed${RC}"
fi
;;
*)
printf "%b\n" "${RED}Unsupported package manager: ""$PACKAGER""${RC}"
;;
esac
}
checkEnv
checkEscalationTool
installDepend

View file

@ -0,0 +1,673 @@
#!/bin/bash
# Redirect stdout and stderr to archsetup.txt and still output to console
exec > >(tee -i archsetup.txt)
exec 2>&1
echo -ne "
-------------------------------------------------------------------------
█████╗ ██████╗ ██████╗██╗ ██╗████████╗██╗████████╗██╗ ██╗███████╗
██╔══██╗██╔══██╗██╔════╝██║ ██║╚══██╔══╝██║╚══██╔══╝██║ ██║██╔════╝
███████║██████╔╝██║ ███████║ ██║ ██║ ██║ ██║ ██║███████╗
██╔══██║██╔══██╗██║ ██╔══██║ ██║ ██║ ██║ ██║ ██║╚════██║
██║ ██║██║ ██║╚██████╗██║ ██║ ██║ ██║ ██║ ╚██████╔╝███████║
╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝
-------------------------------------------------------------------------
Automated Arch Linux Installer
-------------------------------------------------------------------------
Verifying Arch Linux ISO is Booted
"
if [ ! -f /usr/bin/pacstrap ]; then
echo "This script must be run from an Arch Linux ISO environment."
exit 1
fi
root_check() {
if [[ "$(id -u)" != "0" ]]; then
echo -ne "ERROR! This script must be run under the 'root' user!\n"
exit 0
fi
}
docker_check() {
if awk -F/ '$2 == "docker"' /proc/self/cgroup | read -r; then
echo -ne "ERROR! Docker container is not supported (at the moment)\n"
exit 0
elif [[ -f /.dockerenv ]]; then
echo -ne "ERROR! Docker container is not supported (at the moment)\n"
exit 0
fi
}
arch_check() {
if [[ ! -e /etc/arch-release ]]; then
echo -ne "ERROR! This script must be run in Arch Linux!\n"
exit 0
fi
}
pacman_check() {
if [[ -f /var/lib/pacman/db.lck ]]; then
echo "ERROR! Pacman is blocked."
echo -ne "If not running remove /var/lib/pacman/db.lck.\n"
exit 0
fi
}
background_checks() {
root_check
arch_check
pacman_check
docker_check
}
select_option() {
local options=("$@")
local num_options=${#options[@]}
local selected=0
local last_selected=-1
while true; do
# Move cursor up to the start of the menu
if [ $last_selected -ne -1 ]; then
echo -ne "\033[${num_options}A"
fi
if [ $last_selected -eq -1 ]; then
echo "Please select an option using the arrow keys and Enter:"
fi
for i in "${!options[@]}"; do
if [ "$i" -eq $selected ]; then
echo "> ${options[$i]}"
else
echo " ${options[$i]}"
fi
done
last_selected=$selected
# Read user input
read -rsn1 key
case $key in
$'\x1b') # ESC sequence
read -rsn2 -t 0.1 key
case $key in
'[A') # Up arrow
((selected--))
if [ $selected -lt 0 ]; then
selected=$((num_options - 1))
fi
;;
'[B') # Down arrow
((selected++))
if [ $selected -ge $num_options ]; then
selected=0
fi
;;
esac
;;
'') # Enter key
break
;;
esac
done
return $selected
}
# @description Displays ArchTitus logo
# @noargs
logo () {
# This will be shown on every set as user is progressing
echo -ne "
-------------------------------------------------------------------------
█████╗ ██████╗ ██████╗██╗ ██╗████████╗██╗████████╗██╗ ██╗███████╗
██╔══██╗██╔══██╗██╔════╝██║ ██║╚══██╔══╝██║╚══██╔══╝██║ ██║██╔════╝
███████║██████╔╝██║ ███████║ ██║ ██║ ██║ ██║ ██║███████╗
██╔══██║██╔══██╗██║ ██╔══██║ ██║ ██║ ██║ ██║ ██║╚════██║
██║ ██║██║ ██║╚██████╗██║ ██║ ██║ ██║ ██║ ╚██████╔╝███████║
╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝
------------------------------------------------------------------------
Please select presetup settings for your system
------------------------------------------------------------------------
"
}
# @description This function will handle file systems. At this movement we are handling only
# btrfs and ext4. Others will be added in future.
filesystem () {
echo -ne "
Please Select your file system for both boot and root
"
options=("btrfs" "ext4" "luks" "exit")
select_option "${options[@]}"
case $? in
0) export FS=btrfs;;
1) export FS=ext4;;
2)
set_password "LUKS_PASSWORD"
export FS=luks
;;
3) exit ;;
*) echo "Wrong option please select again"; filesystem;;
esac
}
# @description Detects and sets timezone.
timezone () {
# Added this from arch wiki https://wiki.archlinux.org/title/System_time
time_zone="$(curl --fail https://ipapi.co/timezone)"
echo -ne "
System detected your timezone to be '$time_zone' \n"
echo -ne "Is this correct?
"
options=("Yes" "No")
select_option "${options[@]}"
case ${options[$?]} in
y|Y|yes|Yes|YES)
echo "${time_zone} set as timezone"
export TIMEZONE=$time_zone;;
n|N|no|NO|No)
echo "Please enter your desired timezone e.g. Europe/London :"
read -r new_timezone
echo "${new_timezone} set as timezone"
export TIMEZONE=$new_timezone;;
*) echo "Wrong option. Try again";timezone;;
esac
}
# @description Set user's keyboard mapping.
keymap () {
echo -ne "
Please select key board layout from this list"
# These are default key maps as presented in official arch repo archinstall
options=(us by ca cf cz de dk es et fa fi fr gr hu il it lt lv mk nl no pl ro ru se sg ua uk)
select_option "${options[@]}"
keymap=${options[$?]}
echo -ne "Your key boards layout: ${keymap} \n"
export KEYMAP=$keymap
}
# @description Choose whether drive is SSD or not.
drivessd () {
echo -ne "
Is this an ssd? yes/no:
"
options=("Yes" "No")
select_option "${options[@]}"
case ${options[$?]} in
y|Y|yes|Yes|YES)
export MOUNT_OPTIONS="noatime,compress=zstd,ssd,commit=120";;
n|N|no|NO|No)
export MOUNT_OPTIONS="noatime,compress=zstd,commit=120";;
*) echo "Wrong option. Try again";drivessd;;
esac
}
# @description Disk selection for drive to be used with installation.
diskpart () {
echo -ne "
------------------------------------------------------------------------
THIS WILL FORMAT AND DELETE ALL DATA ON THE DISK
Please make sure you know what you are doing because
after formatting your disk there is no way to get data back
*****BACKUP YOUR DATA BEFORE CONTINUING*****
***I AM NOT RESPONSIBLE FOR ANY DATA LOSS***
------------------------------------------------------------------------
"
PS3='
Select the disk to install on: '
options=($(lsblk -n --output TYPE,KNAME,SIZE | awk '$1=="disk"{print "/dev/"$2"|"$3}'))
select_option "${options[@]}"
disk=${options[$?]%|*}
echo -e "\n${disk%|*} selected \n"
export DISK=${disk%|*}
drivessd
}
# @description Gather username and password to be used for installation.
userinfo () {
# Loop through user input until the user gives a valid username
while true
do
read -r -p "Please enter username: " username
if [[ "${username,,}" =~ ^[a-z_]([a-z0-9_-]{0,31}|[a-z0-9_-]{0,30}\$)$ ]]
then
break
fi
echo "Incorrect username."
done
export USERNAME=$username
while true
do
read -rs -p "Please enter password: " PASSWORD1
echo -ne "\n"
read -rs -p "Please re-enter password: " PASSWORD2
echo -ne "\n"
if [[ "$PASSWORD1" == "$PASSWORD2" ]]; then
break
else
echo -ne "ERROR! Passwords do not match. \n"
fi
done
export PASSWORD=$PASSWORD1
# Loop through user input until the user gives a valid hostname, but allow the user to force save
while true
do
read -r -p "Please name your machine: " name_of_machine
# hostname regex (!!couldn't find spec for computer name!!)
if [[ "${name_of_machine,,}" =~ ^[a-z][a-z0-9_.-]{0,62}[a-z0-9]$ ]]
then
break
fi
# if validation fails allow the user to force saving of the hostname
read -r -p "Hostname doesn't seem correct. Do you still want to save it? (y/n)" force
if [[ "${force,,}" = "y" ]]
then
break
fi
done
export NAME_OF_MACHINE=$name_of_machine
}
# Starting functions
background_checks
clear
logo
userinfo
clear
logo
diskpart
clear
logo
filesystem
clear
logo
timezone
clear
logo
keymap
echo "Setting up mirrors for optimal download"
iso=$(curl -4 ifconfig.co/country-iso)
timedatectl set-ntp true
pacman -Sy
pacman -S --noconfirm archlinux-keyring #update keyrings to latest to prevent packages failing to install
pacman -S --noconfirm --needed pacman-contrib terminus-font
setfont ter-v18b
sed -i 's/^#ParallelDownloads/ParallelDownloads/' /etc/pacman.conf
pacman -S --noconfirm --needed reflector rsync grub
cp /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.backup
echo -ne "
-------------------------------------------------------------------------
Setting up $iso mirrors for faster downloads
-------------------------------------------------------------------------
"
reflector -a 48 -c "$iso" -f 5 -l 20 --sort rate --save /etc/pacman.d/mirrorlist
if [ ! -d "/mnt" ]; then
mkdir /mnt
fi
echo -ne "
-------------------------------------------------------------------------
Installing Prerequisites
-------------------------------------------------------------------------
"
pacman -S --noconfirm --needed gptfdisk btrfs-progs glibc
echo -ne "
-------------------------------------------------------------------------
Formatting Disk
-------------------------------------------------------------------------
"
umount -A --recursive /mnt # make sure everything is unmounted before we start
# disk prep
sgdisk -Z "${DISK}" # zap all on disk
sgdisk -a 2048 -o "${DISK}" # new gpt disk 2048 alignment
# create partitions
sgdisk -n 1::+1M --typecode=1:ef02 --change-name=1:'BIOSBOOT' "${DISK}" # partition 1 (BIOS Boot Partition)
sgdisk -n 2::+1GiB --typecode=2:ef00 --change-name=2:'EFIBOOT' "${DISK}" # partition 2 (UEFI Boot Partition)
sgdisk -n 3::-0 --typecode=3:8300 --change-name=3:'ROOT' "${DISK}" # partition 3 (Root), default start, remaining
if [[ ! -d "/sys/firmware/efi" ]]; then # Checking for bios system
sgdisk -A 1:set:2 "${DISK}"
fi
partprobe "${DISK}" # reread partition table to ensure it is correct
# make filesystems
echo -ne "
-------------------------------------------------------------------------
Creating Filesystems
-------------------------------------------------------------------------
"
# @description Creates the btrfs subvolumes.
createsubvolumes () {
btrfs subvolume create /mnt/@
btrfs subvolume create /mnt/@home
}
# @description Mount all btrfs subvolumes after root has been mounted.
mountallsubvol () {
mount -o "${MOUNT_OPTIONS}",subvol=@home "${partition3}" /mnt/home
}
# @description BTRFS subvolulme creation and mounting.
subvolumesetup () {
# create nonroot subvolumes
createsubvolumes
# unmount root to remount with subvolume
umount /mnt
# mount @ subvolume
mount -o "${MOUNT_OPTIONS}",subvol=@ "${partition3}" /mnt
# make directories home, .snapshots, var, tmp
mkdir -p /mnt/home
# mount subvolumes
mountallsubvol
}
if [[ "${DISK}" =~ "nvme" ]]; then
partition2=${DISK}p2
partition3=${DISK}p3
else
partition2=${DISK}2
partition3=${DISK}3
fi
if [[ "${FS}" == "btrfs" ]]; then
mkfs.vfat -F32 -n "EFIBOOT" "${partition2}"
mkfs.btrfs -L ROOT "${partition3}" -f
mount -t btrfs "${partition3}" /mnt
subvolumesetup
elif [[ "${FS}" == "ext4" ]]; then
mkfs.vfat -F32 -n "EFIBOOT" "${partition2}"
mkfs.ext4 -L ROOT "${partition3}"
mount -t ext4 "${partition3}" /mnt
elif [[ "${FS}" == "luks" ]]; then
mkfs.vfat -F32 -n "EFIBOOT" "${partition2}"
# enter luks password to cryptsetup and format root partition
echo -n "${LUKS_PASSWORD}" | cryptsetup -y -v luksFormat "${partition3}" -
# open luks container and ROOT will be place holder
echo -n "${LUKS_PASSWORD}" | cryptsetup open "${partition3}" ROOT -
# now format that container
mkfs.btrfs -L ROOT "${partition3}"
# create subvolumes for btrfs
mount -t btrfs "${partition3}" /mnt
subvolumesetup
fi
sync
if ! mountpoint -q /mnt; then
echo "ERROR! Failed to mount ${partition3} to /mnt after multiple attempts."
exit 1
fi
mkdir -p /mnt/boot/efi
mount -t vfat -L EFIBOOT /mnt/boot/
if ! grep -qs '/mnt' /proc/mounts; then
echo "Drive is not mounted can not continue"
echo "Rebooting in 3 Seconds ..." && sleep 1
echo "Rebooting in 2 Seconds ..." && sleep 1
echo "Rebooting in 1 Second ..." && sleep 1
reboot now
fi
echo -ne "
-------------------------------------------------------------------------
Arch Install on Main Drive
-------------------------------------------------------------------------
"
if [[ ! -d "/sys/firmware/efi" ]]; then
pacstrap /mnt base base-devel linux-lts linux-firmware --noconfirm --needed
else
pacstrap /mnt base base-devel linux-lts linux-firmware efibootmgr --noconfirm --needed
fi
echo "keyserver hkp://keyserver.ubuntu.com" >> /mnt/etc/pacman.d/gnupg/gpg.conf
cp /etc/pacman.d/mirrorlist /mnt/etc/pacman.d/mirrorlist
genfstab -L /mnt >> /mnt/etc/fstab
echo "
Generated /etc/fstab:
"
cat /mnt/etc/fstab
echo -ne "
-------------------------------------------------------------------------
GRUB BIOS Bootloader Install & Check
-------------------------------------------------------------------------
"
if [[ ! -d "/sys/firmware/efi" ]]; then
grub-install --boot-directory=/mnt/boot "${DISK}"
fi
echo -ne "
-------------------------------------------------------------------------
Checking for low memory systems <8G
-------------------------------------------------------------------------
"
TOTAL_MEM=$(cat /proc/meminfo | grep -i 'memtotal' | grep -o '[[:digit:]]*')
if [[ $TOTAL_MEM -lt 8000000 ]]; then
# Put swap into the actual system, not into RAM disk, otherwise there is no point in it, it'll cache RAM into RAM. So, /mnt/ everything.
mkdir -p /mnt/opt/swap # make a dir that we can apply NOCOW to to make it btrfs-friendly.
if findmnt -n -o FSTYPE /mnt | grep -q btrfs; then
chattr +C /mnt/opt/swap # apply NOCOW, btrfs needs that.
fi
dd if=/dev/zero of=/mnt/opt/swap/swapfile bs=1M count=2048 status=progress
chmod 600 /mnt/opt/swap/swapfile # set permissions.
chown root /mnt/opt/swap/swapfile
mkswap /mnt/opt/swap/swapfile
swapon /mnt/opt/swap/swapfile
# The line below is written to /mnt/ but doesn't contain /mnt/, since it's just / for the system itself.
echo "/opt/swap/swapfile none swap sw 0 0" >> /mnt/etc/fstab # Add swap to fstab, so it KEEPS working after installation.
fi
gpu_type=$(lspci | grep -E "VGA|3D|Display")
arch-chroot /mnt /bin/bash -c "KEYMAP='${KEYMAP}' /bin/bash" <<EOF
echo -ne "
-------------------------------------------------------------------------
Network Setup
-------------------------------------------------------------------------
"
pacman -S --noconfirm --needed networkmanager dhclient
systemctl enable --now NetworkManager
echo -ne "
-------------------------------------------------------------------------
Setting up mirrors for optimal download
-------------------------------------------------------------------------
"
pacman -S --noconfirm --needed pacman-contrib curl
pacman -S --noconfirm --needed reflector rsync grub arch-install-scripts git ntp wget
cp /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.bak
nc=$(grep -c ^processor /proc/cpuinfo)
echo -ne "
-------------------------------------------------------------------------
You have " $nc" cores. And
changing the makeflags for " $nc" cores. Aswell as
changing the compression settings.
-------------------------------------------------------------------------
"
TOTAL_MEM=$(cat /proc/meminfo | grep -i 'memtotal' | grep -o '[[:digit:]]*')
if [[ $TOTAL_MEM -gt 8000000 ]]; then
sed -i "s/#MAKEFLAGS=\"-j2\"/MAKEFLAGS=\"-j$nc\"/g" /etc/makepkg.conf
sed -i "s/COMPRESSXZ=(xz -c -z -)/COMPRESSXZ=(xz -c -T $nc -z -)/g" /etc/makepkg.conf
fi
echo -ne "
-------------------------------------------------------------------------
Setup Language to US and set locale
-------------------------------------------------------------------------
"
sed -i 's/^#en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen
locale-gen
timedatectl --no-ask-password set-timezone ${TIMEZONE}
timedatectl --no-ask-password set-ntp 1
localectl --no-ask-password set-locale LANG="en_US.UTF-8" LC_TIME="en_US.UTF-8"
ln -s /usr/share/zoneinfo/${TIMEZONE} /etc/localtime
# Set keymaps
echo "KEYMAP=${KEYMAP}" > /etc/vconsole.conf
echo "XKBLAYOUT=${KEYMAP}" >> /etc/vconsole.conf
echo "Keymap set to: ${KEYMAP}"
# Add sudo no password rights
sed -i 's/^# %wheel ALL=(ALL) NOPASSWD: ALL/%wheel ALL=(ALL) NOPASSWD: ALL/' /etc/sudoers
sed -i 's/^# %wheel ALL=(ALL:ALL) NOPASSWD: ALL/%wheel ALL=(ALL:ALL) NOPASSWD: ALL/' /etc/sudoers
#Add parallel downloading
sed -i 's/^#ParallelDownloads/ParallelDownloads/' /etc/pacman.conf
#Enable multilib
sed -i "/\[multilib\]/,/Include/"'s/^#//' /etc/pacman.conf
pacman -Sy --noconfirm --needed
echo -ne "
-------------------------------------------------------------------------
Installing Microcode
-------------------------------------------------------------------------
"
# determine processor type and install microcode
if grep -q "GenuineIntel" /proc/cpuinfo; then
echo "Installing Intel microcode"
pacman -S --noconfirm --needed intel-ucode
elif grep -q "AuthenticAMD" /proc/cpuinfo; then
echo "Installing AMD microcode"
pacman -S --noconfirm --needed amd-ucode
else
echo "Unable to determine CPU vendor. Skipping microcode installation."
fi
echo -ne "
-------------------------------------------------------------------------
Installing Graphics Drivers
-------------------------------------------------------------------------
"
# Graphics Drivers find and install
if echo "${gpu_type}" | grep -E "NVIDIA|GeForce"; then
echo "Installing NVIDIA drivers: nvidia-lts"
pacman -S --noconfirm --needed nvidia-lts
elif echo "${gpu_type}" | grep 'VGA' | grep -E "Radeon|AMD"; then
echo "Installing AMD drivers: xf86-video-amdgpu"
pacman -S --noconfirm --needed xf86-video-amdgpu
elif echo "${gpu_type}" | grep -E "Integrated Graphics Controller"; then
echo "Installing Intel drivers:"
pacman -S --noconfirm --needed libva-intel-driver libvdpau-va-gl lib32-vulkan-intel vulkan-intel libva-intel-driver libva-utils lib32-mesa
elif echo "${gpu_type}" | grep -E "Intel Corporation UHD"; then
echo "Installing Intel UHD drivers:"
pacman -S --noconfirm --needed libva-intel-driver libvdpau-va-gl lib32-vulkan-intel vulkan-intel libva-intel-driver libva-utils lib32-mesa
fi
echo -ne "
-------------------------------------------------------------------------
Adding User
-------------------------------------------------------------------------
"
groupadd libvirt
useradd -m -G wheel,libvirt -s /bin/bash $USERNAME
echo "$USERNAME created, home directory created, added to wheel and libvirt group, default shell set to /bin/bash"
echo "$USERNAME:$PASSWORD" | chpasswd
echo "$USERNAME password set"
echo $NAME_OF_MACHINE > /etc/hostname
if [[ ${FS} == "luks" ]]; then
# Making sure to edit mkinitcpio conf if luks is selected
# add encrypt in mkinitcpio.conf before filesystems in hooks
sed -i 's/filesystems/encrypt filesystems/g' /etc/mkinitcpio.conf
# making mkinitcpio with linux kernel
mkinitcpio -p linux-lts
fi
echo -ne "
-------------------------------------------------------------------------
█████╗ ██████╗ ██████╗██╗ ██╗████████╗██╗████████╗██╗ ██╗███████╗
██╔══██╗██╔══██╗██╔════╝██║ ██║╚══██╔══╝██║╚══██╔══╝██║ ██║██╔════╝
███████║██████╔╝██║ ███████║ ██║ ██║ ██║ ██║ ██║███████╗
██╔══██║██╔══██╗██║ ██╔══██║ ██║ ██║ ██║ ██║ ██║╚════██║
██║ ██║██║ ██║╚██████╗██║ ██║ ██║ ██║ ██║ ╚██████╔╝███████║
╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝
-------------------------------------------------------------------------
Automated Arch Linux Installer
-------------------------------------------------------------------------
Final Setup and Configurations
GRUB EFI Bootloader Install & Check
"
if [[ -d "/sys/firmware/efi" ]]; then
grub-install --efi-directory=/boot ${DISK}
fi
echo -ne "
-------------------------------------------------------------------------
Creating (and Theming) Grub Boot Menu
-------------------------------------------------------------------------
"
# set kernel parameter for decrypting the drive
if [[ "${FS}" == "luks" ]]; then
sed -i "s%GRUB_CMDLINE_LINUX_DEFAULT=\"%GRUB_CMDLINE_LINUX_DEFAULT=\"cryptdevice=UUID=${ENCRYPTED_PARTITION_UUID}:ROOT root=/dev/mapper/ROOT %g" /etc/default/grub
fi
# set kernel parameter for adding splash screen
sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="[^"]*/& splash /' /etc/default/grub
echo -e "Installing CyberRe Grub theme..."
THEME_DIR="/boot/grub/themes/CyberRe"
echo -e "Creating the theme directory..."
mkdir -p "${THEME_DIR}"
# Clone the theme
cd "${THEME_DIR}" || exit
git init
git remote add -f origin https://github.com/ChrisTitusTech/Top-5-Bootloader-Themes.git
git config core.sparseCheckout true
echo "themes/CyberRe/*" >> .git/info/sparse-checkout
git pull origin main
mv themes/CyberRe/* .
rm -rf themes
rm -rf .git
echo "CyberRe theme has been cloned to ${THEME_DIR}"
echo -e "Backing up Grub config..."
cp -an /etc/default/grub /etc/default/grub.bak
echo -e "Setting the theme as the default..."
grep "GRUB_THEME=" /etc/default/grub 2>&1 >/dev/null && sed -i '/GRUB_THEME=/d' /etc/default/grub
echo "GRUB_THEME=\"${THEME_DIR}/theme.txt\"" >> /etc/default/grub
echo -e "Updating grub..."
grub-mkconfig -o /boot/grub/grub.cfg
echo -e "All set!"
echo -ne "
-------------------------------------------------------------------------
Enabling Essential Services
-------------------------------------------------------------------------
"
ntpd -qg
systemctl enable ntpd.service
echo " NTP enabled"
systemctl disable dhcpcd.service
echo " DHCP disabled"
systemctl stop dhcpcd.service
echo " DHCP stopped"
systemctl enable NetworkManager.service
echo " NetworkManager enabled"
echo -ne "
-------------------------------------------------------------------------
Cleaning
-------------------------------------------------------------------------
"
# Remove no password sudo rights
sed -i 's/^%wheel ALL=(ALL) NOPASSWD: ALL/# %wheel ALL=(ALL) NOPASSWD: ALL/' /etc/sudoers
sed -i 's/^%wheel ALL=(ALL:ALL) NOPASSWD: ALL/# %wheel ALL=(ALL:ALL) NOPASSWD: ALL/' /etc/sudoers
# Add sudo rights
sed -i 's/^# %wheel ALL=(ALL) ALL/%wheel ALL=(ALL) ALL/' /etc/sudoers
sed -i 's/^# %wheel ALL=(ALL:ALL) ALL/%wheel ALL=(ALL:ALL) ALL/' /etc/sudoers
EOF

View file

@ -0,0 +1,26 @@
#!/bin/sh -e
. ../../common-script.sh
installDepend() {
case "$PACKAGER" in
pacman)
if ! command_exists yay; then
printf "%b\n" "${YELLOW}Installing yay as AUR helper...${RC}"
"$ESCALATION_TOOL" "$PACKAGER" -S --needed --noconfirm base-devel git
cd /opt && "$ESCALATION_TOOL" git clone https://aur.archlinux.org/yay-bin.git && "$ESCALATION_TOOL" chown -R "$USER": ./yay-bin
cd yay-bin && makepkg --noconfirm -si
printf "%b\n" "${GREEN}Yay installed${RC}"
else
printf "%b\n" "${GREEN}Aur helper already installed${RC}"
fi
;;
*)
printf "%b\n" "${RED}Unsupported package manager: ""$PACKAGER""${RC}"
;;
esac
}
checkEnv
checkEscalationTool
installDepend

View file

@ -0,0 +1,23 @@
#!/bin/sh -e
. ../../common-script.sh
configureDNF() {
case "$PACKAGER" in
dnf)
printf "%b\n" "${YELLOW}Configuring DNF...${RC}"
"$ESCALATION_TOOL" sed -i '/^max_parallel_downloads=/c\max_parallel_downloads=10' /etc/dnf/dnf.conf || echo 'max_parallel_downloads=10' >> /etc/dnf/dnf.conf
echo "fastestmirror=True" | "$ESCALATION_TOOL" tee -a /etc/dnf/dnf.conf > /dev/null
echo "defaultyes=True" | "$ESCALATION_TOOL" tee -a /etc/dnf/dnf.conf > /dev/null
"$ESCALATION_TOOL" "$PACKAGER" -y install dnf-plugins-core
printf "%b\n" "${GREEN}DNF Configured Successfully.${RC}"
;;
*)
printf "%b\n" "${RED}Unsupported distribution: $DTYPE${RC}"
;;
esac
}
checkEnv
checkEscalationTool
configureDNF

View file

@ -0,0 +1,26 @@
#!/bin/sh -e
. ../../common-script.sh
multimedia() {
case "$PACKAGER" in
dnf)
if [ -e /etc/yum.repos.d/rpmfusion-free.repo ] && [ -e /etc/yum.repos.d/rpmfusion-nonfree.repo ]; then
printf "%b\n" "${YELLOW}Installing Multimedia Codecs...${RC}"
"$ESCALATION_TOOL" "$PACKAGER" swap ffmpeg-free ffmpeg --allowerasing -y
"$ESCALATION_TOOL" "$PACKAGER" update @multimedia --setopt="install_weak_deps=False" --exclude=PackageKit-gstreamer-plugin -y
"$ESCALATION_TOOL" "$PACKAGER" update @sound-and-video -y
printf "%b\n" "${GREEN}Multimedia Codecs Installed...${RC}"
else
printf "%b\n" "${RED}RPM Fusion repositories not found. Please set up RPM Fusion first!${RC}"
fi
;;
*)
printf "%b\n" "${RED}Unsupported distribution: $DTYPE${RC}"
;;
esac
}
checkEnv
checkEscalationTool
multimedia

View file

@ -0,0 +1,94 @@
#!/bin/sh -e
. ../../common-script.sh
# This script allows user to download proprietary drivers for nvidia in fedora
# It also disables nouveau nvidia drivers
# Installation guide link: https://rpmfusion.org/Howto/NVIDIA
# NOTE: Currently script only provides drivers for gpu 2014 and above (510+ and above)
checkRepo() {
REPO_ID="rpmfusion-nonfree-nvidia-driver"
if [ "$(dnf repolist enabled 2>/dev/null | grep -c "$REPO_ID")" -gt 0 ]; then
printf "%b\n" "${GREEN}Nvidia non-free repository is already enabled.${RC}"
else
printf "%b\n" "${YELLOW}Nvidia non-free repository is not enabled. Enabling now...${RC}"
# Enable the repository
"$ESCALATION_TOOL" dnf config-manager --set-enabled "$REPO_ID"
# Refreshing repository list
"$ESCALATION_TOOL" dnf makecache
# Verify if the repository is enabled
if [ "$(dnf repolist enabled 2>/dev/null | grep -c "$REPO_ID")" -gt 0 ]; then
printf "%b\n" "${GREEN}Nvidia non-free repository is now enabled...${RC}"
else
printf "%b\n" "${RED}Failed to enable nvidia non-free repository...${RC}"
exit 1
fi
fi
}
checkDriverInstallation() {
if modinfo -F version nvidia >/dev/null 2>&1; then
return 0
else
return 1
fi
}
installDriver() {
if checkDriverInstallation; then
printf "%b\n" "${GREEN}NVIDIA driver is already installed.${RC}"
exit 0
fi
# NOTE:: Installing graphics driver.
"$ESCALATION_TOOL" dnf install akmod-nvidia xorg-x11-drv-nvidia-cuda -y
printf "%b\n" "${YELLOW}Building the drivers may take upto 5 minutes. Please don't kill the script!\n If the build failed try running the script again, select \"Remove Nvidia Drivers\" and reboot the system, then try installing drivers again.${RC}"
for i in $(seq 1 5); do
if checkDriverInstallation; then
printf "%b\n" "${GREEN}Driver installed successfully.${RC}"
printf "%b\n" "${GREEN}Installed driver version $(modinfo -F version nvidia)${RC}"
break
fi
printf "%b\n" "${YELLOW}Waiting for driver to be built..."
sleep 1m
done
printf "%b\n" "${GREEN}Now you can reboot the system.${RC}"
}
# NOTE: A confirmation option to proceed or not
userConfirmation() {
printf "%b" "${YELLOW}Do you want to continue? (y/N): ${RC}"
read -r choice
case "$choice" in
y | Y)
checkRepo
installDriver
return
;;
n | N)
printf "%b\n" "${RED} Exiting the Script ${RC}"
return
;;
*)
printf "%b\n" "${RED} Invalid Option! ${RC}"
userConfirmation
;;
esac
}
printf "%b\n" "${YELLOW}Warning! This script will enable Nvidia non-free repository and only install drivers for GPUs from 2014 or later. It works on fedora 34 and above.\n It is recommended remove this driver while updating your kernel packages to newer version.${RC}"
checkEnv
checkEscalationTool
userConfirmation

View file

@ -0,0 +1,29 @@
#!/bin/sh -e
. ../../common-script.sh
# https://rpmfusion.org/Configuration
installRPMFusion() {
case "$PACKAGER" in
dnf)
if [ ! -e /etc/yum.repos.d/rpmfusion-free.repo ] || [ ! -e /etc/yum.repos.d/rpmfusion-nonfree.repo ]; then
printf "%b\n" "${YELLOW}Installing RPM Fusion...${RC}"
"$ESCALATION_TOOL" "$PACKAGER" install "https://mirrors.rpmfusion.org/free/fedora/rpmfusion-free-release-$(rpm -E %fedora)".noarch.rpm https://mirrors.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-"$(rpm -E %fedora)".noarch.rpm
"$ESCALATION_TOOL" "$PACKAGER" config-manager --enable fedora-cisco-openh264
"$ESCALATION_TOOL" "$PACKAGER" config-manager --set-enabled rpmfusion-nonfree-updates
"$ESCALATION_TOOL" "$PACKAGER" config-manager --set-enabled rpmfusion-free-updates
printf "%b\n" "${GREEN}RPM Fusion installed and enabled${RC}"
else
printf "%b\n" "${GREEN}RPM Fusion already installed${RC}"
fi
;;
*)
printf "%b\n" "${RED}Unsupported distribution: $DTYPE${RC}"
;;
esac
}
checkEnv
checkEscalationTool
installRPMFusion

View file

@ -0,0 +1,21 @@
#!/bin/sh -e
. ../../common-script.sh
# Install virtualization tools to enable virtual machines
configureVirtualization() {
case "$PACKAGER" in
dnf)
printf "%b\n" "${YELLOW}Installing virtualization tools...${RC}"
"$ESCALATION_TOOL" "$PACKAGER" install -y @virtualization
printf "%b\n" "${GREEN}Installed virtualization tools...${RC}"
;;
*)
printf "%b\n" "${RED}Unsupported distribution: $DTYPE${RC}"
;;
esac
}
checkEnv
checkEscalationTool
configureVirtualization

View file

@ -0,0 +1,106 @@
#!/bin/sh -e
. ../common-script.sh
installDepend() {
# Check for dependencies
DEPENDENCIES='wine dbus'
printf "%b\n" "${YELLOW}Installing dependencies...${RC}"
case "$PACKAGER" in
pacman)
#Check for multilib
if ! grep -q "^\s*\[multilib\]" /etc/pacman.conf; then
echo "[multilib]" | "$ESCALATION_TOOL" tee -a /etc/pacman.conf
echo "Include = /etc/pacman.d/mirrorlist" | "$ESCALATION_TOOL" tee -a /etc/pacman.conf
"$ESCALATION_TOOL" "$PACKAGER" -Syu
else
printf "%b\n" "${GREEN}Multilib is already enabled.${RC}"
fi
DISTRO_DEPS="gnutls lib32-gnutls base-devel gtk2 gtk3 lib32-gtk2 lib32-gtk3 libpulse lib32-libpulse alsa-lib lib32-alsa-lib \
alsa-utils alsa-plugins lib32-alsa-plugins alsa-lib lib32-alsa-lib giflib lib32-giflib libpng lib32-libpng \
libldap lib32-libldap openal lib32-openal libxcomposite lib32-libxcomposite libxinerama lib32-libxinerama \
ncurses lib32-ncurses vulkan-icd-loader lib32-vulkan-icd-loader ocl-icd lib32-ocl-icd libva lib32-libva \
gst-plugins-base-libs lib32-gst-plugins-base-libs sdl2"
$AUR_HELPER -S --needed --noconfirm $DEPENDENCIES $DISTRO_DEPS
;;
apt-get|nala)
DISTRO_DEPS="libasound2 libsdl2 wine64 wine32"
"$ESCALATION_TOOL" "$PACKAGER" update
"$ESCALATION_TOOL" dpkg --add-architecture i386
"$ESCALATION_TOOL" "$PACKAGER" install -y software-properties-common
"$ESCALATION_TOOL" apt-add-repository contrib -y
"$ESCALATION_TOOL" "$PACKAGER" update
"$ESCALATION_TOOL" "$PACKAGER" install -y $DEPENDENCIES $DISTRO_DEPS
;;
dnf)
if [ "$(rpm -E %fedora)" -le 41 ]; then
"$ESCALATION_TOOL" "$PACKAGER" install ffmpeg ffmpeg-libs -y
"$ESCALATION_TOOL" "$PACKAGER" install -y $DEPENDENCIES
else
printf "%b\n" "${CYAN}Fedora < 41 detected. Installing rpmfusion repos.${RC}"
"$ESCALATION_TOOL" "$PACKAGER" install https://mirrors.rpmfusion.org/free/fedora/rpmfusion-free-release-"$(rpm -E %fedora)".noarch.rpm https://mirrors.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-"$(rpm -E %fedora)".noarch.rpm -y
"$ESCALATION_TOOL" "$PACKAGER" config-manager --enable fedora-cisco-openh264 -y
"$ESCALATION_TOOL" "$PACKAGER" install -y $DEPENDENCIES
fi
;;
zypper)
"$ESCALATION_TOOL" "$PACKAGER" -n install $DEPENDENCIES
;;
*)
"$ESCALATION_TOOL" "$PACKAGER" install -y $DEPENDENCIES
;;
esac
}
installAdditionalDepend() {
case "$PACKAGER" in
pacman)
DISTRO_DEPS='steam lutris goverlay'
"$ESCALATION_TOOL" "$PACKAGER" -S --needed --noconfirm $DISTRO_DEPS
;;
apt-get|nala)
version=$(git -c 'versionsort.suffix=-' ls-remote --tags --sort='v:refname' https://github.com/lutris/lutris |
grep -v 'beta' |
tail -n1 |
cut -d '/' --fields=3)
version_no_v=$(echo "$version" | tr -d v)
curl -sSLo "lutris_${version_no_v}_all.deb" "https://github.com/lutris/lutris/releases/download/${version}/lutris_${version_no_v}_all.deb"
printf "%b\n" "${YELLOW}Installing Lutris...${RC}"
"$ESCALATION_TOOL" "$PACKAGER" install ./lutris_"${version_no_v}"_all.deb
rm lutris_"${version_no_v}"_all.deb
printf "%b\n" "${GREEN}Lutris Installation complete.${RC}"
printf "%b\n" "${YELLOW}Installing steam...${RC}"
if lsb_release -i | grep -qi Debian; then
"$ESCALATION_TOOL" apt-add-repository non-free -y
"$ESCALATION_TOOL" "$PACKAGER" install steam-installer -y
else
"$ESCALATION_TOOL" "$PACKAGER" install -y steam
fi
;;
dnf)
DISTRO_DEPS='steam lutris'
"$ESCALATION_TOOL" "$PACKAGER" install -y $DISTRO_DEPS
;;
zypper)
# Flatpak
DISTRO_DEPS='lutris'
"$ESCALATION_TOOL" "$PACKAGER" -n install $DISTRO_DEPS
;;
*)
;;
esac
}
checkEnv
checkAURHelper
checkEscalationTool
installDepend
installAdditionalDepend

View file

@ -0,0 +1,466 @@
#!/bin/sh -e
# ANSI color codes
RED='\033[0;31m'
CYAN='\033[0;36m'
YELLOW='\033[0;33m'
LIGHT_GREEN='\033[0;92m'
BOLD='\033[1m'
NC='\033[0m'
# Initialize storage variables
_STORED_ERRORS=""
_STORED_WARNINGS=""
_STORED_INFOS=""
_STORED_NOTES=""
# Modified echo functions that store and display messages
echo_error() {
message="${RED}$1${NC}\n"
printf "$message" >&2
_STORED_ERRORS="${_STORED_ERRORS}${message}"
}
echo_warning() {
message="${YELLOW}$1${NC}\n"
printf "$message"
_STORED_WARNINGS="${_STORED_WARNINGS}${message}"
}
echo_info() {
message="${CYAN}$1${NC}\n"
printf "$message"
_STORED_INFOS="${_STORED_INFOS}${message}"
}
echo_note() {
message="${LIGHT_GREEN}$1${NC}\n"
printf "$message"
_STORED_NOTES="${_STORED_NOTES}${message}"
}
echo_db() {
message="${LIGHT_GREEN}$1${NC}\n"
printf "$message"
}
# ─< Check if the given command exists silently >─────────────────────────────────────────
command_exists() {
command -v "$@" >/dev/null 2>&1
}
# ─< to get the alias to install everything either with your shell or inside your script! >─
if command_exists curl; then
install_pkg() {
sh -c "$(curl -sSL https://git.k4li.de/pika/scripts/raw/branch/main/bash/snippets/install_pkg.sh)" -- "$@"
}
else
echo_error "curl is not installed, universal install disabled!"
fi
# Check if the user is root and set sudo variable if necessary
check_root() {
if [ "$(id -u)" -ne 0 ]; then
if command_exists sudo; then
echo_info "User is not root. Using sudo for privileged operations."
_sudo="sudo"
else
echo_error "No sudo found and you're not root! Can't install packages."
return 1
fi
else
echo_info "Root access confirmed."
_sudo=""
fi
}
comment_cd_sources() {
# Path to sources.list
sources_file="/etc/apt/sources.list"
# Check if file exists
if [ ! -f "$sources_file" ]; then
echo_error "Error: $sources_file not found"
return 1
fi
# Comment out CD-ROM entries using sudo
$_sudo sed -i 's/^[[:space:]]*deb[[:space:]]\+cdrom:/#&/' "$sources_file"
echo_info "CD-ROM entries have been commented out in $sources_file"
}
i_yazi() {
if command_exists curl; then
curl -fsSL https://git.k4li.de/pika/scripts/raw/branch/main/bash/installs/yazi.sh | sh
else
echo_error "No curl was found"
fi
}
deps="zsh tmux gdu rsync fzf unzip go btop make stow git npm bc pv zoxide ripgrep trash-cli"
check_nala() {
deb_pkger=""
echo_info "Updating sources.."
if ! $_sudo apt-get update; then
echo_error "Maybe you need a proxy?"
fi
if ! command_exists sudo; then
echo_note "Installing sudo"
apt-get install sudo --assume-yes
fi
if command_exists nala; then
deb_pkger="nala"
echo_info "Nala is already present, fetching mirros now! (This might take a minute or two, depending on your internet speed)"
$_sudo nala fetch --auto --assume-yes
else
echo_note "Nala is not installed on the system, do you want to install it now? (Y/n): "
read -r inst_nala
case "$inst_nala" in
N | n)
deb_pkger="apt-get"
echo_warning "All right, continue without nala!"
;;
*)
echo_note "Installing nala.."
$_sudo apt-get install nala --assume-yes &&
deb_pkger="nala"
echo_info "Fetching best mirrors"
$_sudo nala fetch --auto --assume-yes
;;
esac
fi
}
inst_debian() {
comment_cd_sources
check_nala
if command_exists nano; then
if command_exists vi; then
echo_note "Removing nano"
$_sudo $deb_pkger remove nano --assume-yes
else
echo_info "Removing nano and installing vi as a backup"
$_sudo $deb_pkger remove nano --assume-yes && $_sudo apt-get install vi --assume-yes
fi
fi
echo_note "Installing base packages: $deps"
for _deps in $deps; do
if ! command_exists "$_deps"; then
if ! $_sudo $deb_pkger install "$_deps" --assume-yes; then
echo_error "$_deps - failed to install"
fi
else
echo_note "$_deps - was already installed"
fi
done
i_yazi
}
inst_ubuntu() {
comment_cd_sources
check_nala
if command_exists nano; then
if command_exists vi; then
echo_note "Removing nano"
$_sudo $deb_pkger remove nano --assume-yes
else
echo_note "Removing nano and installing vi as a backup"
$_sudo $deb_pkger remove nano --assume-yes && $_sudo apt-get install vi --assume-yes
fi
fi
echo_note "Installing base packages: $deps"
for _deps in $deps; do
if ! command_exists "$_deps"; then
if ! $_sudo $deb_pkger install "$_deps" --assume-yes; then
echo_error "$_deps - failed to install"
fi
else
echo_note "$_deps - was already installed"
fi
done
i_yazi
}
inst_fedora() {
if command_exists nano; then
if command_exists vi; then
echo_note "Removing nano"
$_sudo dnf remove nano </dev/tty
else
echo_note "Removing nano and installing vi as a backup"
$_sudo dnf remove nano </dev/tty &&
$_sudo dnf install vi </dev/tty
fi
fi
echo_note "Installing base packages: $deps"
for _deps in $deps; do
if ! command_exists "$_deps"; then
if ! $_sudo dnf install "$_deps" </dev/tty; then
echo_error "$_deps - failed to install"
fi
else
echo_note "$_deps - was already installed"
fi
done
i_yazi
}
inst_opensuse() {
if command_exists nano; then
if command_exists vi; then
echo_note "Removing nano"
$_sudo zypper install -y nano </dev/tty
else
echo_note "Removing nano and installing vi as a backup"
$_sudo zypper install -y vi </dev/tty
fi
fi
echo_note "Installing base packages: $deps"
for _deps in $deps; do
if ! command_exists "$_deps"; then
if ! $_sudo zypper in -y "$_deps" </dev/tty; then
echo_error "$_deps - failed to install"
fi
else
echo_note "$_deps - was already installed"
fi
done
i_yazi
}
inst_arch() {
if command_exists nano; then
if command_exists vi; then
echo_note "Removing nano"
$_sudo pacman -R nano --noconfirm
else
echo_note "Removing nano and installing vi as a backup"
$_sudo pacman -S vi --noconfirm
fi
fi
$_sudo pacman -S base-devel --noconfirm
echo_note "Installing base packages: $deps"
for _deps in $deps; do
if ! command_exists "$_deps"; then
if ! $_sudo pacman -S "$_deps" --noconfirm; then
echo_error "$_deps - failed to install"
fi
else
echo_note "$_deps - was already installed"
fi
done
i_yazi
}
# ─< Distribution detection and installation >────────────────────────────────────────
get_packager() {
if [ -e /etc/os-release ]; then
echo_info "Detecting distribution..."
. /etc/os-release
# Convert $ID and $ID_LIKE to lowercase
ID=$(printf "%s" "$ID" | tr '[:upper:]' '[:lower:]')
ID_LIKE=$(printf "%s" "$ID_LIKE" | tr '[:upper:]' '[:lower:]')
case "$ID" in
ubuntu | pop | zorin) inst_ubuntu ;;
debian) inst_debian ;;
fedora) inst_fedora ;;
alpine) inst_alpine ;;
arch | manjaro | garuda | endeavour) inst_arch ;;
opensuse*) inst_opensuse ;;
*)
# Use standard [ ] syntax for string matching
if [ "${ID_LIKE#*debian}" != "$ID_LIKE" ]; then
inst_debian
elif [ "${ID_LIKE#*ubuntu}" != "$ID_LIKE" ]; then
inst_ubuntu
elif [ "${ID_LIKE#*arch}" != "$ID_LIKE" ]; then
inst_arch
elif [ "${ID_LIKE#*fedora}" != "$ID_LIKE" ]; then
inst_fedora
elif [ "${ID_LIKE#*suse}" != "$ID_LIKE" ]; then
inst_opensuse
else
echo_error "Unsupported distribution: $ID"
exit 1
fi
;;
esac
else
echo_error "Unable to detect distribution. /etc/os-release not found."
exit 1
fi
}
# Improved display function that only shows categories with content
display_stored_messages() {
has_messages=0
# First check if we have any messages at all
if [ -z "$_STORED_ERRORS" ] && [ -z "$_STORED_WARNINGS" ] && [ -z "$_STORED_INFOS" ] && [ -z "$_STORED_NOTES" ]; then
return 0
fi
# Now display each non-empty category with proper spacing
if [ -n "$_STORED_ERRORS" ]; then
printf "\n${BOLD}${RED}=== Errors ===${NC}\n"
printf "$_STORED_ERRORS"
has_messages=1
fi
if [ -n "$_STORED_WARNINGS" ]; then
[ "$has_messages" -eq 1 ] && printf "\n"
printf "${BOLD}${YELLOW}=== Warnings ===${NC}\n"
printf "$_STORED_WARNINGS"
has_messages=1
fi
if [ -n "$_STORED_INFOS" ]; then
[ "$has_messages" -eq 1 ] && printf "\n"
printf "${BOLD}${CYAN}=== Info ===${NC}\n"
printf "$_STORED_INFOS"
has_messages=1
fi
if [ -n "$_STORED_NOTES" ]; then
[ "$has_messages" -eq 1 ] && printf "\n"
printf "${BOLD}${LIGHT_GREEN}=== Notes ===${NC}\n"
printf "$_STORED_NOTES"
fi
}
_inst_docker() {
if ! command_exists docker; then
bash --norc -c "$(curl -fsSL https://git.k4li.de/pika/scripts/raw/branch/main/bash/installs/docker.sh)"
else
echo_note "Docker is already installed, do you need to activate it and make the group changes for $(whoami)? (y/n): "
read -r _docker
case "$_docker" in
N | n)
return 1
;;
*)
$_sudo systemctl enable --now docker &&
$_sudo usermod -aG docker "$(whoami)"
echo_info "Docker was configured"
;;
esac
fi
}
_inst_lazydocker() {
if [ ! -e "$HOME/.local/bin/lazydocker" ]; then
if command_exists curl; then
curl https://raw.githubusercontent.com/jesseduffield/lazydocker/master/scripts/install_update_linux.sh | bash
else
echo_error "curl is not installed, cannot continue!"
exit 1
fi
else
echo_warning "$HOME/.local/bin/lazydocker is already present."
fi
_dashboard
}
_check_gitpath() {
if [ ! -d "$HOME/git/" ]; then
mkdir $HOME/git
else
echo_note "git dir is already present"
fi
}
_ytgo() {
if ! command_exists go; then
if ! install_pkg golang; then
echo_error "Something went wrong, couldn't install golang"
fi
fi
if ! command_exists ytgo; then
cd "$(mktemp --dir)"
git clone --depth=1 https://git.k4li.de/pika/ytgo.git
cd ytgo
make install
else
echo_info "ytgo is already present at $(whereis ytgo)"
fi
}
_init_dotfiles() {
_check_gitpath
echo_db "What dotfiles do you want to clone?
1. homelab-dotfiles
2. hyprdots
3. tty-dotfiles
q. Quit"
read -r _dotfiles_db
case "$_dotfiles_db" in
1)
git clone --recursive --depth=1 https://git.k4li.de/dotfiles/homelab-dotfiles.git $HOME/git/homelab-dotfiles
;;
2)
git clone --recursive --depth=1 https://git.k4li.de/dotfiles/hyprdots.git $HOME/git/hyprdots
;;
3)
git clone --recursive --depth=1 https://git.k4li.de/dotfiles/tty-dotfiles.git $HOME/git/tty-dotfiles
;;
q)
return 1
;;
*)
echo default
;;
esac
_dashboard
}
_dashboard() {
echo_db "What else can I do for you?
1. Docker installation
2. Dotfile initialization
3. lazydocker installation
4. ytgo
q. Quit"
read -r _db </dev/tty
case "$_db" in
1)
_inst_docker
;;
2)
_init_dotfiles
;;
3)
_inst_lazydocker
;;
4)
_ytgo
;;
q)
exit 1
;;
esac
}
main() {
# set -x
if check_root; then
get_packager
_dashboard
fi
}
main

View file

@ -0,0 +1,33 @@
#!/bin/sh -e
. ../common-script.sh
removeSnaps() {
if command_exists snap; then
case "$PACKAGER" in
pacman)
"$ESCALATION_TOOL" "$PACKAGER" -Rns snapd
;;
apt-get|nala)
"$ESCALATION_TOOL" "$PACKAGER" autoremove --purge snapd
if [ "$ID" = ubuntu ]; then
"$ESCALATION_TOOL" apt-mark hold snapd
fi
;;
dnf|zypper)
"$ESCALATION_TOOL" "$PACKAGER" remove snapd
;;
*)
printf "%b\n" "${RED}Unsupported package manager: ""$PACKAGER""${RC}"
exit 1
;;
esac
printf "%b\n" "${GREEN}Successfully removed snaps.${RC}"
else
printf "%b\n" "${GREEN}Snapd is not installed.${RC}"
fi
}
checkEnv
checkEscalationTool
removeSnaps

View file

@ -0,0 +1,71 @@
#!/bin/sh -e
. ../common-script.sh
cleanup_system() {
printf "%b\n" "${YELLOW}Performing system cleanup...${RC}"
case "$PACKAGER" in
apt-get|nala)
"$ESCALATION_TOOL" "$PACKAGER" clean
"$ESCALATION_TOOL" "$PACKAGER" autoremove -y
"$ESCALATION_TOOL" "$PACKAGER" autoclean
"$ESCALATION_TOOL" du -h /var/cache/apt
"$ESCALATION_TOOL" "$PACKAGER" clean
;;
zypper)
"$ESCALATION_TOOL" "$PACKAGER" clean -a
"$ESCALATION_TOOL" "$PACKAGER" tidy
"$ESCALATION_TOOL" "$PACKAGER" cc -a
;;
dnf)
"$ESCALATION_TOOL" "$PACKAGER" clean all
"$ESCALATION_TOOL" "$PACKAGER" autoremove -y
;;
pacman)
"$ESCALATION_TOOL" "$PACKAGER" -Sc --noconfirm
"$ESCALATION_TOOL" "$PACKAGER" -Rns $(pacman -Qtdq) --noconfirm > /dev/null 2>&1
;;
*)
printf "%b\n" "${RED}Unsupported package manager: ${PACKAGER}. Skipping.${RC}"
;;
esac
}
common_cleanup() {
if [ -d /var/tmp ]; then
"$ESCALATION_TOOL" find /var/tmp -type f -atime +5 -delete
fi
if [ -d /tmp ]; then
"$ESCALATION_TOOL" find /tmp -type f -atime +5 -delete
fi
if [ -d /var/log ]; then
"$ESCALATION_TOOL" find /var/log -type f -name "*.log" -exec truncate -s 0 {} \;
fi
"$ESCALATION_TOOL" journalctl --vacuum-time=3d
}
clean_data() {
printf "%b" "${YELLOW}Clean up old cache files and empty the trash? (y/N): ${RC}"
read -r clean_response
case $clean_response in
y|Y)
printf "%b\n" "${YELLOW}Cleaning up old cache files and emptying trash...${RC}"
if [ -d "$HOME/.cache" ]; then
find "$HOME/.cache/" -type f -atime +5 -delete
fi
if [ -d "$HOME/.local/share/Trash" ]; then
find "$HOME/.local/share/Trash" -mindepth 1 -delete
fi
printf "%b\n" "${GREEN}Cache and trash cleanup completed.${RC}"
;;
*)
printf "%b\n" "${YELLOW}Skipping cache and trash cleanup.${RC}"
;;
esac
}
checkEnv
checkEscalationTool
cleanup_system
common_cleanup
clean_data

View file

@ -0,0 +1,106 @@
#!/bin/sh -e
. ../common-script.sh
fastUpdate() {
case "$PACKAGER" in
pacman)
$AUR_HELPER -S --needed --noconfirm rate-mirrors-bin
printf "%b\n" "${YELLOW}Generating a new list of mirrors using rate-mirrors. This process may take a few seconds...${RC}"
if [ -s /etc/pacman.d/mirrorlist ]; then
"$ESCALATION_TOOL" cp /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.bak
fi
# If for some reason DTYPE is still unknown use always arch so the rate-mirrors does not fail
dtype_local=${DTYPE}
if [ "${DTYPE}" = "unknown" ]; then
dtype_local="arch"
fi
"$ESCALATION_TOOL" rate-mirrors --top-mirrors-number-to-retest=5 --disable-comments --save /etc/pacman.d/mirrorlist --allow-root ${dtype_local}
if [ $? -ne 0 ] || [ ! -s /etc/pacman.d/mirrorlist ]; then
printf "%b\n" "${RED}Rate-mirrors failed, restoring backup.${RC}"
"$ESCALATION_TOOL" cp /etc/pacman.d/mirrorlist.bak /etc/pacman.d/mirrorlist
fi
;;
apt-get|nala)
"$ESCALATION_TOOL" apt-get update
if ! command_exists nala; then
"$ESCALATION_TOOL" apt-get install -y nala || { printf "%b\n" "${YELLOW}Falling back to apt-get${RC}"; PACKAGER="apt-get"; }
fi
if [ "$PACKAGER" = "nala" ]; then
"$ESCALATION_TOOL" cp /etc/apt/sources.list /etc/apt/sources.list.bak
"$ESCALATION_TOOL" nala update
PACKAGER="nala"
fi
"$ESCALATION_TOOL" "$PACKAGER" upgrade -y
;;
dnf)
"$ESCALATION_TOOL" "$PACKAGER" update -y
;;
zypper)
"$ESCALATION_TOOL" "$PACKAGER" ref
"$ESCALATION_TOOL" "$PACKAGER" --non-interactive dup
;;
*)
printf "%b\n" "${RED}Unsupported package manager: "$PACKAGER"${RC}"
exit 1
;;
esac
}
updateSystem() {
printf "%b\n" "${GREEN}Updating system${RC}"
case "$PACKAGER" in
apt-get|nala)
"$ESCALATION_TOOL" "$PACKAGER" update
"$ESCALATION_TOOL" "$PACKAGER" upgrade -y
;;
dnf)
"$ESCALATION_TOOL" "$PACKAGER" update -y
"$ESCALATION_TOOL" "$PACKAGER" upgrade -y
;;
pacman)
"$ESCALATION_TOOL" "$PACKAGER" -Sy --noconfirm --needed archlinux-keyring
"$ESCALATION_TOOL" "$PACKAGER" -Su --noconfirm
;;
zypper)
"$ESCALATION_TOOL" "$PACKAGER" ref
"$ESCALATION_TOOL" "$PACKAGER" --non-interactive dup
;;
*)
printf "%b\n" "${RED}Unsupported package manager: "$PACKAGER"${RC}"
exit 1
;;
esac
}
updateFlatpaks() {
if command_exists flatpak; then
printf "%b\n" "${YELLOW}Updating installed Flathub apps...${RC}"
installed_apps=$(flatpak list --app --columns=application)
if [ -z "$installed_apps" ]; then
printf "%b\n" "${RED}No Flathub apps are installed.${RC}"
return
fi
for app in $installed_apps; do
printf "%b\n" "${YELLOW}Updating $app...${RC}"
flatpak update -y "$app"
done
fi
}
checkEnv
checkAURHelper
checkEscalationTool
fastUpdate
updateSystem
updateFlatpaks

View file

@ -0,0 +1,102 @@
name = "System Setup"
multi_selectable = false
[[data]]
name = "Arch Linux"
[[data.preconditions]]
matches = true
data = "command_exists"
values = ["pacman"]
[[data.entries]]
name = "Arch Server Setup"
description = "This command installs a minimal arch server setup under 5 minutes."
script = "arch/server-setup.sh"
task_list = "SI D"
[[data.entries]]
name = "Paru AUR Helper"
description = "Paru is your standard pacman wrapping AUR helper with lots of features and minimal interaction.\nTo know more about AUR helpers visit: https://wiki.archlinux.org/title/AUR_helpers"
script = "arch/paru-setup.sh"
task_list = "I"
[[data.entries]]
name = "Yay AUR Helper"
description = "Yet Another Yogurt - An AUR Helper Written in Go.\nTo know more about AUR helpers visit: https://wiki.archlinux.org/title/AUR_helpers"
script = "arch/yay-setup.sh"
task_list = "I"
[[data]]
name = "Fedora"
[[data.preconditions]]
matches = true
data = "command_exists"
values = ["dnf"]
[[data.entries]]
name = "Configure DNF"
description = "Optimizes DNF for parallel downloads"
script = "fedora/configure-dnf.sh"
task_list = "PFM"
[[data.entries]]
name = "Multimedia Codecs"
description = "This script is designed to install multimedia codecs, and to ensure RPM Fusion repositories are installed."
script = "fedora/multimedia-codecs.sh"
task_list = "I"
[[data.entries]]
name = "Nvidia Proprietary Drivers"
description = "This script is designed to download the proprietary NVIDIA drivers in Fedora."
script = "fedora/nvidia-proprietary-driver-setup.sh"
task_list = "I"
[[data.entries]]
name = "RPM Fusion"
description = "RPM Fusion provides software that the Fedora Project or Red Hat doesn't want to ship.\nThat software is provided as precompiled RPMs for all current Fedora versions and current Red Hat Enterprise Linux or clones versions; you can use the RPM Fusion repositories with tools like yum and PackageKit.\nFor more information visit: https://rpmfusion.org/"
script = "fedora/rpm-fusion-setup.sh"
task_list = "MP"
[[data.entries]]
name = "Virtualization"
description = "Enables Virtualization through dnf"
script = "fedora/virtualization.sh"
task_list = "I"
[[data]]
name = "Full System Cleanup"
description = "This script is designed to remove unnecessary packages, clean old cache files, remove temporary files, and to empty the trash."
script = "system-cleanup.sh"
task_list = "RP PFM"
[[data]]
name = "Full System Update"
description = "This command updates your system to the latest packages available for your distro"
script = "system-update.sh"
task_list = "PFM"
[[data]]
name = "Gaming Dependencies"
description = "This script is designed to handle the installation of gaming dependencies across different Linux distributions"
script = "gaming-setup.sh"
task_list = "I"
[[data]]
name = "Postinstallation Script"
description = "This script is designed to handle the installation of various software dependencies across different Linux distributions"
script = "postinstall.sh"
task_list = "I"
[[data]]
name = "Remove Snaps"
description = "This script is designed to remove snap"
script = "remove-snaps.sh"
task_list = "RP"
[[data]]
name = "TTY Fonts"
description = "This Script will set the default TTY font to Terminus size 32 Bold"
script = "terminus-tty.sh"
task_list = "I PFM"

View file

@ -0,0 +1,66 @@
#!/bin/sh -e
. ../common-script.sh
InstallTermiusFonts() {
if [ ! -f "/usr/share/kbd/consolefonts/ter-c18b.psf.gz" ] &&
[ ! -f "/usr/share/consolefonts/Uni3-TerminusBold18x10.psf.gz" ] &&
[ ! -f "/usr/lib/kbd/consolefonts/ter-p32n.psf.gz" ]; then
printf "%b\n" "${YELLOW}Installing Terminus Fonts...${RC}"
case "$PACKAGER" in
pacman)
"$ESCALATION_TOOL" "$PACKAGER" -S --needed --noconfirm terminus-font
;;
apt-get|nala)
"$ESCALATION_TOOL" "$PACKAGER" install -y fonts-terminus
;;
dnf)
"$ESCALATION_TOOL" "$PACKAGER" install -y terminus-fonts-console
;;
*)
printf "%b\n" "${RED}Unsupported package manager: ""$PACKAGER""${RC}"
exit 1
;;
esac
else
printf "%b\n" "${GREEN}Terminus Fonts is already installed.${RC}"
fi
}
SetTermiusFonts() {
case "$DTYPE" in
arch)
printf "%b\n" "${YELLOW}Updating FONT= line in /etc/vconsole.conf...${RC}"
"$ESCALATION_TOOL" sed -i 's/^FONT=.*/FONT=ter-v32b/' /etc/vconsole.conf
if [ -z "$DISPLAY" ] && [ -z "$WAYLAND_DISPLAY" ]; then
"$ESCALATION_TOOL" setfont -C /dev/tty1 ter-v32b
fi
printf "%b\n" "${GREEN}Terminus font set for TTY.${RC}"
;;
debian)
printf "%b\n" "${YELLOW}Updating console-setup configuration...${RC}"
"$ESCALATION_TOOL" sed -i 's/^CODESET=.*/CODESET="guess"/' /etc/default/console-setup
"$ESCALATION_TOOL" sed -i 's/^FONTFACE=.*/FONTFACE="TerminusBold"/' /etc/default/console-setup
"$ESCALATION_TOOL" sed -i 's/^FONTSIZE=.*/FONTSIZE="16x32"/' /etc/default/console-setup
printf "%b\n" "${GREEN}Console-setup configuration updated for Terminus font.${RC}"
# Editing console-setup requires initramfs to be regenerated
"$ESCALATION_TOOL" update-initramfs -u
if [ -z "$DISPLAY" ] && [ -z "$WAYLAND_DISPLAY" ]; then
"$ESCALATION_TOOL" setfont -C /dev/tty1 /usr/share/consolefonts/Uni3-TerminusBold32x16.psf.gz
fi
printf "%b\n" "${GREEN}Terminus font has been set for TTY.${RC}"
;;
fedora)
printf "%b\n" "${YELLOW}Updating FONT= line in /etc/vconsole.conf...${RC}"
"$ESCALATION_TOOL" sed -i 's/^FONT=.*/FONT=ter-v32b/' /etc/vconsole.conf
if [ -z "$DISPLAY" ] && [ -z "$WAYLAND_DISPLAY" ]; then
"$ESCALATION_TOOL" setfont -C /dev/tty1 ter-v32b
fi
printf "%b\n" "${GREEN}Terminus font has been set for TTY.${RC}"
;;
esac
}
checkEnv
InstallTermiusFonts
SetTermiusFonts

7
core/tabs/tabs.toml Normal file
View file

@ -0,0 +1,7 @@
directories = [
"applications-setup",
# "gaming",
# "security",
"system-setup",
"utils"
]

View file

@ -0,0 +1,175 @@
#!/bin/sh -e
. ../common-script.sh
# Function to list common session options
list_sessions() {
printf "%b\n" "Select the session:"
printf "%b\n" "1) GNOME (gnome.desktop)"
printf "%b\n" "2) KDE Plasma (plasma.desktop)"
printf "%b\n" "3) XFCE (xfce.desktop)"
printf "%b\n" "4) LXDE (LXDE.desktop)"
printf "%b\n" "5) LXQt (lxqt.desktop)"
printf "%b\n" "6) Cinnamon (cinnamon.desktop)"
printf "%b\n" "7) MATE (mate.desktop)"
printf "%b\n" "8) Openbox (openbox.desktop)"
printf "%b\n" "9) i3 (i3.desktop)"
printf "%b\n" "10) Custom session"
printf "%b" "Enter your choice (1-10): "
read -r session_choice
case "$session_choice" in
1) session="gnome.desktop" ;;
2) session="plasma.desktop" ;;
3) session="xfce.desktop" ;;
4) session="LXDE.desktop" ;;
5) session="lxqt.desktop" ;;
6) session="cinnamon.desktop" ;;
7) session="mate.desktop" ;;
8) session="openbox.desktop" ;;
9) session="i3.desktop" ;;
10)
printf "%b" "Enter custom session name (e.g., mysession): "
read -r session ;;
*)
printf "%b\n" "Invalid option selected."
exit 1 ;;
esac
}
# Function to configure LightDM
configure_lightdm() {
printf "%b\n" "Configuring LightDM for autologin..."
printf "%b" "Enter username for LightDM autologin: "
read -r user
printf "%b\n" '[Seat:*]' | "$ESCALATION_TOOL" tee -a /etc/lightdm/lightdm.conf
printf "%s\n" "autologin-user=$user" | "$ESCALATION_TOOL" tee -a /etc/lightdm/lightdm.conf
printf "%b\n" 'autologin-user-timeout=0' | "$ESCALATION_TOOL" tee -a /etc/lightdm/lightdm.conf
printf "%b\n" "LightDM has been configured for autologin."
}
# Function to remove LightDM autologin
remove_lightdm_autologin() {
printf "%b\n" "Removing LightDM autologin configuration..."
"$ESCALATION_TOOL" sed -i'' '/^\[Seat:\*]/d' /etc/lightdm/lightdm.conf
"$ESCALATION_TOOL" sed -i'' '/^autologin-/d' /etc/lightdm/lightdm.conf
printf "%b\n" "LightDM autologin configuration has been removed."
}
# Function to configure GDM
configure_gdm() {
printf "%b\n" "Configuring GDM for autologin..."
printf "%b" "Enter username for GDM autologin: "
read -r user
printf "%b\n" '[daemon]' | "$ESCALATION_TOOL" tee -a /etc/gdm/custom.conf
printf "%b\n" 'AutomaticLoginEnable = true' | "$ESCALATION_TOOL" tee -a /etc/gdm/custom.conf
printf "%s\n" "AutomaticLogin = $user" | "$ESCALATION_TOOL" tee -a /etc/gdm/custom.conf
printf "%b\n" "GDM has been configured for autologin."
}
# Function to remove GDM autologin
remove_gdm_autologin() {
printf "%b\n" "Removing GDM autologin configuration..."
"$ESCALATION_TOOL" sed -i'' '/AutomaticLoginEnable/d' /etc/gdm/custom.conf
"$ESCALATION_TOOL" sed -i'' '/AutomaticLogin/d' /etc/gdm/custom.conf
printf "%b\n" "GDM autologin configuration has been removed."
}
# Function to configure SDDM
configure_sddm() {
printf "%b\n" "Configuring SDDM for autologin..."
printf "%b" "Enter username for SDDM autologin: "
read -r user
list_sessions # Show session options
printf "%b\n" '[Autologin]' | "$ESCALATION_TOOL" tee -a /etc/sddm.conf
printf "%s\n" "User=$user" | "$ESCALATION_TOOL" tee -a /etc/sddm.conf
printf "%s\n" "Session=$session" | "$ESCALATION_TOOL" tee -a /etc/sddm.conf
printf "%b\n" "SDDM has been configured for autologin."
}
# Function to remove SDDM autologin
remove_sddm_autologin() {
printf "%b\n" "Removing SDDM autologin configuration..."
"$ESCALATION_TOOL" sed -i'' '/\[Autologin\]/,+2d' /etc/sddm.conf
printf "%b\n" "SDDM autologin configuration has been removed."
}
# Function to configure LXDM
configure_lxdm() {
printf "%b\n" "Configuring LXDM for autologin..."
printf "%b" "Enter username for LXDM autologin: "
read -r user
list_sessions # Show session options
"$ESCALATION_TOOL" sed -i'' "s/^#.*autologin=.*$/autologin=${user}/" /etc/lxdm/lxdm.conf
"$ESCALATION_TOOL" sed -i'' "s|^#.*session=.*$|session=/usr/bin/${session}|; s|^session=.*$|session=/usr/bin/${session}|" /etc/lxdm/lxdm.conf
printf "%b\n" "LXDM has been configured for autologin."
}
# Function to remove LXDM autologin
remove_lxdm_autologin() {
printf "%b\n" "Removing LXDM autologin configuration..."
"$ESCALATION_TOOL" sed -i'' "s/^autologin=.*$/#autologin=/" /etc/lxdm/lxdm.conf
"$ESCALATION_TOOL" sed -i'' "s/^session=.*$/#session=/" /etc/lxdm/lxdm.conf
printf "%b\n" "LXDM autologin configuration has been removed."
}
# Function to configure or remove autologin based on user choice
configure_or_remove_autologin() {
printf "%b\n" "Do you want to add or remove autologin?"
printf "%b\n" "1) Add autologin"
printf "%b\n" "2) Remove autologin"
printf "%b" "Enter your choice (1-2): "
read -r action_choice
if [ "$action_choice" = "1" ]; then
printf "%b\n" "Choose the display manager to configure:"
printf "%b\n" "1) LightDM"
printf "%b\n" "2) GDM"
printf "%b\n" "3) SDDM"
printf "%b\n" "4) LXDM"
printf "%b" "Enter your choice (1-4): "
read -r choice
case "$choice" in
1) configure_lightdm ;;
2) configure_gdm ;;
3) configure_sddm ;;
4) configure_lxdm ;;
*) printf "%b\n" "Invalid option selected." ;;
esac
elif [ "$action_choice" = "2" ]; then
printf "%b\n" "Choose the display manager to remove autologin:"
printf "%b\n" "1) LightDM"
printf "%b\n" "2) GDM"
printf "%b\n" "3) SDDM"
printf "%b\n" "4) LXDM"
printf "%b" "Enter your choice (1-4): "
read -r choice
case "$choice" in
1) remove_lightdm_autologin ;;
2) remove_gdm_autologin ;;
3) remove_sddm_autologin ;;
4) remove_lxdm_autologin ;;
*) printf "%b\n" "Invalid option selected." ;;
esac
else
printf "%b\n" "Invalid choice. Exiting..."
exit 1
fi
printf "%b\n" "Action completed. Exiting..."
exit 0
}
checkEnv
checkEscalationTool
configure_or_remove_autologin

62
core/tabs/utils/ssh-keyperm.sh Executable file
View file

@ -0,0 +1,62 @@
#!/bin/sh
# ssh-permissions script for linux
# ─< ANSI color codes >───────────────────────────────────────────────────────────────────
RED='\033[0;31m'
CYAN='\033[0;36m'
YELLOW='\033[0;33m'
LIGHT_GREEN='\033[0;92m'
BOLD='\033[1m'
NC='\033[0m' # No Color
echo_error() {
printf "${BOLD}${RED}ERROR: ${NC}${RED}%s${NC}\n" "$1" >&2
}
echo_info() {
printf "${BOLD}${CYAN}INFO: ${NC}${CYAN}%s${NC}\n" "$1"
}
echo_warning() {
printf "${BOLD}${YELLOW}WARNING: ${NC}${YELLOW}%s${NC}\n" "$1"
}
echo_note() {
printf "${BOLD}${LIGHT_GREEN}NOTE: ${NC}${LIGHT_GREEN}%s${NC}\n" "$1"
}
# ─< Check if the user is root and set sudo variable if necessary >───────────────────────
check_root() {
if [ "$(id -u)" -ne 0 ]; then
if command -v sudo >/dev/null; then
echo_info "User is not root. Using sudo for privileged operations."
_sudo="sudo"
else
echo_error "No sudo found and you're not root! Can't install packages."
return 1
fi
else
echo_note "Root access confirmed."
_sudo=""
fi
}
set_perm() {
check_root
if [[ -d "$HOME/.ssh" ]]; then
echo_note "chmod 700 $HOME/.ssh"
"$_sudo" chmod 700 $HOME/.ssh >/dev/null 2>&1
if ls $HOME/.ssh/*.pub >/dev/null 2>&1; then
echo_note "chmod 600 $HOME/.ssh/*id*"
"$_sudo" chmod 600 $HOME/.ssh/*id* >/dev/null 2>&1
echo_note "chmod 666 $HOME/.ssh/*.pub"
"$_sudo" chmod 666 $HOME/.ssh/*.pub >/dev/null 2>&1
else
echo_error "There is no *.pub file in the $HOME/.ssh/ directory! Aborting now!"
fi
else
echo_error "No .ssh folder found in $HOME - exiting now!"
exit 1
fi
}
set_perm

View file

@ -0,0 +1,13 @@
name = "Utilities"
multi_selectable = false
[[data]]
name = "Auto Login"
script = "auto-login.sh"
task_list = "DE setup"
[[data]]
name = "SSH Permissions"
script = "ssh-keyperm.sh"
description = "This script will set the SSH permissions"
task_list = "I"

4
docs/KnownIssues.md Normal file
View file

@ -0,0 +1,4 @@
# Known Issues
---
- [Known Issues](https://github.com/ChrisTitusTech/linutil/issues)

BIN
docs/assets/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

BIN
docs/assets/preview.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

89
docs/assets/preview.tape Normal file
View file

@ -0,0 +1,89 @@
# VHS documentation
#
# Output:
# Output <path>.gif Create a GIF output at the given <path>
# Output <path>.mp4 Create an MP4 output at the given <path>
# Output <path>.webm Create a WebM output at the given <path>
#
# Require:
# Require <string> Ensure a program is on the $PATH to proceed
#
# Settings:
# Set FontSize <number> Set the font size of the terminal
# Set FontFamily <string> Set the font family of the terminal
# Set Height <number> Set the height of the terminal
# Set Width <number> Set the width of the terminal
# Set LetterSpacing <float> Set the font letter spacing (tracking)
# Set LineHeight <float> Set the font line height
# Set LoopOffset <float>% Set the starting frame offset for the GIF loop
# Set Theme <json|string> Set the theme of the terminal
# Set Padding <number> Set the padding of the terminal
# Set Framerate <number> Set the framerate of the recording
# Set PlaybackSpeed <float> Set the playback speed of the recording
# Set MarginFill <file|#000000> Set the file or color the margin will be filled with.
# Set Margin <number> Set the size of the margin. Has no effect if MarginFill isn't set.
# Set BorderRadius <number> Set terminal border radius, in pixels.
# Set WindowBar <string> Set window bar type. (one of: Rings, RingsRight, Colorful, ColorfulRight)
# Set WindowBarSize <number> Set window bar size, in pixels. Default is 40.
# Set TypingSpeed <time> Set the typing speed of the terminal. Default is 50ms.
#
# Sleep:
# Sleep <time> Sleep for a set amount of <time> in seconds
#
# Type:
# Type[@<time>] "<characters>" Type <characters> into the terminal with a
# <time> delay between each character
#
# Keys:
# Escape[@<time>] [number] Press the Escape key
# Backspace[@<time>] [number] Press the Backspace key
# Delete[@<time>] [number] Press the Delete key
# Insert[@<time>] [number] Press the Insert key
# Down[@<time>] [number] Press the Down key
# Enter[@<time>] [number] Press the Enter key
# Space[@<time>] [number] Press the Space key
# Tab[@<time>] [number] Press the Tab key
# Left[@<time>] [number] Press the Left Arrow key
# Right[@<time>] [number] Press the Right Arrow key
# Up[@<time>] [number] Press the Up Arrow key
# Down[@<time>] [number] Press the Down Arrow key
# PageUp[@<time>] [number] Press the Page Up key
# PageDown[@<time>] [number] Press the Page Down key
# Ctrl+<key> Press the Control key + <key> (e.g. Ctrl+C)
#
# Display:
# Hide Hide the subsequent commands from the output
# Show Show the subsequent commands in the output
Output preview.gif
Require linutil
Require sh
Set Shell "bash"
Set FontFamily "JetBrainsMono Nerd Font"
Set FontSize 24
Set Width 1920
Set Height 1080
Sleep 1s
Type "linutil" Sleep 1s Enter
Sleep 5s
Left Sleep 2s
Down Sleep 1s
Down Sleep 1s
Down Sleep 1s
Down Sleep 2s
Right Sleep 3s
Type "/" Sleep 1s
Type@200ms "System Cleanup" Sleep 1s Enter
Sleep 2s
Enter Sleep 3s
Type "y" Sleep 15s # CONFIRMATION PROMPT
Escape

72
docs/contributing.md Normal file
View file

@ -0,0 +1,72 @@
<!-- THIS FILE IS GENERATED AUTOMATICALLY. EDIT .github/CONTRIBUTING.md -->
# Contributing Guidelines for Linutil
Thank you for considering contributing to Linutil! We appreciate your effort in helping improve this project. To ensure that your contributions align with the goals and quality standards of Linutil, please follow these guidelines:
## 1. **Install Rust**:
Make sure you have Rust installed on your machine. You can install it by following the instructions at [rust-lang.org](https://www.rust-lang.org/tools/install).
## 2. **Fork and Clone the repo**
1. Make a fork of the repo in GitHub
2. Clone the fork
```bash
git clone https://github.com/YOUR_USERNAME_HERE/linutil.git
cd linutil
```
## 3. Make your changes
- **Edit the files you want to change**: Make your changes to the relevant files.
- **Test your changes**: Run `cargo run` to test your modifications in a local environment and ensure everything works as expected.
## 4. Understand the existing code
- **Have a clear reason**: Dont change the way things are done without a valid reason. If you propose an alteration, be prepared to explain why its necessary and how it improves the project.
- **Respect existing conventions**: Changes should align with the existing code style, design patterns, and overall project philosophy. If you want to introduce a new way of doing things, justify it clearly.
## 5. Learn from Past Pull Requests (PRs)
- **Check merged PRs**: Reviewing merged pull requests can give you an idea of what kind of contributions are accepted and how they are implemented.
- **Study rejected PRs**: This is especially important as it helps you avoid making similar mistakes or proposing changes that have already been considered and declined.
## 6. Write Clean, Descriptive Commit Messages
- **Be descriptive**: Your commit messages should clearly describe what the change does and why it was made.
- **Use the imperative mood**: For example, "Add feature X" or "Fix bug in Y", rather than "Added feature X" or "Fixed bug in Y".
- **Keep commits clean**: Avoid committing a change and then immediately following it with a fix for that change. Instead, amend your commit or squash it if needed.
## 7. Keep Your Pull Requests (PRs) Small and Focused
- **Make small, targeted PRs**: Focus on one feature or fix per pull request. This makes it easier to review and increases the likelihood of acceptance.
- **Avoid combining unrelated changes**: PRs that tackle multiple unrelated issues are harder to review and might be rejected because of a single problem.
## 8. Understand and Test the Code You Write
- **Review your code**: Before submitting your changes, take the time to review your code for readability, efficiency and performance. Consider how your changes affect the project.
- **Avoid using LLMs**: Don't submit AI-generated code without reviewing and testing it first. Ensure that any code you submit is thoroughly understood and meets the project's standards.
- **Testing Requirements**: Failure to conduct testing after multiple requests may result in the closure of your Pull Request.
## 9. Code Review and Feedback
- **Expect feedback**: PRs will undergo code review. Be open to feedback and willing to make adjustments as needed.
- **Participate in reviews**: If you feel comfortable, review other contributors' PRs as well. Peer review is a great way to learn and ensure high-quality contributions.
## 10. Contributing Is More Than Just Code
- **Test the tool**: Running tests and providing feedback on how the tool works in different environments is a valuable contribution.
- **Write well-formed issues**: Clearly describe bugs or problems you encounter, providing as much detail as possible, including steps to reproduce the issue.
- **Propose reasonable feature requests**: When suggesting new features, ensure they fit within the scope, style, and design of the project. Provide clear reasoning and use cases.
## 11. Documentation
- **Update the documentation**: If your change affects the functionality, please update the relevant documentation files to reflect this.
- **Automatic generation**: If you decide to add functionality through a new shell script, make sure to fill out all fields in `tab_data.toml` and run `cargo xtask docgen`.
## 12. License
- **Agree to the license**: By contributing to Linutil, you agree that your contributions will be licensed under the project's MIT license.
We appreciate your contributions and look forward to collaborating with you to make Linutil better!

4
docs/faq.md Normal file
View file

@ -0,0 +1,4 @@
# FAQ's
## How do I uninstall LinUtil?
* You do not have to uninstall LinUtil. As it is a script you run from your terminal it only loads into your RAM. This means as soon as you close LinUtil it will be deleted off your system.

76
docs/index.md Normal file
View file

@ -0,0 +1,76 @@
# Welcome to the LinUtil Documentation!
[![Version](https://img.shields.io/github/v/release/ChrisTitusTech/linutil?color=%230567ff&label=Latest%20Release&style=for-the-badge)](https://github.com/ChrisTitusTech/linutil/releases/latest)
![GitHub Downloads (specific asset, all releases)](https://img.shields.io/github/downloads/ChrisTitusTech/linutil/linutil?label=Total%20Downloads&style=for-the-badge)
[![](https://dcbadge.limes.pink/api/server/https://discord.gg/bujFYKAHSp)](https://discord.gg/bujFYKAHSp)
[![Crates.io Version](https://img.shields.io/crates/v/linutil_tui?style=for-the-badge&color=%23af3a03)](https://crates.io/crates/linutil_tui) [![linutil AUR Version](https://img.shields.io/aur/version/linutil?style=for-the-badge&label=%5BAUR%5D%20linutil&color=%23230567ff)](https://aur.archlinux.org/packages/linutil) [![linutil-bin AUR Version](https://img.shields.io/aur/version/linutil-bin?style=for-the-badge&label=%5BAUR%5D%20linutil-bin&color=%23230567ff)](https://aur.archlinux.org/packages/linutil-bin)
## Running the latest release of LinUtil
To get started, run the following command in your terminal:
### Stable branch
```
curl -fsSL https://christitus.com/linux | sh
```
---
### Installation
LinUtil is also available as a package in various repositories:
[![Packaging status](https://repology.org/badge/vertical-allrepos/linutil.svg)](https://repology.org/project/linutil/versions)
<details>
<summary>Arch Linux</summary>
LinUtil can be installed on [Arch Linux](https://archlinux.org) with three different [AUR](https://aur.archlinux.org) packages:
- `linutil` - Stable release compiled from source
- `linutil-bin` - Stable release pre-compiled
- `linutil-git` - Compiled from the last commit (not recommended)
by running:
```bash
git clone https://aur.archlinux.org/<package>.git
cd linutil
makepkg -si
```
Replace `<package>` with your preferred package.
If you use [yay](https://github.com/Jguer/yay), [paru](https://github.com/Morganamilo/paru) or any other [AUR Helper](https://wiki.archlinux.org/title/AUR_helpers), it's even simpler:
```bash
paru -S linutil
```
Replace `paru` with your preferred helper and `linutil` with your preferred package.
</details>
<details>
<summary>Cargo</summary>
LinUtil can be installed via [Cargo](https://doc.rust-lang.org/cargo) with:
```bash
cargo install linutil
```
Note that crates installed using `cargo install` require manual updating with `cargo install --force` (update functionality is [included in LinUtil](https://christitustech.github.io/linutil/userguide/#applications-setup))
</details>
---
After you've ran the command, you should see a GUI on your screen; It will look something like this:
![preview](assets/preview.gif)
!!! info
LinUtil is updated weekly as of the time of writing. Consequently, features and functionalities may evolve, and the documentation may not always reflect the most current images or information.

23
docs/roadmap.md Normal file
View file

@ -0,0 +1,23 @@
# Roadmap
## Vision
- To simplify linux tasks for all users for all distributions; Easily, efficiently, and effortlessly.
## Goals
- [ ] Focus on tasks that take time in Linux and automate them. (Example: Removing a user, adding a user, etc. - but mostly BASH scripts with POSIX compliance.)
- [ ] Remove Binary linutil from being tracked in git and make it a github action.
- [ ] Document every function and feature of linutil. (Preview panel description addition)
- [x] Create a discord server for linutil and invite the community.
- [ ] Power Optimizations for Laptops
## Milestones
### Q3 2024
- [ ] Finish the foundation of the project in CLI mode.
- [ ] DENY ALL GUI Pull Requests while CLI and foundation is being established.
### Q4 2024
- [ ] GUI Brainstorming and Planning
- [ ] GUI Implementation towards the end of Q4
## Community Feedback
- Encourage community input and suggestions for future development.

151
docs/userguide.md Normal file
View file

@ -0,0 +1,151 @@
<!-- THIS FILE IS GENERATED BY cargo xtask docgen -->
# Walkthrough
## Applications Setup
### Developer Tools
- **Github Desktop**: GitHub Desktop is a user-friendly application that simplifies the process of managing Git repositories and interacting with GitHub, providing a graphical interface for tasks like committing, branching, and syncing changes.
- **Neovim**: Neovim is a refactor, and sometimes redactor, in the tradition of Vim.
It is not a rewrite but a continuation and extension of Vim.
This command configures neovim from CTT's neovim configuration.
https://github.com/ChrisTitusTech/neovim
- **Sublime Text**: Sublime Text is a fast, lightweight, and customizable text editor known for its simplicity, powerful features, and wide range of plugins for various programming languages.
- **VS Code**: Visual Studio Code (VS Code) is a lightweight, open-source code editor with built-in support for debugging, version control, and extensions for various programming languages and frameworks.
- **VS Codium**: VSCodium is a free, open-source version of Visual Studio Code (VS Code) that removes Microsoft-specific telemetry and branding.
- **Meld**: Meld is a visual diff and merge tool that helps compare files, directories, and version-controlled projects.
- **Ngrok**: Ngrok is a tool that creates secure, temporary tunnels to expose local servers to the internet for testing and development.
### Communication Apps
- **Discord**: Discord is a versatile communication platform for gamers and communities, offering voice, video, and text chat features.
- **Jitsi**: Jitsi Meet is an open-source video conferencing tool that allows users to host and join secure meetings directly from their web browsers without the need for downloads.
- **Signal**: Signal is a privacy-focused messaging app that provides end-to-end encryption for secure text, voice, and video communication.
- **Slack**: Slack is a collaboration platform designed for team communication, featuring channels, direct messaging, file sharing, and integrations with various productivity tools.
- **Telegram**: Telegram is a cloud-based messaging app known for its speed and security, offering features like group chats, channels, and end-to-end encrypted calls.
- **Zoom**: Zoom is a widely-used video conferencing platform that allows users to host virtual meetings, webinars, and online collaboration with features like screen sharing and recording.
- **Thunderbird**: Thunderbird is a free, open-source email client that offers powerful features like customizable email management, a built-in calendar, and extensive add-ons for enhanced functionality.
### Office Suites
### PDF Suites
### Web Browsers
- **Brave**: Brave is a free and open-source web browser developed by Brave Software, Inc. based on the Chromium web browser.
- **Chromium**: Chromium is an open-source web browser project started by Google, to provide the source code for the proprietary Google Chrome browser.
- **Google Chrome**: Google Chrome is a fast, secure, and free web browser, built for the modern web.
- **LibreWolf**: LibreWolf is a fork of Firefox, focused on privacy, security, and freedom.
- **Lynx**: Lynx is a highly configurable text-based web browser for use on cursor-addressable character cell terminals.
- **Mozilla Firefox**: Mozilla Firefox is a free and open-source web browser developed by the Mozilla Foundation.
- **Thorium**: Thorium is a Chromium-based browser focused on privacy and performance.
- **Vivaldi**: Vivaldi is a freeware, cross-platform web browser developed by Vivaldi Technologies.
- **Alacritty**: Alacritty is a modern terminal emulator that comes with sensible defaults, but allows for extensive configuration. By integrating with other applications, rather than reimplementing their functionality, it manages to provide a flexible set of features with high performance. The supported platforms currently consist of BSD, Linux, macOS and Windows.
This command installs and condifures alacritty terminal emulator.
- **Android Debloater**: Universal Android Debloater (UAD) is a tool designed to help users remove bloatware and unnecessary pre-installed applications from Android devices, enhancing performance and user experience.
- **Bash Prompt**: The .bashrc file is a script that runs every time a new terminal session is started in Unix-like operating systems.
It is used to configure the shell session, set up aliases, define functions, and more, making the terminal easier to use and more powerful.
This command configures the key sections and functionalities defined in the .bashrc file from CTT's mybash repository.
https://github.com/ChrisTitusTech/mybash
- **Bottles**: Bottles allows Windows software, like applications and games, to run on Linux.
Bottles also provides tools to categorize, organize and optimize your applications.
- **DWM-Titus**: DWM is a dynamic window manager for X.
It manages windows in tiled, monocle and floating layouts.
All of the layouts can be applied dynamically, optimising the environment for the application in use and the task performed.
This command installs and configures DWM and a desktop manager.
The list of patches applied can be found in CTT's DWM repository
https://github.com/ChrisTitusTech/dwm-titus
- **Docker**: Docker is an open platform that uses OS-level virtualization to deliver software in packages called containers.
- **Fastfetch**: Fastfetch is a neofetch-like tool for fetching system information and displaying it prettily.
It is written mainly in C, with performance and customizability in mind.
This command installs fastfetch and configures from CTT's mybash repository.
https://github.com/ChrisTitusTech/mybash
- **Flatpak / Flathub**: Flatpak is a universal application sandbox for Linux that uses isolated packages from Flathub to prevent conflicts and system alterations, while alleviating dependency concerns.
This command installs Flatpak and adds the Flathub repository
- **Grub Theme**: Installs ChrisTitusTech's Top 5 Bootloader Themes script to allow for easy customization of GRUB.
- **Kitty**: kitty is a free and open-source GPU-accelerated terminal emulator for Linux, macOS, and some BSD distributions, focused on performance and features.
kitty is written in a mix of C and Python programming languages.
This command installs and configures kitty.
- **Linutil Installer**: Installs a distro-specific Linutil package locally.
- **Linutil Updater**: Updates your local Linutil crate installation.
- **Rofi**: Rofi is a window switcher, run dialog, ssh-launcher and dmenu replacement that started as a clone of simpleswitcher, written by Sean Pringle and later expanded by Dave Davenport.
This command installs and configures rofi with configuration from CTT's DWM repo.
https://github.com/ChrisTitusTech/dwm-titus
- **Waydroid**: Waydroid is an emulator that allows you to run Android apps and games on Linux.
- **ZSH Prompt**: The Z shell is a Unix shell that can be used as an interactive login shell and as a command interpreter for shell scripting. Zsh is an extended Bourne shell with many improvements, including some features of Bash, ksh, and tcsh.
This command installs ZSH prompt and provides basic configuration.
## Gaming
### Diablo II Resurrected
- **Loot Filter**: This is a loot filter for Diablo II Resurrected.
It's designed to be a simple, clean, and easy to read loot filter that highlights the most important items.
Works on battle.net and single player.
No frills, no config, just highlights high runes and other valuable items.
For more information visit: https://github.com/ChrisTitusTech/d2r-loot-filter
## Security
- **Firewall Baselines (CTT)**: Developed to ease iptables firewall configuration, UFW provides a user friendly way to create an IPv4 or IPv6 host-based firewall.
This command installs UFW and configures UFW based on CTT's recommended rules.
For more information visit: https://christitus.com/linux-security-mistakes
## System Setup
### Arch Linux
- **Arch Server Setup**: This command installs a minimal arch server setup under 5 minutes.
- **Paru AUR Helper**: Paru is your standard pacman wrapping AUR helper with lots of features and minimal interaction.
To know more about AUR helpers visit: https://wiki.archlinux.org/title/AUR_helpers
- **Yay AUR Helper**: Yet Another Yogurt - An AUR Helper Written in Go.
To know more about AUR helpers visit: https://wiki.archlinux.org/title/AUR_helpers
### Fedora
- **Configure DNF**: Optimizes DNF for parallel downloads
- **Multimedia Codecs**: This script is designed to install multimedia codecs, and to ensure RPM Fusion repositories are installed.
- **Nvidia Proprietary Drivers**: This script is designed to download the proprietary NVIDIA drivers in Fedora.
- **RPM Fusion**: RPM Fusion provides software that the Fedora Project or Red Hat doesn't want to ship.
That software is provided as precompiled RPMs for all current Fedora versions and current Red Hat Enterprise Linux or clones versions; you can use the RPM Fusion repositories with tools like yum and PackageKit.
For more information visit: https://rpmfusion.org/
- **Virtualization**: Enables Virtualization through dnf
- **Build Prerequisites**: This script is designed to handle the installation of various software dependencies across different Linux distributions
- **Full System Cleanup**: This script is designed to remove unnecessary packages, clean old cache files, remove temporary files, and to empty the trash.
- **Full System Update**: This command updates your system to the latest packages available for your distro
- **Gaming Dependencies**: This script is designed to handle the installation of gaming dependencies across different Linux distributions
- **Global Theme**: This script is designed to handle the installation and configuration of global theming
- **Remove Snaps**: This script is designed to remove snap
- **TTY Fonts**: This Script will set the default TTY font to Terminus size 32 Bold
## Utilities
### Monitor Control
- **Auto Detect Displays**: This script is designed to detect and apply recommended configuration for monitors connected with your system
- **Change Orientation**: This script is designed to change the orientation of monitors in your system
- **Disable Monitor**: This script is designed to disable a monitor in your system
- **Duplicate Displays**: This script is designed to duplicate display among multi-monitor setup in your system
- **Enable Monitor**: This script is designed to enable a monitor in your system
- **Extend Displays**: This script is designed to extend display among multi-monitor setup in your system
- **Manage Arrangement**: This script is designed to arrange monitors in multi-monitor setup in your system
- **Reset Scaling**: This script is designed to reset scaling of a monitor in your system
- **Scale Monitors**: This script is designed to change the scaling of monitors in your system
- **Set Brightness**: This script is designed to change the Brightness of monitors connected to your system
- **Set Primary Monitor**: This script is designed to set a Primary monitor in your system
- **Set Resolution**: This script is designed to change the resolution of monitors connected to your system
### User Account Manager
- **Auto Mount Drive**: This utility is designed to help with automating the process of mounting a drive on to your system.
- **Bluetooth Manager**: This utility is designed to manage bluetooth in your system
- **Numlock on Startup**: This utility is designed to configure auto enabling of numlock on boot
- **Ollama**: This utility is designed to manage ollama in your system
- **Service Manager**: This utility is designed to manage services in your system
- **WiFi Manager**: This utility is designed to manage wifi in your system

65
man/linutil.1 Normal file
View file

@ -0,0 +1,65 @@
.\" manpage for Linutil
.TH "linutil" "1" "October 2024" "" "Linutil Manual"
.SH NAME
linutil \- Chris Titus Tech's Linux Toolbox
.SH SYNOPSIS
\fBlinutil [OPTIONS]\fR
.SH DESCRIPTION
Linutil is a distro-agnostic toolbox designed to simplify everyday Linux tasks.
.br
It helps you set up applications and optimize your system for specific use cases. The utility is actively developed in Rust, providing performance and reliability.
.SH LIVE VERSION
To get started with the live version, pick which branch you would like to use, then run the command in your terminal:
.TP
\fBStable Branch\fR
curl -fsSL https://christitus.com/linux | sh
.TP
\fBDevelopement branch\fR
curl -fsSL https://christitus.com/linuxdev | sh
.SH OPTIONS
.TP
\fB\-t\fR, \fB\-\-theme\fR \fI<theme>\fR
Set the theme to use in the TUI.
.br
Possible values:
\fIdefault\fR,
\fIcompatible\fR.
.br
Defaults to \fIdefault\fR.
.TP
\fB\-\-override\-validation\fR
Show all available entries, disregarding compatibility checks. (\fBUNSAFE\fR)
.TP
\fB\-h\fR, \fB\-\-help\fR
Print help.
.SH SUPPORT
If you find Linutil helpful, please consider giving it a star on GitHub to show your support!
https://github.com/ChrisTitusTech/linutil
.SH DOCUMENTATION
For comprehensive information on how to use Linutil, visit the Official Linutil Documentation.
https://christitustech.github.io/linutil
.SH AUTHOR
Written by Adam Perkowski.
<adas1per@protonmail.com>
.SH REPORTING BUGS
Since the project is still in active development, you may encounter some issues.
.br
Please consider submitting feedback if you do.
https://github.com/ChrisTitusTech/linutil/issues
.SH COPYRIGHT
Copyright (c) 2024 Chris Titus.
.br
MIT License.
https://opensource.org/license/MIT

12
overrides/main.html Normal file
View file

@ -0,0 +1,12 @@
{% extends "base.html" %}
{% block header %}
{{ super() }}
<div style="color: red; text-align: center; padding: 10px; font-size: 20px;">
<strong>Announcement:</strong> This documentation is still in progress.
</div>
{% endblock %}
{% block footer %}
{# Empty block to override the footer #}
{% endblock %}

51
start.sh Executable file
View file

@ -0,0 +1,51 @@
#!/bin/sh -e
# Prevent execution if this script was only partially downloaded
{
rc='\033[0m'
red='\033[0;31m'
check() {
exit_code=$1
message=$2
if [ "$exit_code" -ne 0 ]; then
printf '%sERROR: %s%s\n' "$red" "$message" "$rc"
exit 1
fi
unset exit_code
unset message
}
findArch() {
case "$(uname -m)" in
x86_64|amd64) arch="x86_64" ;;
aarch64|arm64) arch="aarch64" ;;
*) check 1 "Unsupported architecture"
esac
}
getUrl() {
case "${arch}" in
x86_64) echo "https://github.com/ChrisTitusTech/linutil/releases/latest/download/linutil";;
*) echo "https://github.com/ChrisTitusTech/linutil/releases/latest/download/linutil-${arch}";;
esac
}
findArch
temp_file=$(mktemp)
check $? "Creating the temporary file"
curl -fsL "$(getUrl)" -o "$temp_file"
check $? "Downloading linutil"
chmod +x "$temp_file"
check $? "Making linutil executable"
"$temp_file"
check $? "Executing linutil"
rm -f "$temp_file"
check $? "Deleting the temporary file"
} # End of wrapping

77
startdev.sh Executable file
View file

@ -0,0 +1,77 @@
#!/bin/sh -e
# Prevent execution if this script was only partially downloaded
{
RC='\033[0m'
RED='\033[0;31m'
# Function to fetch the latest release tag from the GitHub API
get_latest_release() {
latest_release=$(curl -s https://api.github.com/repos/ChrisTitusTech/linutil/releases |
grep -oP '"tag_name": "\K[^"]*' |
head -n 1)
if [ -z "$latest_release" ]; then
printf "%b\n" "Error fetching release data" >&2
return 1
fi
printf "%b\n" "$latest_release"
}
# Function to redirect to the latest pre-release version
redirect_to_latest_pre_release() {
latest_release=$(get_latest_release)
if [ -n "$latest_release" ]; then
url="https://github.com/ChrisTitusTech/linutil/releases/download/$latest_release/linutil"
else
printf "%b\n" 'Unable to determine latest pre-release version.' >&2
printf "%b\n" "Using latest Full Release"
url="https://github.com/ChrisTitusTech/linutil/releases/latest/download/linutil"
fi
addArch
printf "%b\n" "Using URL: $url"
}
check() {
exit_code=$1
message=$2
if [ "$exit_code" -ne 0 ]; then
printf "%b\n" "${RED}ERROR: $message${RC}"
exit 1
fi
}
addArch() {
case "${arch}" in
x86_64);;
*) url="${url}-${arch}";;
esac
}
findArch() {
case "$(uname -m)" in
x86_64|amd64) arch="x86_64" ;;
aarch64|arm64) arch="aarch64" ;;
*) check 1 "Unsupported architecture"
esac
}
findArch
redirect_to_latest_pre_release
TMPFILE=$(mktemp)
check $? "Creating the temporary file"
printf "%b\n" "Downloading linutil from $url"
curl -fsL "$url" -o "$TMPFILE"
check $? "Downloading linutil"
chmod +x "$TMPFILE"
check $? "Making linutil executable"
"$TMPFILE"
check $? "Executing linutil"
rm -f "$TMPFILE"
check $? "Deleting the temporary file"
} # End of wrapping

40
tui/Cargo.toml Normal file
View file

@ -0,0 +1,40 @@
[package]
name = "linutil_tui"
description = "Pika's fork from https://christitustech.github.io/linutil to serve as his own tui for his scripts"
documentation = "https://christitustech.github.io/linutil"
readme = "../README.md"
edition = "2021"
license.workspace = true
repository = "https://github.com/ChrisTitusTech/linutil/tree/main/tui"
version.workspace = true
include = ["src/*.rs", "Cargo.toml", "build.rs", "cool_tips.txt", "../man/linutil.1"]
build = "build.rs"
[features]
default = ["tips"]
tips = ["rand"]
[dependencies]
clap = { version = "4.5.19", features = ["derive"] }
crossterm = "0.28.1"
ego-tree = { workspace = true }
oneshot = "0.1.8"
portable-pty = "0.8.1"
ratatui = "0.28.1"
tui-term = "0.1.12"
temp-dir = "0.1.14"
unicode-width = "0.2.0"
rand = { version = "0.8.5", optional = true }
linutil_core = { path = "../core", version = "24.9.28" }
tree-sitter-highlight = "0.24.2"
tree-sitter-bash = "0.23.1"
anstyle = "1.0.8"
ansi-to-tui = "6.0.0"
zips = "0.1.7"
[build-dependencies]
chrono = "0.4.33"
[[bin]]
name = "linutil"
path = "src/main.rs"

7
tui/build.rs Normal file
View file

@ -0,0 +1,7 @@
fn main() {
// Add current date as a variable to be displayed in the 'Linux Toolbox' text.
println!(
"cargo:rustc-env=BUILD_DATE={}",
chrono::Local::now().format("%Y-%m-%d")
);
}

239
tui/cool_tips.txt Normal file
View file

@ -0,0 +1,239 @@
ls: Lists files and directories in the current directory.
cd: Changes the current directory.
pwd: Prints the current working directory.
mkdir: Creates a new directory.  
rmdir: Removes an empty directory.
cp: Copies files or directories.  
mv: Moves or renames files or directories.
rm: Removes files or directories.
touch: Creates an empty file or updates the timestamp of an existing file.
cat: Displays the content of a file.
less: Views the content of a file, one page at a time.
head: Displays the first few lines of a file.
tail: Displays the last few lines of a file.
find: Searches for files in a directory hierarchy.
grep: Searches for a specific pattern in files.
chmod: Changes file or directory permissions.
chown: Changes file or directory ownership.
ln: Creates hard or symbolic links to files.
df: Displays disk space usage.
du: Shows disk usage of files and directories.
top: Displays real-time system processes.
ps: Shows running processes.
kill: Terminates a process by PID.
man: Displays the manual page for a command.
history: Shows the history of commands you've run.
sudo: Executes a command with superuser privileges.
apt-get: Installs, updates, or removes packages on Debian-based systems.
yum: Installs, updates, or removes packages on Red Hat-based systems.
wget: Downloads files from the web.
curl: Transfers data from or to a server using various protocols.
ssh: Connects to a remote machine securely via SSH.
ping: Tests connectivity to a network host.
ifconfig: Displays or configures network interfaces.
ip: Displays and manages network interfaces, routing, and more.
netstat: Displays network connections, routing tables, and interface statistics.
echo: Prints text to the terminal or writes text to files.
date: Displays or sets the system date and time.
shutdown: Shuts down or reboots the system.
reboot: Reboots the system.
alias: Creates a shortcut for a command.
diff: Compares the contents of two files line by line.
cmp: Compares two files byte by byte.
sort: Sorts the lines of a file alphabetically or numerically.
uniq: Removes duplicate lines from a sorted file.
wc: Counts words, lines, and characters in a file.
cut: Cuts sections from each line of a file or output.
tr: Translates or deletes characters from input.
xargs: Builds and executes command lines from standard input.
tee: Reads from standard input and writes to both standard output and files.
basename: Strips directory and suffix from filenames.
dirname: Extracts the directory path from a file path.
read: Reads input from the user or file.
tar: Archives and extracts files using tar format.
zip: Compresses files into a zip archive.
unzip: Extracts files from a zip archive.
gzip: Compresses files using the gzip format.
gunzip: Decompresses gzip-compressed files.
rsync: Synchronizes files and directories between two locations.
iptables: Configures the IP packet filter rules of the Linux kernel.
ufw: Simplified firewall management tool (Uncomplicated Firewall).
systemctl: Controls the systemd system and service manager.
journalctl: Views systemd logs.
dmesg: Displays kernel ring buffer messages.
who: Shows who is logged into the system.
last: Displays a list of last logged-in users.
at: Schedules a one-time task to run at a specific time.
awk: Pattern scanning and processing language used for text processing.
sed: Stream editor for filtering and transforming text.
chroot: Changes the root directory for a command or shell.
lsof: Lists open files and the processes that opened them.
nc: A versatile networking tool often used for testing and debugging.
sftp: A secure file transfer program over SSH.
ncdu: Disk usage analyzer with a user-friendly interface.
dig: Performs DNS lookups.
nslookup: Queries DNS information.
hostname: Displays or sets the systems hostname.
curl ifconfig.me: Gets your public IP address.
adduser: Adds a new user to the system.
deluser: Removes a user from the system.
groupadd: Adds a new group to the system.
usermod: Modifies user account details.
groups: Displays the groups the current user belongs to.
sudo su: Switches to the root user.
nohup: Runs a command that will continue running after logging out.
jobs: Lists all active jobs in the current session.
fg: Brings a background job to the foreground.
bg: Resumes a stopped job in the background.
ctrl + z: Pauses a foreground job, allowing it to run in the background.
locate: Quickly finds files by name.
updatedb: Updates the database used by the locate command.
alias ll='ls -la': Creates an alias ll for a long-format list of files.
unalias: Removes an alias for a command.
export: Sets or exports environment variables.
env: Displays the current environment variables.
crontab: Manages cron jobs for automating tasks.
watch: Repeatedly runs a command at regular intervals.
vmstat: Reports virtual memory statistics.
mpstat: Displays CPU usage statistics.
htop: An interactive process viewer (more user-friendly than top).
uptime: Displays the system uptime and load average.
ulimit: Displays or sets resource limits for user processes.
ip link: Manages network interfaces.
ss: A faster alternative to netstat for displaying network connections.
traceroute: Traces the route packets take to a network host.
ping6: Tests connectivity to a network host using IPv6.
scp: Securely copies files between hosts over SSH.
bc: A command-line calculator.
dd: Converts and copies files, useful for creating disk images.
arp: Displays or modifies the system's ARP table.
md5sum: Computes and verifies MD5 hashes.
sha256sum: Computes and verifies SHA-256 hashes.
hostnamectl: Controls the system's hostname.
ip a: Displays IP addresses of the system's network interfaces.
ip r: Displays the routing table.
journalctl -f: Follows the system logs in real time.
tshark: A command-line network packet analyzer.
lspci: Lists PCI devices connected to the system.
lsusb: Lists USB devices connected to the system.
modprobe: Adds or removes modules from the Linux kernel.
parted: A disk partitioning tool.
mkfs: Creates a file system on a partition or device.
fsck: Checks and repairs a file system.
tune2fs: Adjusts tunable file system parameters on ext filesystems.
swapoff: Disables swap space on a device.
swapon: Enables swap space on a device.
fuser: Identifies processes using files or sockets.
nmcli: Command-line tool for managing NetworkManager.
w: Displays logged-in users and their active processes.
wall: Sends a message to all logged-in users.
passwd: Changes user passwords.
stat: Displays detailed information about a file or file system.
chage: Changes user password expiration information.
pmap: Reports memory map of a process.
ionice: Sets or gets I/O scheduling class and priority.
nc (netcat): Reads and writes data across network connections.
dstat: Combines and displays system resource statistics, such as CPU, disk, and network usage.
sar: Collects, reports, or saves system activity information.
iostat: Reports CPU and I/O statistics for devices and partitions.
iotop: Displays real-time disk I/O usage by processes.
inotifywait: Waits for changes to files or directories using inotify.
inotifywatch: Watches for changes in a file or directory using inotify.
nice: Runs a command with a modified scheduling priority.
renice: Alters the priority of running processes.
lsblk: Lists information about block devices.
hdparm: Configures and displays information about SATA/IDE devices.
smartctl: Monitors the health of hard drives using SMART.
fallocate: Preallocates space to a file.
wipe: Securely erases files or partitions.
file: Determines file type based on content.
shred: Securely deletes a file by overwriting it.
ncftpput: Uploads files to an FTP server.
ncftpget: Downloads files from an FTP server.
ufw: Simplified firewall utility for managing iptables rules.
ethtool: Configures and displays Ethernet device settings.
brctl: Manages Ethernet bridges.
xkill: Terminates a window by clicking on it.
xrandr: Configures display screen resolution, rotation, and reflection.
xset: Manages X display settings.
xdg-open: Opens a file or URL in the user's preferred application.
apropos: Searches the manual page names and descriptions for keywords.
systemd-analyze: Displays system boot performance statistics.
timedatectl: Manages system time and date settings.
fwupdmgr: Firmware update manager for updating hardware firmware.
lscpu: Displays information about the CPU architecture.
getfacl: Displays file access control lists (ACLs).
setfacl: Sets file access control lists (ACLs).
pv: Monitors the progress of data through a pipeline.
logrotate: Manages the automatic rotation and compression of log files.
xclip: Interfaces with the X clipboard from the command line.
cups: Manages printers (Common Unix Printing System).
lp: Sends a file to the printer.
lprm: Removes print jobs from the queue.
lpstat: Displays the status of the print system.
strace: Traces system calls and signals.
tcpdump: Captures network traffic for analysis.
envsubst: Substitutes environment variables in shell commands.
tput: Initializes terminal capabilities, such as clearing the screen.
xargs: Builds and executes command lines from standard input.
dmesg | tail: Displays recent kernel messages (useful for hardware or system errors).
lsns: Lists all active Linux namespaces.
ss -tuln: Lists open network ports (TCP and UDP).
iptables-save: Outputs current iptables rules to a file.
iptables-restore: Restores iptables rules from a file.
tac: Displays a file in reverse line order (opposite of cat).
nl: Numbers the lines of a file.
yes: Repeatedly outputs a string until stopped (e.g., yes y).
split: Splits a file into pieces.
csplit: Splits a file into pieces based on context.
paste: Merges lines of files side by side.
comm: Compares two sorted files line by line.
shuf: Shuffles lines of text in random order.
factor: Prints the prime factors of a given number.
seq: Prints numbers in a sequence.
pr: Converts text files for printing, adding headers and footers.
column: Formats output into columns.
od: Displays files in octal, decimal, hexadecimal, or ASCII.
hexdump: Displays files in hexadecimal format.
xxd: Creates a hex dump of a file or converts a hex dump back to binary.
watch: Runs a command repeatedly, displaying the output and updates.
timeout: Runs a command with a time limit.
stdbuf: Alters the buffering of input/output for a command.
rename: Renames files using a regular expression.
prlimit: Displays or modifies resource limits of running processes.
uuidgen: Generates a new universally unique identifier (UUID).
vipw: Safely edits the /etc/passwd file.
vigr: Safely edits the /etc/group file.
getent: Retrieves entries from databases like passwd, group, or hosts.
addgroup: Creates a new user group.
pwgen: Generates random passwords.
expire: Forces a password change after a specific period.
showmount: Displays information about an NFS server.
exportfs: Maintains the NFS server's exported file systems.
rpcinfo: Displays information about RPC services on a networked system.
lsmod: Lists currently loaded kernel modules.
insmod: Inserts a module into the Linux kernel.
rmmod: Removes a module from the Linux kernel.
depmod: Generates modules dependency and map files.
kmod: Interfaces with kernel modules from the command line.
e2fsck: Checks the integrity of an ext2/ext3/ext4 file system.
blkid: Displays block device attributes, including UUID.
mount: Mounts a file system.
umount: Unmounts a file system.
parted: A command-line partition editor.
gparted: A graphical partition editor (based on parted).
cryptsetup: Manages encrypted devices.
losetup: Configures loopback devices.
mkswap: Sets up a swap area on a device or file.
tmux: Terminal multiplexer for managing multiple terminal sessions.
finger: Displays user information (if installed).
lastb: Shows failed login attempts.
pidof: Finds the process ID (PID) of a running program.
pgrep: Searches for processes by name.
curl -I: Fetches the HTTP headers from a URL.
chattr: Changes file attributes on a Linux file system.
lsattr: Lists file attributes on a Linux file system.
join: Joins lines of two files based on a common field.
tree: Displays a directory structure in a tree-like format.
col: Filters reverse line feeds from input.
free: Displays memory usage.

126
tui/src/confirmation.rs Normal file
View file

@ -0,0 +1,126 @@
use std::borrow::Cow;
use crate::{float::FloatContent, hint::Shortcut};
use crossterm::event::{KeyCode, KeyEvent};
use ratatui::{
layout::Alignment,
prelude::*,
widgets::{Block, Borders, Clear, List},
};
pub enum ConfirmStatus {
Confirm,
Abort,
None,
}
pub struct ConfirmPrompt {
pub names: Box<[String]>,
pub status: ConfirmStatus,
scroll: usize,
}
impl ConfirmPrompt {
pub fn new(names: &[&str]) -> Self {
let max_count_str = format!("{}", names.len());
let names = names
.iter()
.zip(1..)
.map(|(name, n)| {
let count_str = format!("{n}");
let space_str = (0..(max_count_str.len() - count_str.len()))
.map(|_| ' ')
.collect::<String>();
format!("{space_str}{n}. {name}")
})
.collect();
Self {
names,
status: ConfirmStatus::None,
scroll: 0,
}
}
pub fn scroll_down(&mut self) {
if self.scroll < self.names.len() - 1 {
self.scroll += 1;
}
}
pub fn scroll_up(&mut self) {
if self.scroll > 0 {
self.scroll -= 1;
}
}
}
impl FloatContent for ConfirmPrompt {
fn draw(&mut self, frame: &mut Frame, area: Rect) {
let block = Block::default()
.borders(Borders::ALL)
.title(" Confirm selections ")
.title_bottom(" [y] to continue, [n] to abort ")
.title_alignment(Alignment::Center)
.title_style(Style::default().bold())
.style(Style::default());
frame.render_widget(block.clone(), area);
let inner_area = block.inner(area);
let paths_text = self
.names
.iter()
.skip(self.scroll)
.map(|p| {
let span = Span::from(Cow::<'_, str>::Borrowed(p));
Line::from(span).style(Style::default())
})
.collect::<Text>();
frame.render_widget(Clear, inner_area);
frame.render_widget(List::new(paths_text), inner_area);
}
fn handle_key_event(&mut self, key: &KeyEvent) -> bool {
use KeyCode::*;
self.status = match key.code {
Char('y') | Char('Y') => ConfirmStatus::Confirm,
Char('n') | Char('N') | Esc => ConfirmStatus::Abort,
Char('j') => {
self.scroll_down();
ConfirmStatus::None
}
Char('k') => {
self.scroll_up();
ConfirmStatus::None
}
_ => ConfirmStatus::None,
};
false
}
fn is_finished(&self) -> bool {
use ConfirmStatus::*;
match self.status {
Confirm | Abort => true,
None => false,
}
}
fn get_shortcut_list(&self) -> (&str, Box<[Shortcut]>) {
(
"Confirmation prompt",
Box::new([
Shortcut::new("Continue", ["Y", "y"]),
Shortcut::new("Abort", ["N", "n"]),
Shortcut::new("Scroll up", ["j"]),
Shortcut::new("Scroll down", ["k"]),
Shortcut::new("Close linutil", ["CTRL-c", "q"]),
]),
)
}
}

167
tui/src/filter.rs Normal file
View file

@ -0,0 +1,167 @@
use crate::{state::ListEntry, theme::Theme};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ego_tree::NodeId;
use linutil_core::Tab;
use ratatui::{
layout::{Position, Rect},
style::Style,
text::Span,
widgets::{Block, Borders, Paragraph},
Frame,
};
use unicode_width::UnicodeWidthChar;
pub enum SearchAction {
None,
Exit,
Update,
}
pub struct Filter {
search_input: Vec<char>,
in_search_mode: bool,
input_position: usize,
items: Vec<ListEntry>,
}
impl Filter {
pub fn new() -> Self {
Self {
search_input: vec![],
in_search_mode: false,
input_position: 0,
items: vec![],
}
}
pub fn item_list(&self) -> &[ListEntry] {
&self.items
}
pub fn activate_search(&mut self) {
self.in_search_mode = true;
}
pub fn deactivate_search(&mut self) {
self.in_search_mode = false;
}
pub fn update_items(&mut self, tabs: &[Tab], current_tab: usize, node: NodeId) {
if self.search_input.is_empty() {
let curr = tabs[current_tab].tree.get(node).unwrap();
self.items = curr
.children()
.map(|node| ListEntry {
node: node.value().clone(),
id: node.id(),
has_children: node.has_children(),
})
.collect();
} else {
self.items.clear();
let query_lower = self.search_input.iter().collect::<String>().to_lowercase();
for tab in tabs.iter() {
let mut stack = vec![tab.tree.root().id()];
while let Some(node_id) = stack.pop() {
let node = tab.tree.get(node_id).unwrap();
if node.value().name.to_lowercase().contains(&query_lower)
&& !node.has_children()
{
self.items.push(ListEntry {
node: node.value().clone(),
id: node.id(),
has_children: false,
});
}
stack.extend(node.children().map(|child| child.id()));
}
}
self.items.sort_by(|a, b| a.node.name.cmp(&b.node.name));
}
}
pub fn draw_searchbar(&self, frame: &mut Frame, area: Rect, theme: &Theme) {
//Set the search bar text (If empty use the placeholder)
let display_text = if !self.in_search_mode && self.search_input.is_empty() {
Span::raw("Press / to search")
} else {
Span::raw(self.search_input.iter().collect::<String>())
};
let search_color = if self.in_search_mode {
theme.focused_color()
} else {
theme.unfocused_color()
};
//Create the search bar widget
let search_bar = Paragraph::new(display_text)
.block(Block::default().borders(Borders::ALL).title("Search"))
.style(Style::default().fg(search_color));
//Render the search bar (First chunk of the screen)
frame.render_widget(search_bar, area);
// Render cursor in search bar
if self.in_search_mode {
let cursor_position: usize = self.search_input[..self.input_position]
.iter()
.map(|c| c.width().unwrap_or(1))
.sum();
let x = area.x + cursor_position as u16 + 1;
let y = area.y + 1;
frame.set_cursor_position(Position::new(x, y));
}
}
// Handles key events. Returns true if search must be exited
pub fn handle_key(&mut self, event: &KeyEvent) -> SearchAction {
//Insert user input into the search bar
match event.code {
KeyCode::Char('c') if event.modifiers.contains(KeyModifiers::CONTROL) => {
return self.exit_search()
}
KeyCode::Char(c) => self.insert_char(c),
KeyCode::Backspace => self.remove_previous(),
KeyCode::Delete => self.remove_next(),
KeyCode::Left => return self.cursor_left(),
KeyCode::Right => return self.cursor_right(),
KeyCode::Enter => return SearchAction::Exit,
KeyCode::Esc => return self.exit_search(),
_ => return SearchAction::None,
};
SearchAction::Update
}
fn exit_search(&mut self) -> SearchAction {
self.input_position = 0;
self.search_input.clear();
SearchAction::Exit
}
fn cursor_left(&mut self) -> SearchAction {
self.input_position = self.input_position.saturating_sub(1);
SearchAction::None
}
fn cursor_right(&mut self) -> SearchAction {
if self.input_position < self.search_input.len() {
self.input_position += 1;
}
SearchAction::None
}
fn insert_char(&mut self, input: char) {
self.search_input.insert(self.input_position, input);
self.cursor_right();
}
fn remove_previous(&mut self) {
let current = self.input_position;
if current > 0 {
self.search_input.remove(current - 1);
self.cursor_left();
}
}
fn remove_next(&mut self) {
let current = self.input_position;
if current < self.search_input.len() {
self.search_input.remove(current);
}
}
}

76
tui/src/float.rs Normal file
View file

@ -0,0 +1,76 @@
use crossterm::event::{KeyCode, KeyEvent};
use ratatui::{
layout::{Constraint, Direction, Layout, Rect},
Frame,
};
use crate::hint::Shortcut;
pub trait FloatContent {
fn draw(&mut self, frame: &mut Frame, area: Rect);
fn handle_key_event(&mut self, key: &KeyEvent) -> bool;
fn is_finished(&self) -> bool;
fn get_shortcut_list(&self) -> (&str, Box<[Shortcut]>);
}
pub struct Float<Content: FloatContent + ?Sized> {
pub content: Box<Content>,
width_percent: u16,
height_percent: u16,
}
impl<Content: FloatContent + ?Sized> Float<Content> {
pub fn new(content: Box<Content>, width_percent: u16, height_percent: u16) -> Self {
Self {
content,
width_percent,
height_percent,
}
}
fn floating_window(&self, size: Rect) -> Rect {
let hor_float = Layout::default()
.constraints([
Constraint::Percentage((100 - self.width_percent) / 2),
Constraint::Percentage(self.width_percent),
Constraint::Percentage((100 - self.width_percent) / 2),
])
.direction(Direction::Horizontal)
.split(size)[1];
Layout::default()
.constraints([
Constraint::Percentage((100 - self.height_percent) / 2),
Constraint::Percentage(self.height_percent),
Constraint::Percentage((100 - self.height_percent) / 2),
])
.direction(Direction::Vertical)
.split(hor_float)[1]
}
pub fn draw(&mut self, frame: &mut Frame, parent_area: Rect) {
let popup_area = self.floating_window(parent_area);
self.content.draw(frame, popup_area);
}
// Returns true if the floating window is finished.
pub fn handle_key_event(&mut self, key: &KeyEvent) -> bool {
match key.code {
KeyCode::Enter
| KeyCode::Char('p')
| KeyCode::Char('d')
| KeyCode::Char('g')
| KeyCode::Char('q')
| KeyCode::Esc
if self.content.is_finished() =>
{
true
}
_ => self.content.handle_key_event(key),
}
}
pub fn get_shortcut_list(&self) -> (&str, Box<[Shortcut]>) {
self.content.get_shortcut_list()
}
}

291
tui/src/floating_text.rs Normal file
View file

@ -0,0 +1,291 @@
use std::{
borrow::Cow,
collections::VecDeque,
io::{Cursor, Read as _, Seek, SeekFrom, Write as _},
};
use crate::{float::FloatContent, hint::Shortcut};
use linutil_core::Command;
use crossterm::event::{KeyCode, KeyEvent};
use ratatui::{
layout::Rect,
style::{Style, Stylize},
text::Line,
widgets::{Block, Borders, Clear, List},
Frame,
};
use ansi_to_tui::IntoText;
use tree_sitter_bash as hl_bash;
use tree_sitter_highlight::{self as hl, HighlightEvent};
use zips::zip_result;
pub struct FloatingText {
pub src: Vec<String>,
max_line_width: usize,
v_scroll: usize,
h_scroll: usize,
mode_title: String,
}
macro_rules! style {
($r:literal, $g:literal, $b:literal) => {{
use anstyle::{Color, RgbColor, Style};
Style::new().fg_color(Some(Color::Rgb(RgbColor($r, $g, $b))))
}};
}
const SYNTAX_HIGHLIGHT_STYLES: [(&str, anstyle::Style); 8] = [
("function", style!(220, 220, 170)), // yellow
("string", style!(206, 145, 120)), // brown
("property", style!(156, 220, 254)), // light blue
("comment", style!(92, 131, 75)), // green
("embedded", style!(206, 145, 120)), // blue (string expansions)
("constant", style!(79, 193, 255)), // dark blue
("keyword", style!(197, 134, 192)), // magenta
("number", style!(181, 206, 168)), // light green
];
fn get_highlighted_string(s: &str) -> Option<String> {
let mut hl_conf = hl::HighlightConfiguration::new(
hl_bash::LANGUAGE.into(),
"bash",
hl_bash::HIGHLIGHT_QUERY,
"",
"",
)
.ok()?;
let matched_tokens = &SYNTAX_HIGHLIGHT_STYLES
.iter()
.map(|hl| hl.0)
.collect::<Vec<_>>();
hl_conf.configure(matched_tokens);
let mut hl = hl::Highlighter::new();
let mut style_stack = vec![anstyle::Style::new()];
let src = s.as_bytes();
let events = hl.highlight(&hl_conf, src, None, |_| None).ok()?;
let mut buf = Cursor::new(vec![]);
for event in events {
match event.unwrap() {
HighlightEvent::HighlightStart(h) => {
style_stack.push(SYNTAX_HIGHLIGHT_STYLES.get(h.0)?.1);
}
HighlightEvent::HighlightEnd => {
style_stack.pop();
}
HighlightEvent::Source { start, end } => {
let style = style_stack.last()?;
zip_result!(
write!(&mut buf, "{}", style),
buf.write_all(&src[start..end]),
write!(&mut buf, "{style:#}"),
)?;
}
}
}
let mut output = String::new();
zip_result!(
buf.seek(SeekFrom::Start(0)),
buf.read_to_string(&mut output),
)?;
Some(output)
}
macro_rules! max_width {
($($lines:tt)+) => {{
$($lines)+.iter().fold(0, |accum, val| accum.max(val.len()))
}}
}
#[inline]
fn get_lines(s: &str) -> Vec<&str> {
s.lines().collect::<Vec<_>>()
}
#[inline]
fn get_lines_owned(s: &str) -> Vec<String> {
get_lines(s).iter().map(|s| s.to_string()).collect()
}
impl FloatingText {
pub fn new(text: String, title: &str) -> Self {
let src = get_lines(&text)
.into_iter()
.map(|s| s.to_string())
.collect::<Vec<_>>();
let max_line_width = max_width!(src);
Self {
src,
mode_title: title.to_string(),
max_line_width,
v_scroll: 0,
h_scroll: 0,
}
}
pub fn from_command(command: &Command, title: String) -> Option<Self> {
let (max_line_width, src) = match command {
Command::Raw(cmd) => {
// just apply highlights directly
(max_width!(get_lines(cmd)), Some(cmd.clone()))
}
Command::LocalFile { file, .. } => {
// have to read from tmp dir to get cmd src
let raw = std::fs::read_to_string(file)
.map_err(|_| format!("File not found: {:?}", file))
.unwrap();
(max_width!(get_lines(&raw)), Some(raw))
}
// If command is a folder, we don't display a preview
Command::None => (0usize, None),
};
let src = get_lines_owned(&get_highlighted_string(&src?)?);
Some(Self {
src,
mode_title: title,
max_line_width,
h_scroll: 0,
v_scroll: 0,
})
}
fn scroll_down(&mut self) {
if self.v_scroll + 1 < self.src.len() {
self.v_scroll += 1;
}
}
fn scroll_up(&mut self) {
if self.v_scroll > 0 {
self.v_scroll -= 1;
}
}
fn scroll_left(&mut self) {
if self.h_scroll > 0 {
self.h_scroll -= 1;
}
}
fn scroll_right(&mut self) {
if self.h_scroll + 1 < self.max_line_width {
self.h_scroll += 1;
}
}
}
impl FloatContent for FloatingText {
fn draw(&mut self, frame: &mut Frame, area: Rect) {
// Define the Block with a border and background color
let block = Block::default()
.borders(Borders::ALL)
.title(self.mode_title.clone())
.title_alignment(ratatui::layout::Alignment::Center)
.title_style(Style::default().reversed())
.style(Style::default());
// Draw the Block first
frame.render_widget(block.clone(), area);
// Calculate the inner area to ensure text is not drawn over the border
let inner_area = block.inner(area);
let Rect { height, .. } = inner_area;
let lines = self
.src
.iter()
.skip(self.v_scroll)
.take(height as usize)
.flat_map(|l| l.into_text().unwrap())
.map(|line| {
let mut skipped = 0;
let mut spans = line
.into_iter()
.skip_while(|span| {
let skip = (skipped + span.content.len()) <= self.h_scroll;
if skip {
skipped += span.content.len();
true
} else {
false
}
})
.collect::<VecDeque<_>>();
if spans.is_empty() {
Line::raw(Cow::Owned(String::new()))
} else {
if skipped < self.h_scroll {
let to_split = spans.pop_front().unwrap();
let new_content = to_split.content.clone().into_owned()
[self.h_scroll - skipped..]
.to_owned();
spans.push_front(to_split.content(Cow::Owned(new_content)));
}
Line::from(Vec::from(spans))
}
})
.collect::<Vec<_>>();
// Create list widget
let list = List::new(lines)
.block(Block::default())
.highlight_style(Style::default().reversed());
// Clear the text underneath the floats rendered area
frame.render_widget(Clear, inner_area);
// Render the list inside the bordered area
frame.render_widget(list, inner_area);
}
fn handle_key_event(&mut self, key: &KeyEvent) -> bool {
use KeyCode::*;
match key.code {
Down | Char('j') => self.scroll_down(),
Up | Char('k') => self.scroll_up(),
Left | Char('h') => self.scroll_left(),
Right | Char('l') => self.scroll_right(),
_ => {}
}
false
}
fn is_finished(&self) -> bool {
true
}
fn get_shortcut_list(&self) -> (&str, Box<[Shortcut]>) {
(
&self.mode_title,
Box::new([
Shortcut::new("Scroll down", ["j", "Down"]),
Shortcut::new("Scroll up", ["k", "Up"]),
Shortcut::new("Scroll left", ["h", "Left"]),
Shortcut::new("Scroll right", ["l", "Right"]),
Shortcut::new("Close window", ["Enter", "p", "q", "d", "g"]),
]),
)
}
}

96
tui/src/hint.rs Normal file
View file

@ -0,0 +1,96 @@
use std::borrow::Cow;
use ratatui::{
style::{Style, Stylize},
text::{Line, Span},
};
pub struct Shortcut {
pub key_sequences: Vec<Span<'static>>,
pub desc: &'static str,
}
fn add_spacing(list: Vec<Vec<Span>>) -> Line {
list.into_iter()
.flat_map(|mut s| {
s.push(Span::default().content(" "));
s
})
.collect()
}
pub fn span_vec_len(span_vec: &[Span]) -> usize {
span_vec.iter().rfold(0, |init, s| init + s.width())
}
pub fn create_shortcut_list(
shortcuts: impl IntoIterator<Item = Shortcut>,
render_width: u16,
) -> Box<[Line<'static>]> {
let hints = shortcuts.into_iter().collect::<Box<[Shortcut]>>();
let mut shortcut_spans: Vec<Vec<Span<'static>>> = hints.iter().map(|h| h.to_spans()).collect();
let mut lines: Vec<Line<'static>> = vec![];
loop {
let split_idx = shortcut_spans
.iter()
.scan(0usize, |total_len, s| {
// take at least one so that we guarantee that we drain the list
// otherwise, this might lock up if there's a shortcut that exceeds the window width
if *total_len == 0 {
*total_len += span_vec_len(s) + 4;
Some(())
} else {
*total_len += span_vec_len(s);
if *total_len > render_width as usize {
None
} else {
*total_len += 4;
Some(())
}
}
})
.count();
let rest = shortcut_spans.split_off(split_idx);
lines.push(add_spacing(shortcut_spans));
if rest.is_empty() {
break;
} else {
shortcut_spans = rest;
}
}
lines.into_boxed_slice()
}
impl Shortcut {
pub fn new<const N: usize>(desc: &'static str, key_sequences: [&'static str; N]) -> Self {
Self {
key_sequences: key_sequences
.iter()
.map(|s| Span::styled(Cow::<'static, str>::Borrowed(s), Style::default().bold()))
.collect(),
desc,
}
}
fn to_spans(&self) -> Vec<Span<'static>> {
let mut ret: Vec<_> = self
.key_sequences
.iter()
.flat_map(|seq| {
[
Span::default().content("["),
seq.clone(),
Span::default().content("] "),
]
})
.collect();
ret.push(Span::styled(self.desc, Style::default().italic()));
ret
}
}

84
tui/src/main.rs Normal file
View file

@ -0,0 +1,84 @@
mod confirmation;
mod filter;
mod float;
mod floating_text;
mod hint;
mod running_command;
pub mod state;
mod theme;
use std::{
io::{self, stdout},
time::Duration,
};
use crate::theme::Theme;
use clap::Parser;
use crossterm::{
event::{self, DisableMouseCapture, Event, KeyEventKind},
style::ResetColor,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
ExecutableCommand,
};
use ratatui::{backend::CrosstermBackend, Terminal};
use state::AppState;
// Linux utility toolbox
#[derive(Debug, Parser)]
struct Args {
#[arg(short, long, value_enum)]
#[arg(default_value_t = Theme::Default)]
#[arg(help = "Set the theme to use in the application")]
theme: Theme,
#[arg(long, default_value_t = false)]
#[clap(help = "Show all available options, disregarding compatibility checks (UNSAFE)")]
override_validation: bool,
}
fn main() -> io::Result<()> {
let args = Args::parse();
let mut state = AppState::new(args.theme, args.override_validation);
stdout().execute(EnterAlternateScreen)?;
enable_raw_mode()?;
let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?;
terminal.clear()?;
run(&mut terminal, &mut state)?;
// restore terminal
disable_raw_mode()?;
terminal.backend_mut().execute(LeaveAlternateScreen)?;
terminal.backend_mut().execute(DisableMouseCapture)?;
terminal.backend_mut().execute(ResetColor)?;
terminal.show_cursor()?;
Ok(())
}
fn run(
terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
state: &mut AppState,
) -> io::Result<()> {
loop {
terminal.draw(|frame| state.draw(frame)).unwrap();
// Wait for an event
if !event::poll(Duration::from_millis(10))? {
continue;
}
// It's guaranteed that the `read()` won't block when the `poll()`
// function returns `true`
if let Event::Key(key) = event::read()? {
// We are only interested in Press and Repeat events
if key.kind != KeyEventKind::Press && key.kind != KeyEventKind::Repeat {
continue;
}
if !state.handle_key(&key) {
return Ok(());
}
}
}
}

327
tui/src/running_command.rs Normal file
View file

@ -0,0 +1,327 @@
use crate::{float::FloatContent, hint::Shortcut};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use linutil_core::Command;
use oneshot::{channel, Receiver};
use portable_pty::{
ChildKiller, CommandBuilder, ExitStatus, MasterPty, NativePtySystem, PtySize, PtySystem,
};
use ratatui::{
layout::{Rect, Size},
style::{Color, Style, Stylize},
text::{Line, Span},
widgets::{Block, Borders},
Frame,
};
use std::{
io::Write,
sync::{Arc, Mutex},
thread::JoinHandle,
};
use tui_term::{
vt100::{self, Screen},
widget::PseudoTerminal,
};
pub struct RunningCommand {
/// A buffer to save all the command output (accumulates, until the command exits)
buffer: Arc<Mutex<Vec<u8>>>,
/// A handle for the thread running the command
command_thread: Option<JoinHandle<ExitStatus>>,
/// A handle to kill the running process; it's an option because it can only be used once
child_killer: Option<Receiver<Box<dyn ChildKiller + Send + Sync>>>,
/// A join handle for the thread that reads command output and sends it to the main thread
_reader_thread: JoinHandle<()>,
/// Virtual terminal (pty) handle, used for resizing the pty
pty_master: Box<dyn MasterPty + Send>,
/// Used for sending keys to the emulated terminal
writer: Box<dyn Write + Send>,
/// Only set after the process has ended
status: Option<ExitStatus>,
scroll_offset: usize,
}
impl FloatContent for RunningCommand {
fn draw(&mut self, frame: &mut Frame, area: Rect) {
// Calculate the inner size of the terminal area, considering borders
let inner_size = Size {
width: area.width - 2, // Adjust for border width
height: area.height - 2,
};
// Define the block for the terminal display
let block = if !self.is_finished() {
// Display a block indicating the command is running
Block::default()
.borders(Borders::ALL)
.title_top(Line::from("Running the command....").centered())
.title_style(Style::default().reversed())
.title_bottom(Line::from("Press Ctrl-C to KILL the command"))
} else {
// Display a block with the command's exit status
let mut title_line = if self.get_exit_status().success() {
Line::from(
Span::default()
.content("SUCCESS!")
.style(Style::default().fg(Color::Green).reversed()),
)
} else {
Line::from(
Span::default()
.content("FAILED!")
.style(Style::default().fg(Color::Red).reversed()),
)
};
title_line.push_span(
Span::default()
.content(" press <ENTER> to close this window ")
.style(Style::default()),
);
Block::default()
.borders(Borders::ALL)
.title_top(title_line.centered())
};
// Process the buffer and create the pseudo-terminal widget
let screen = self.screen(inner_size);
let pseudo_term = PseudoTerminal::new(&screen).block(block);
// Render the widget on the frame
frame.render_widget(pseudo_term, area);
}
/// Handle key events of the running command "window". Returns true when the "window" should be
/// closed
fn handle_key_event(&mut self, key: &KeyEvent) -> bool {
match key.code {
// Handle Ctrl-C to kill the command
KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
self.kill_child();
}
// Close the window when Enter is pressed and the command is finished
KeyCode::Enter if self.is_finished() => {
return true;
}
KeyCode::PageUp => {
self.scroll_offset = self.scroll_offset.saturating_add(10);
}
KeyCode::PageDown => {
self.scroll_offset = self.scroll_offset.saturating_sub(10);
}
// Pass other key events to the terminal
_ => self.handle_passthrough_key_event(key),
}
false
}
fn is_finished(&self) -> bool {
// Check if the command thread has finished
if let Some(command_thread) = &self.command_thread {
command_thread.is_finished()
} else {
true
}
}
fn get_shortcut_list(&self) -> (&str, Box<[Shortcut]>) {
if self.is_finished() {
(
"Finished command",
Box::new([
Shortcut::new("Close window", ["Enter", "q"]),
Shortcut::new("Scroll up", ["Page up"]),
Shortcut::new("Scroll down", ["Page down"]),
]),
)
} else {
(
"Running command",
Box::new([
Shortcut::new("Kill the command", ["CTRL-c"]),
Shortcut::new("Scroll up", ["Page up"]),
Shortcut::new("Scroll down", ["Page down"]),
]),
)
}
}
}
impl RunningCommand {
pub fn new(commands: Vec<Command>) -> Self {
let pty_system = NativePtySystem::default();
// Build the command based on the provided Command enum variant
let mut cmd: CommandBuilder = CommandBuilder::new("sh");
cmd.arg("-c");
// All the merged commands are passed as a single argument to reduce the overhead of rebuilding the command arguments for each and every command
let mut script = String::new();
for command in commands {
match command {
Command::Raw(prompt) => script.push_str(&format!("{}\n", prompt)),
Command::LocalFile {
executable,
args,
file,
} => {
if let Some(parent_directory) = file.parent() {
script.push_str(&format!("cd {}\n", parent_directory.display()));
}
script.push_str(&executable);
for arg in args {
script.push(' ');
script.push_str(&arg);
}
script.push('\n'); // Ensures that each command is properly separated for execution preventing directory errors
}
Command::None => panic!("Command::None was treated as a command"),
}
}
cmd.arg(script);
// Open a pseudo-terminal with initial size
let pair = pty_system
.openpty(PtySize {
rows: 24, // Initial number of rows (will be updated dynamically)
cols: 80, // Initial number of columns (will be updated dynamically)
pixel_width: 0,
pixel_height: 0,
})
.unwrap();
let (tx, rx) = channel();
// Thread waiting for the child to complete
let command_handle = std::thread::spawn(move || {
let mut child = pair.slave.spawn_command(cmd).unwrap();
let killer = child.clone_killer();
tx.send(killer).unwrap();
child.wait().unwrap()
});
let mut reader = pair.master.try_clone_reader().unwrap(); // This is a reader, this is where we
// A buffer, shared between the thread that reads the command output, and the main tread.
// The main thread only reads the contents
let command_buffer: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::new()));
let reader_handle = {
// Arc is just a reference, so we can create an owned copy without any problem
let command_buffer = command_buffer.clone();
// The closure below moves all variables used into it, so we can no longer use them,
// that's why command_buffer.clone(), because we need to use command_buffer later
std::thread::spawn(move || {
let mut buf = [0u8; 8192];
loop {
let size = reader.read(&mut buf).unwrap(); // Can block here
if size == 0 {
break; // EOF
}
let mut mutex = command_buffer.lock(); // Only lock the mutex after the read is
// done, to minimise the time it is opened
let command_buffer = mutex.as_mut().unwrap();
command_buffer.extend_from_slice(&buf[0..size]);
// The mutex is closed here automatically
}
})
};
let writer = pair.master.take_writer().unwrap();
Self {
buffer: command_buffer,
command_thread: Some(command_handle),
child_killer: Some(rx),
_reader_thread: reader_handle,
pty_master: pair.master,
writer,
status: None,
scroll_offset: 0,
}
}
fn screen(&mut self, size: Size) -> Screen {
// Resize the emulated pty
self.pty_master
.resize(PtySize {
rows: size.height,
cols: size.width,
pixel_width: 0,
pixel_height: 0,
})
.unwrap();
// Process the buffer with a parser with the current screen size
// We don't actually need to create a new parser every time, but it is so much easier this
// way, and doesn't cost that much
let mut parser = vt100::Parser::new(size.height, size.width, 200);
let mutex = self.buffer.lock();
let buffer = mutex.as_ref().unwrap();
parser.process(buffer);
// Adjust the screen content based on the scroll offset
parser.screen_mut().set_scrollback(self.scroll_offset);
parser.screen().clone()
}
/// This function will block if the command is not finished
fn get_exit_status(&mut self) -> ExitStatus {
if self.command_thread.is_some() {
let handle = self.command_thread.take().unwrap();
let exit_status = handle.join().unwrap();
self.status = Some(exit_status.clone());
exit_status
} else {
self.status.as_ref().unwrap().clone()
}
}
/// Send SIGHUB signal, *not* SIGKILL or SIGTERM, to the child process
pub fn kill_child(&mut self) {
if !self.is_finished() {
let mut killer = self.child_killer.take().unwrap().recv().unwrap();
killer.kill().unwrap();
}
}
/// Convert the KeyEvent to pty key codes, and send them to the virtual terminal
fn handle_passthrough_key_event(&mut self, key: &KeyEvent) {
let input_bytes = match key.code {
KeyCode::Char(ch) => {
let raw_utf8 = || ch.to_string().into_bytes();
match ch.to_ascii_uppercase() {
_ if key.modifiers != KeyModifiers::CONTROL => raw_utf8(),
// https://github.com/fyne-io/terminal/blob/master/input.go
// https://gist.github.com/ConnerWill/d4b6c776b509add763e17f9f113fd25b
'2' | '@' | ' ' => vec![0],
'3' | '[' => vec![27],
'4' | '\\' => vec![28],
'5' | ']' => vec![29],
'6' | '^' => vec![30],
'7' | '-' | '_' => vec![31],
c if ('A'..='_').contains(&c) => {
let ascii_val = c as u8;
let ascii_to_send = ascii_val - 64;
vec![ascii_to_send]
}
_ => raw_utf8(),
}
}
KeyCode::Enter => vec![b'\n'],
KeyCode::Backspace => vec![0x7f],
KeyCode::Left => vec![27, 91, 68],
KeyCode::Right => vec![27, 91, 67],
KeyCode::Up => vec![27, 91, 65],
KeyCode::Down => vec![27, 91, 66],
KeyCode::Tab => vec![9],
KeyCode::Home => vec![27, 91, 72],
KeyCode::End => vec![27, 91, 70],
KeyCode::BackTab => vec![27, 91, 90],
KeyCode::Delete => vec![27, 91, 51, 126],
KeyCode::Insert => vec![27, 91, 50, 126],
KeyCode::Esc => vec![27],
_ => return,
};
// Send the keycodes to the virtual terminal
let _ = self.writer.write_all(&input_bytes);
}
}

757
tui/src/state.rs Normal file
View file

@ -0,0 +1,757 @@
use crate::{
confirmation::{ConfirmPrompt, ConfirmStatus},
filter::{Filter, SearchAction},
float::{Float, FloatContent},
floating_text::FloatingText,
hint::{create_shortcut_list, Shortcut},
running_command::RunningCommand,
theme::Theme,
};
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ego_tree::NodeId;
use linutil_core::{ListNode, Tab};
#[cfg(feature = "tips")]
use rand::Rng;
use ratatui::{
layout::{Alignment, Constraint, Direction, Flex, Layout},
style::{Style, Stylize},
text::{Line, Span, Text},
widgets::{Block, Borders, List, ListState, Paragraph},
Frame,
};
use std::rc::Rc;
use temp_dir::TempDir;
const MIN_WIDTH: u16 = 77;
const MIN_HEIGHT: u16 = 19;
const TITLE: &str = concat!("Linux Toolbox - ", env!("BUILD_DATE"));
const ACTIONS_GUIDE: &str = "List of important tasks performed by commands' names:
D - disk modifications (ex. partitioning) (privileged)
FI - flatpak installation
FM - file modification
I - installation (privileged)
MP - package manager actions
SI - full system installation
SS - systemd actions (privileged)
RP - package removal
P* - privileged *
";
pub struct AppState {
/// This must be passed to retain the temp dir until the end of the program
_temp_dir: TempDir,
/// Selected theme
theme: Theme,
/// Currently focused area
pub focus: Focus,
/// List of tabs
tabs: Vec<Tab>,
/// Current tab
current_tab: ListState,
/// This stack keeps track of our "current directory". You can think of it as `pwd`. but not
/// just the current directory, all paths that took us here, so we can "cd .."
visit_stack: Vec<NodeId>,
/// This is the state associated with the list widget, used to display the selection in the
/// widget
selection: ListState,
filter: Filter,
multi_select: bool,
selected_commands: Vec<Rc<ListNode>>,
drawable: bool,
#[cfg(feature = "tips")]
tip: &'static str,
}
pub enum Focus {
Search,
TabList,
List,
FloatingWindow(Float<dyn FloatContent>),
ConfirmationPrompt(Float<ConfirmPrompt>),
}
pub struct ListEntry {
pub node: Rc<ListNode>,
pub id: NodeId,
pub has_children: bool,
}
impl AppState {
pub fn new(theme: Theme, override_validation: bool) -> Self {
let (temp_dir, tabs) = linutil_core::get_tabs(!override_validation);
let root_id = tabs[0].tree.root().id();
let mut state = Self {
_temp_dir: temp_dir,
theme,
focus: Focus::List,
tabs,
current_tab: ListState::default().with_selected(Some(0)),
visit_stack: vec![root_id],
selection: ListState::default().with_selected(Some(0)),
filter: Filter::new(),
multi_select: false,
selected_commands: Vec::new(),
drawable: false,
#[cfg(feature = "tips")]
tip: get_random_tip(),
};
state.update_items();
state
}
fn get_list_item_shortcut(&self) -> Box<[Shortcut]> {
if self.selected_item_is_dir() {
Box::new([Shortcut::new("Go to selected dir", ["l", "Right", "Enter"])])
} else {
Box::new([
Shortcut::new("Run selected command", ["l", "Right", "Enter"]),
Shortcut::new("Enable preview", ["p"]),
Shortcut::new("Command Description", ["d"]),
])
}
}
pub fn get_keybinds(&self) -> (&str, Box<[Shortcut]>) {
match self.focus {
Focus::Search => (
"Search bar",
Box::new([
Shortcut::new("Abort search", ["Esc", "CTRL-c"]),
Shortcut::new("Search", ["Enter"]),
]),
),
Focus::List => {
let mut hints = Vec::new();
hints.push(Shortcut::new("Exit linutil", ["q", "CTRL-c"]));
if self.at_root() {
hints.push(Shortcut::new("Focus tab list", ["h", "Left"]));
hints.extend(self.get_list_item_shortcut());
} else if self.selected_item_is_up_dir() {
hints.push(Shortcut::new(
"Go to parent directory",
["l", "Right", "Enter", "h", "Left"],
));
} else {
hints.push(Shortcut::new("Go to parent directory", ["h", "Left"]));
hints.extend(self.get_list_item_shortcut());
}
hints.push(Shortcut::new("Select item above", ["k", "Up"]));
hints.push(Shortcut::new("Select item below", ["j", "Down"]));
hints.push(Shortcut::new("Next theme", ["t"]));
hints.push(Shortcut::new("Previous theme", ["T"]));
if self.is_current_tab_multi_selectable() {
hints.push(Shortcut::new("Toggle multi-selection mode", ["v"]));
hints.push(Shortcut::new("Select multiple commands", ["Space"]));
}
hints.push(Shortcut::new("Next tab", ["Tab"]));
hints.push(Shortcut::new("Previous tab", ["Shift-Tab"]));
hints.push(Shortcut::new("Important actions guide", ["g"]));
("Command list", hints.into_boxed_slice())
}
Focus::TabList => (
"Tab list",
Box::new([
Shortcut::new("Exit linutil", ["q", "CTRL-c"]),
Shortcut::new("Focus action list", ["l", "Right", "Enter"]),
Shortcut::new("Select item above", ["k", "Up"]),
Shortcut::new("Select item below", ["j", "Down"]),
Shortcut::new("Next theme", ["t"]),
Shortcut::new("Previous theme", ["T"]),
Shortcut::new("Next tab", ["Tab"]),
Shortcut::new("Previous tab", ["Shift-Tab"]),
]),
),
Focus::FloatingWindow(ref float) => float.get_shortcut_list(),
Focus::ConfirmationPrompt(ref prompt) => prompt.get_shortcut_list(),
}
}
pub fn draw(&mut self, frame: &mut Frame) {
let terminal_size = frame.area();
if terminal_size.width < MIN_WIDTH || terminal_size.height < MIN_HEIGHT {
let warning = Paragraph::new(format!(
"Terminal size too small:\nWidth = {} Height = {}\n\nMinimum size:\nWidth = {} Height = {}",
terminal_size.width,
terminal_size.height,
MIN_WIDTH,
MIN_HEIGHT,
))
.alignment(Alignment::Center)
.style(Style::default().fg(ratatui::style::Color::Red).bold())
.wrap(ratatui::widgets::Wrap { trim: true });
let centered_layout = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Fill(1),
Constraint::Length(5),
Constraint::Fill(1),
])
.split(terminal_size);
self.drawable = false;
return frame.render_widget(warning, centered_layout[1]);
} else {
self.drawable = true;
}
let label_block =
Block::default()
.borders(Borders::all())
.border_set(ratatui::symbols::border::Set {
top_left: " ",
top_right: " ",
bottom_left: " ",
bottom_right: " ",
vertical_left: " ",
vertical_right: " ",
horizontal_top: "*",
horizontal_bottom: "*",
});
let str1 = "scriptui ";
let str2 = "by pika";
let label = Paragraph::new(Line::from(vec![
Span::styled(str1, Style::default().bold()),
Span::styled(str2, Style::default().italic()),
]))
.block(label_block)
.alignment(Alignment::Center);
let longest_tab_display_len = self
.tabs
.iter()
.map(|tab| tab.name.len() + self.theme.tab_icon().len())
.max()
.unwrap_or(0)
.max(str1.len() + str2.len());
let (keybind_scope, shortcuts) = self.get_keybinds();
let keybind_render_width = terminal_size.width - 2;
let keybinds_block = Block::default()
.title(format!(" {} ", keybind_scope))
.borders(Borders::all());
let keybinds = create_shortcut_list(shortcuts, keybind_render_width);
let n_lines = keybinds.len() as u16;
let keybind_para = Paragraph::new(Text::from_iter(keybinds)).block(keybinds_block);
let vertical = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage(0),
Constraint::Max(n_lines as u16 + 2),
])
.flex(Flex::Legacy)
.margin(0)
.split(frame.area());
let horizontal = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Min(longest_tab_display_len as u16 + 5),
Constraint::Percentage(100),
])
.split(vertical[0]);
let left_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Length(3), Constraint::Min(1)])
.split(horizontal[0]);
frame.render_widget(label, left_chunks[0]);
let tabs = self
.tabs
.iter()
.map(|tab| tab.name.as_str())
.collect::<Vec<_>>();
let tab_hl_style = if let Focus::TabList = self.focus {
Style::default().reversed().fg(self.theme.tab_color())
} else {
Style::new().fg(self.theme.tab_color())
};
let list = List::new(tabs)
.block(Block::default().borders(Borders::ALL))
.highlight_style(tab_hl_style)
.highlight_symbol(self.theme.tab_icon());
frame.render_stateful_widget(list, left_chunks[1], &mut self.current_tab);
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Length(3), Constraint::Min(1)].as_ref())
.split(horizontal[1]);
let list_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(70), Constraint::Percentage(30)].as_ref())
.split(chunks[1]);
self.filter.draw_searchbar(frame, chunks[0], &self.theme);
let mut items: Vec<Line> = Vec::new();
let mut task_items: Vec<Line> = Vec::new();
if !self.at_root() {
items.push(
Line::from(format!("{} ..", self.theme.dir_icon())).style(self.theme.dir_color()),
);
task_items.push(Line::from(" ").style(self.theme.dir_color()));
}
items.extend(self.filter.item_list().iter().map(
|ListEntry {
node, has_children, ..
}| {
let is_selected = self.selected_commands.contains(node);
let (indicator, style) = if is_selected {
(self.theme.multi_select_icon(), Style::default().bold())
} else {
("", Style::new())
};
if *has_children {
Line::from(format!(
"{} {} {}",
self.theme.dir_icon(),
node.name,
indicator
))
.style(self.theme.dir_color())
} else {
Line::from(format!(
"{} {} {}",
self.theme.cmd_icon(),
node.name,
indicator
))
.style(self.theme.cmd_color())
.patch_style(style)
}
},
));
task_items.extend(self.filter.item_list().iter().map(
|ListEntry {
node, has_children, ..
}| {
if *has_children {
Line::from(" ").style(self.theme.dir_color())
} else {
Line::from(format!("{} ", node.task_list))
.alignment(Alignment::Right)
.style(self.theme.cmd_color())
.bold()
}
},
));
let style = if let Focus::List = self.focus {
Style::default().reversed()
} else {
Style::new()
};
let title = if self.multi_select {
&format!("{} [Multi-Select]", TITLE)
} else {
TITLE
};
#[cfg(feature = "tips")]
let bottom_title = Line::from(self.tip.bold().blue()).right_aligned();
#[cfg(not(feature = "tips"))]
let bottom_title = "";
let task_list_title = Line::from("Important Actions ").right_aligned();
// Create the list widget with items
let list = List::new(items)
.highlight_style(style)
.block(
Block::default()
.borders(Borders::ALL & !Borders::RIGHT)
.title(title)
.title_bottom(bottom_title),
)
.scroll_padding(1);
frame.render_stateful_widget(list, list_chunks[0], &mut self.selection);
let disclaimer_list = List::new(task_items).highlight_style(style).block(
Block::default()
.borders(Borders::ALL & !Borders::LEFT)
.title(task_list_title),
);
frame.render_stateful_widget(disclaimer_list, list_chunks[1], &mut self.selection);
match &mut self.focus {
Focus::FloatingWindow(float) => float.draw(frame, chunks[1]),
Focus::ConfirmationPrompt(prompt) => prompt.draw(frame, chunks[1]),
_ => {}
}
frame.render_widget(keybind_para, vertical[1]);
}
pub fn handle_key(&mut self, key: &KeyEvent) -> bool {
// This should be defined first to allow closing
// the application even when not drawable ( If terminal is small )
// Exit on 'q' or 'Ctrl-c' input
if matches!(
self.focus,
Focus::TabList | Focus::List | Focus::ConfirmationPrompt(_)
) && (key.code == KeyCode::Char('q')
|| key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c'))
{
return false;
}
// If UI is not drawable returning true will mark as the key handled
if !self.drawable {
return true;
}
// Handle key only when Tablist or List is focused
// Prevents exiting the application even when a command is running
// Add keys here which should work on both TabList and List
if matches!(self.focus, Focus::TabList | Focus::List) {
match key.code {
KeyCode::Tab => {
if self.current_tab.selected().unwrap() == self.tabs.len() - 1 {
self.current_tab.select_first();
} else {
self.current_tab.select_next();
}
self.refresh_tab();
}
KeyCode::BackTab => {
if self.current_tab.selected().unwrap() == 0 {
self.current_tab.select(Some(self.tabs.len() - 1));
} else {
self.current_tab.select_previous();
}
self.refresh_tab();
}
_ => {}
}
}
match &mut self.focus {
Focus::FloatingWindow(command) => {
if command.handle_key_event(key) {
self.focus = Focus::List;
}
}
Focus::ConfirmationPrompt(confirm) => {
confirm.content.handle_key_event(key);
match confirm.content.status {
ConfirmStatus::Abort => {
self.focus = Focus::List;
// selected command was pushed to selection list if multi-select was
// enabled, need to clear it to prevent state corruption
if !self.multi_select {
self.selected_commands.clear()
}
}
ConfirmStatus::Confirm => self.handle_confirm_command(),
ConfirmStatus::None => {}
}
}
Focus::Search => match self.filter.handle_key(key) {
SearchAction::Exit => self.exit_search(),
SearchAction::Update => self.update_items(),
SearchAction::None => {}
},
Focus::TabList => match key.code {
KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => self.focus = Focus::List,
KeyCode::Char('j') | KeyCode::Down
if self.current_tab.selected().unwrap() + 1 < self.tabs.len() =>
{
self.current_tab.select_next();
self.refresh_tab();
}
KeyCode::Char('k') | KeyCode::Up => {
self.current_tab.select_previous();
self.refresh_tab();
}
KeyCode::Char('/') => self.enter_search(),
KeyCode::Char('t') => self.theme.next(),
KeyCode::Char('T') => self.theme.prev(),
KeyCode::Char('g') => self.toggle_task_list_guide(),
_ => {}
},
Focus::List if key.kind != KeyEventKind::Release => match key.code {
KeyCode::Char('j') | KeyCode::Down => self.selection.select_next(),
KeyCode::Char('k') | KeyCode::Up => self.selection.select_previous(),
KeyCode::Char('p') | KeyCode::Char('P') => self.enable_preview(),
KeyCode::Char('d') | KeyCode::Char('D') => self.enable_description(),
KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => self.handle_enter(),
KeyCode::Char('h') | KeyCode::Left => self.go_back(),
KeyCode::Char('/') => self.enter_search(),
KeyCode::Char('t') => self.theme.next(),
KeyCode::Char('T') => self.theme.prev(),
KeyCode::Char('g') => self.toggle_task_list_guide(),
KeyCode::Char('v') | KeyCode::Char('V') => self.toggle_multi_select(),
KeyCode::Char(' ') if self.multi_select => self.toggle_selection(),
_ => {}
},
_ => (),
};
true
}
fn toggle_multi_select(&mut self) {
if self.is_current_tab_multi_selectable() {
self.multi_select = !self.multi_select;
if !self.multi_select {
self.selected_commands.clear();
}
}
}
fn toggle_selection(&mut self) {
if let Some(command) = self.get_selected_node() {
if self.selected_commands.contains(&command) {
self.selected_commands.retain(|c| c != &command);
} else {
self.selected_commands.push(command);
}
}
}
pub fn is_current_tab_multi_selectable(&self) -> bool {
let index = self.current_tab.selected().unwrap_or(0);
self.tabs
.get(index)
.map_or(false, |tab| tab.multi_selectable)
}
fn update_items(&mut self) {
self.filter.update_items(
&self.tabs,
self.current_tab.selected().unwrap(),
*self.visit_stack.last().unwrap(),
);
if !self.is_current_tab_multi_selectable() {
self.multi_select = false;
self.selected_commands.clear();
}
}
/// Checks either the current tree node is the root node (can we go up the tree or no)
/// Returns `true` if we can't go up the tree (we are at the tree root)
/// else returns `false`
pub fn at_root(&self) -> bool {
self.visit_stack.len() == 1
}
fn go_back(&mut self) {
if self.at_root() {
self.focus = Focus::TabList;
} else {
self.enter_parent_directory();
}
}
fn enter_parent_directory(&mut self) {
self.visit_stack.pop();
self.selection.select(Some(0));
self.update_items();
}
fn get_selected_node(&self) -> Option<Rc<ListNode>> {
let mut selected_index = self.selection.selected().unwrap_or(0);
if !self.at_root() && selected_index == 0 {
return None;
}
if !self.at_root() {
selected_index = selected_index.saturating_sub(1);
}
if let Some(item) = self.filter.item_list().get(selected_index) {
if !item.has_children {
return Some(item.node.clone());
}
}
None
}
fn get_selected_description(&self) -> Option<String> {
self.get_selected_node()
.map(|node| node.description.clone())
}
pub fn go_to_selected_dir(&mut self) {
let mut selected_index = self.selection.selected().unwrap_or(0);
if !self.at_root() && selected_index == 0 {
self.enter_parent_directory();
return;
}
if !self.at_root() {
selected_index = selected_index.saturating_sub(1);
}
if let Some(item) = self.filter.item_list().get(selected_index) {
if item.has_children {
self.visit_stack.push(item.id);
self.selection.select(Some(0));
self.update_items();
}
}
}
pub fn selected_item_is_dir(&self) -> bool {
let mut selected_index = self.selection.selected().unwrap_or(0);
if !self.at_root() && selected_index == 0 {
return false;
}
if !self.at_root() {
selected_index = selected_index.saturating_sub(1);
}
self.filter
.item_list()
.get(selected_index)
.map_or(false, |item| item.has_children)
}
pub fn selected_item_is_cmd(&self) -> bool {
// Any item that is not a directory or up directory (..) must be a command
self.selection.selected().is_some()
&& !(self.selected_item_is_up_dir() || self.selected_item_is_dir())
}
pub fn selected_item_is_up_dir(&self) -> bool {
let selected_index = self.selection.selected().unwrap_or(0);
!self.at_root() && selected_index == 0
}
fn enable_preview(&mut self) {
if let Some(list_node) = self.get_selected_node() {
let mut preview_title = "[Preview] - ".to_string();
preview_title.push_str(list_node.name.as_str());
if let Some(preview) = FloatingText::from_command(&list_node.command, preview_title) {
self.spawn_float(preview, 80, 80);
}
}
}
fn enable_description(&mut self) {
if let Some(command_description) = self.get_selected_description() {
let description = FloatingText::new(command_description, "Command Description");
self.spawn_float(description, 80, 80);
}
}
fn handle_enter(&mut self) {
if self.selected_item_is_cmd() {
if self.selected_commands.is_empty() {
if let Some(node) = self.get_selected_node() {
self.selected_commands.push(node);
}
}
let cmd_names = self
.selected_commands
.iter()
.map(|node| node.name.as_str())
.collect::<Vec<_>>();
let prompt = ConfirmPrompt::new(&cmd_names[..]);
self.focus = Focus::ConfirmationPrompt(Float::new(Box::new(prompt), 40, 40));
} else {
self.go_to_selected_dir();
}
}
fn handle_confirm_command(&mut self) {
let commands = self
.selected_commands
.iter()
.map(|node| node.command.clone())
.collect();
let command = RunningCommand::new(commands);
self.spawn_float(command, 80, 80);
self.selected_commands.clear();
}
fn spawn_float<T: FloatContent + 'static>(&mut self, float: T, width: u16, height: u16) {
self.focus = Focus::FloatingWindow(Float::new(Box::new(float), width, height));
}
fn enter_search(&mut self) {
self.focus = Focus::Search;
self.filter.activate_search();
self.selection.select(None);
}
fn exit_search(&mut self) {
self.selection.select(Some(0));
self.focus = Focus::List;
self.filter.deactivate_search();
self.update_items();
}
fn refresh_tab(&mut self) {
self.visit_stack = vec![self.tabs[self.current_tab.selected().unwrap()]
.tree
.root()
.id()];
self.selection.select(Some(0));
self.update_items();
}
fn toggle_task_list_guide(&mut self) {
self.spawn_float(
FloatingText::new(ACTIONS_GUIDE.to_string(), "Important Actions Guide"),
80,
80,
);
}
}
#[cfg(feature = "tips")]
const TIPS: &str = include_str!("../cool_tips.txt");
#[cfg(feature = "tips")]
fn get_random_tip() -> &'static str {
let tips: Vec<&str> = TIPS.lines().collect();
if tips.is_empty() {
return "";
}
let mut rng = rand::thread_rng();
let random_index = rng.gen_range(0..tips.len());
tips[random_index]
}

107
tui/src/theme.rs Normal file
View file

@ -0,0 +1,107 @@
use clap::ValueEnum;
use ratatui::style::Color;
// Add the Theme name here for a new theme
// This is more secure than the previous list
// We cannot index out of bounds, and we are giving
// names to our various themes, making it very clear
// This will make it easy to add new themes
#[derive(Clone, Debug, PartialEq, Default, ValueEnum, Copy)]
pub enum Theme {
#[default]
Default,
Compatible,
}
impl Theme {
pub fn dir_color(&self) -> Color {
match self {
Theme::Default => Color::Blue,
Theme::Compatible => Color::Blue,
}
}
pub fn cmd_color(&self) -> Color {
match self {
Theme::Default => Color::Rgb(204, 224, 208),
Theme::Compatible => Color::LightGreen,
}
}
pub fn tab_color(&self) -> Color {
match self {
Theme::Default => Color::Rgb(255, 255, 85),
Theme::Compatible => Color::Yellow,
}
}
pub fn dir_icon(&self) -> &'static str {
match self {
Theme::Default => "",
Theme::Compatible => "[DIR]",
}
}
pub fn cmd_icon(&self) -> &'static str {
match self {
Theme::Default => "",
Theme::Compatible => "[CMD]",
}
}
pub fn tab_icon(&self) -> &'static str {
match self {
Theme::Default => "",
Theme::Compatible => ">> ",
}
}
pub fn multi_select_icon(&self) -> &'static str {
match self {
Theme::Default => "",
Theme::Compatible => "*",
}
}
pub fn success_color(&self) -> Color {
match self {
Theme::Default => Color::Rgb(199, 55, 44),
Theme::Compatible => Color::Green,
}
}
pub fn fail_color(&self) -> Color {
match self {
Theme::Default => Color::Rgb(5, 255, 55),
Theme::Compatible => Color::Red,
}
}
pub fn focused_color(&self) -> Color {
match self {
Theme::Default => Color::LightBlue,
Theme::Compatible => Color::LightBlue,
}
}
pub fn unfocused_color(&self) -> Color {
match self {
Theme::Default => Color::Gray,
Theme::Compatible => Color::Gray,
}
}
}
impl Theme {
pub fn next(&mut self) {
let position = *self as usize;
let types = Theme::value_variants();
*self = types[(position + 1) % types.len()];
}
pub fn prev(&mut self) {
let position = *self as usize;
let types = Theme::value_variants();
*self = types[(position + types.len() - 1) % types.len()];
}
}

8
xtask/Cargo.toml Normal file
View file

@ -0,0 +1,8 @@
[package]
name = "xtask"
version.workspace = true
license.workspace = true
edition.workspace = true
[dependencies]
linutil_core = { path = "../core" }

60
xtask/src/docgen.rs Normal file
View file

@ -0,0 +1,60 @@
use std::fs;
use linutil_core::Command;
use crate::path;
use crate::DynError;
pub const USER_GUIDE: &str = "userguide.md";
pub fn userguide() -> Result<String, DynError> {
let mut md = String::new();
md.push_str("<!-- THIS FILE IS GENERATED BY cargo xtask docgen -->\n# Walkthrough\n");
let tabs = linutil_core::get_tabs(false).1;
for tab in tabs {
#[cfg(debug_assertions)]
println!("Tab: {}", tab.name);
md.push_str(&format!("\n## {}\n\n", tab.name));
for entry in tab.tree {
if entry.command == Command::None {
#[cfg(debug_assertions)]
println!(" Directory: {}", entry.name);
if entry.name != "root".to_string() {
md.push_str(&format!("\n### {}\n\n", entry.name));
}
/* let current_dir = &entry.name;
if *current_dir != "root".to_string() {
md.push_str(&format!(
"\n<details><summary>{}</summary>\n\n",
current_dir
));
} */ // Commenting this for now, might be a good idea later
} else {
if !entry.description.is_empty() {
#[cfg(debug_assertions)]
println!(" Entry: {}", entry.name);
#[cfg(debug_assertions)]
println!(" Description: {}", entry.description);
md.push_str(&format!("- **{}**: {}\n", entry.name, entry.description));
} /* else {
md.push_str(&format!("- **{}**\n", entry.name));
} */ // https://github.com/ChrisTitusTech/linutil/pull/753
}
}
}
Ok(md)
}
pub fn write(file: &str, data: &str) {
let path = path::docs().join(file);
fs::write(path, data).unwrap_or_else(|_| panic!("Could not write to {}", file));
}

40
xtask/src/main.rs Normal file
View file

@ -0,0 +1,40 @@
mod docgen;
mod path;
use std::{env, error::Error};
type DynError = Box<dyn Error>;
pub mod tasks {
use crate::docgen::USER_GUIDE;
use crate::docgen::{userguide, write};
use crate::DynError;
pub fn docgen() -> Result<(), DynError> {
write(USER_GUIDE, &userguide()?);
Ok(())
}
pub fn print_help() {
println!(
"
Usage: `cargo xtask <task>`
Tasks:
docgen: Generate Markdown files.
"
);
}
}
fn main() -> Result<(), DynError> {
let task = env::args().nth(1);
match task {
None => tasks::print_help(),
Some(t) => match t.as_str() {
"docgen" => tasks::docgen()?,
invalid => return Err(format!("Invalid task: {}", invalid).into()),
},
};
Ok(())
}

12
xtask/src/path.rs Normal file
View file

@ -0,0 +1,12 @@
use std::path::{Path, PathBuf};
pub fn project_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.to_path_buf()
}
pub fn docs() -> PathBuf {
project_root().join("docs/")
}