Compare commits

...

177 Commits

Author SHA1 Message Date
7ce32cc320 Update CHANGELOG.md (#9659)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-05 00:13:55 +00:00
0e263ad54e Update versions.json (#9658)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-05 01:13:24 +01:00
85c20e3b25 Update CHANGELOG.md (#9654)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-04 21:00:26 +00:00
268464781e update pdm repo to stable (#9648) 2025-12-04 22:00:02 +01:00
775caae9c9 Update CHANGELOG.md (#9653)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-04 18:41:27 +00:00
0f7c201b57 core: extend storage type support (rbd, nfs, cifs) and validation (iscidirect, isci, zfs, cephfs, pbs) (#9646)
* core: enhance storage type validation and error codes

Improve storage validation for LXC container creation with
explicit checks for unsupported storage types.

Changes:
- Add validation for storage types that don't support containers:
  - iscsidirect (exit 212) - VMs only
  - iscsi/zfs (exit 213) - no rootdir support
  - cephfs (exit 219) - use RBD instead
  - pbs (exit 224) - backups only
- Add connectivity check for network storage (linstor, rbd, nfs, cifs)
- Simplify storage content validation using pvesm status
- Reorganize Proxmox error codes (200-231) for consistency
- Update error messages to be more descriptive and actionable

This helps users identify storage compatibility issues early
before container creation fails with cryptic errors.

* Update build.func
2025-12-04 19:41:01 +01:00
5780dc1532 Update CHANGELOG.md (#9650)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-04 15:55:26 +00:00
5333e9f4b6 Fix kimai.sh update script path typo for local.yaml (#9645)
* Initial plan

* Fix typo in kimai.sh: correct config path to config/packages/local.yaml

Co-authored-by: MickLesk <47820557+MickLesk@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: MickLesk <47820557+MickLesk@users.noreply.github.com>
2025-12-04 16:55:00 +01:00
513e11569b Update versions.json (#9642)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-04 13:06:00 +01:00
9ed56051b9 Update CHANGELOG.md (#9640)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-04 08:44:57 +00:00
4b496ebf2e Update CHANGELOG.md 2025-12-04 09:44:31 +01:00
530438a721 chore(frontend): update bun.lock for tooltip component 2025-12-04 09:31:04 +01:00
62201a0872 Refactor DataPage for cleaner imports and UI improvements
Consolidated and reordered import statements for better readability. Simplified JSX formatting and conditional rendering throughout the file. Added error tooltips for failed installations in the log table, improved table cell formatting, and fixed disk size unit from MB to GB. Minor code style and consistency improvements applied across the component.
2025-12-04 09:23:28 +01:00
8e93f5cb1d Improve Temurin JDK version detection
Enhances the setup_java function to attempt a package purge and reinstall if a Temurin JDK is detected but its version cannot be determined. This helps recover from inconsistent or broken JDK installations.
2025-12-04 09:20:32 +01:00
838e663a6d Update CHANGELOG.md (#9638)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-04 06:52:42 +00:00
a826769899 Three-tier defaults system | security improvements | error_handler | improved logging | improved container creation | improved architecture (#9540)
* Refactor Core

Refactored misc/alpine-install.func to improve error handling, network checks, and MOTD setup. Added misc/alpine-tools.func and misc/error_handler.func for modular tool installation and error management. Enhanced misc/api.func with detailed exit code explanations and telemetry functions. Updated misc/core.func for better initialization, validation, and execution helpers. Removed misc/create_lxc.sh as part of cleanup.

* Delete config-file.func

* Update install.func

* Refactor stop_all_services function and variable names

Refactor service stopping logic and improve variable handling

* Refactor installation script and update copyright

Updated copyright information and adjusted package installation commands. Enhanced IPv6 disabling logic and improved container customization process.

* Update install.func

* Update license comment format in install.func

* Refactor IPv6 handling and enhance MOTD and SSH

Refactor IPv6 handling and update OS function. Enhance MOTD with additional details and configure SSH settings.

* big core refactor

* Enhance IPv6 configuration menu options

Updated IPv6 Address Management menu options for clarity and added a new option for fully disabling IPv6.

* Update default Node.js version to 24 LTS

* Update misc/alpine-tools.func

Co-authored-by: Michel Roegl-Brunner <73236783+michelroegl-brunner@users.noreply.github.com>

* indention

* remove debugf and duplicate codes

* Update whiptail backtitles and error codes

Removed '[dev]' from whiptail --backtitle strings for consistency. Refactored custom exit codes in build.func and error_handler.func: updated Proxmox error codes, shifted MySQL/MariaDB codes to 260-263, and removed unused MongoDB code. Updated error descriptions to match new codes.

* comments

* Refactor error handling and clean up debug comments

Standardized bash variable checks, removed unnecessary debug and commented code, and clarified error handling logic in container build and setup scripts. These changes improve code readability and maintainability without altering functional behavior.

* Update build.func

* feat: Improve LXC network checks and LINSTOR storage handling

Enhanced LXC container network setup to check for both IPv4 and IPv6 addresses, added connectivity (ping) tests, and provided troubleshooting tips on failure. Updated storage validation to support LINSTOR, including cluster connectivity checks and special handling for LINSTOR template storage.

---------

Co-authored-by: Michel Roegl-Brunner <73236783+michelroegl-brunner@users.noreply.github.com>
2025-12-04 07:52:18 +01:00
a5e6810872 Update CHANGELOG.md (#9637)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-04 00:13:57 +00:00
7c73dac819 Update versions.json (#9636)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-04 01:13:31 +01:00
cf616cbc9f Update CHANGELOG.md (#9635)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-03 23:06:22 +00:00
84057a657a explicit node versions (#9594) 2025-12-04 00:05:56 +01:00
fc1389ce8f Update CHANGELOG.md (#9634)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-03 22:15:23 +00:00
952c35ecc7 Bump next in /frontend in the npm_and_yarn group across 1 directory (#9632)
Bumps the npm_and_yarn group with 1 update in the /frontend directory: [next](https://github.com/vercel/next.js).


Updates `next` from 15.5.2 to 15.5.7
- [Release notes](https://github.com/vercel/next.js/releases)
- [Changelog](https://github.com/vercel/next.js/blob/canary/release.js)
- [Commits](https://github.com/vercel/next.js/compare/v15.5.2...v15.5.7)

---
updated-dependencies:
- dependency-name: next
  dependency-version: 15.5.7
  dependency-type: direct:production
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-03 23:14:42 +01:00
d41538e1b1 Update CHANGELOG.md (#9633)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-03 21:10:03 +00:00
3b84a80f7a Update logo URL in swizzin.json (#9627) 2025-12-03 22:09:38 +01:00
cb7fb45edb Fix service name mismatch between librespeed-rust install and update scripts (#9628)
* Initial plan

* Fix service name inconsistency - use librespeed-rs for both install and update

Co-authored-by: MickLesk <47820557+MickLesk@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: MickLesk <47820557+MickLesk@users.noreply.github.com>
2025-12-03 21:01:38 +01:00
462b68637d Update CHANGELOG.md (#9631)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-03 19:02:02 +00:00
fb12b1eea6 Fix Homebridge update detection for Debian 13 DEB822 format (#9629)
* Initial plan

* Fix Homebridge update detection for Debian 13

Co-authored-by: MickLesk <47820557+MickLesk@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: MickLesk <47820557+MickLesk@users.noreply.github.com>
2025-12-03 20:01:37 +01:00
41329f919a Update versions.json (#9624)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-03 13:06:00 +01:00
72efc88a96 Update CHANGELOG.md (#9619)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-03 09:05:23 +00:00
d29a11acda Add WorkingDirectory to go2rtc service configuration (#9618) 2025-12-03 10:04:55 +01:00
5fd2a7cade Update CHANGELOG.md (#9617)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-03 07:49:05 +00:00
3d4e7ea986 Update CHANGELOG.md (#9616)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-03 07:48:45 +00:00
7d40b03359 Enable OPNsense VM by setting disable to false 2025-12-03 08:48:43 +01:00
1c9e03d6b7 fix(opnsense-vm): improve script robustness and add single-interface mode (#9614)
- Fix typo in send_line_to_vm: 'shift=x' -> 'shift-x' for uppercase X
- Fix typo in FILE variable: 'Fressbsd.qcow2' -> 'FreeBSD.qcow2'
- Add network mode selection: dual interface (firewall) or single interface (proxy/VPN/IDS)
- Add conditional WAN interface configuration based on selected network mode
- Improve WAN interface setup: only add when WAN_BRG is configured
- Add proper quoting for VM_NAME and CORE_COUNT variable checks
- Improve download URL message formatting
- Remove sleep 2 delay before URL display
- Fix WAN IP configuration: only attempt when WAN bridge is configured
- Clean up whitespace and formatting inconsistencies
- Remove orphaned TEMP_DIR initialization
2025-12-03 08:48:12 +01:00
056d064584 Update CHANGELOG.md (#9612)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-03 00:13:36 +00:00
1603d930ae Update versions.json (#9611)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-03 01:13:11 +01:00
4801aca8aa Update CHANGELOG.md (#9610)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 23:23:24 +00:00
5d1c6a7460 Update category for "Wanderer" (#9607) 2025-12-03 00:22:56 +01:00
c34a229f02 Update CHANGELOG.md (#9606)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 21:32:44 +00:00
6944797213 Set Valkey memory and eviction defaults (#9602) 2025-12-02 22:32:16 +01:00
1b1677ab7c Update CHANGELOG.md (#9604)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 19:34:07 +00:00
833866d097 Fix ExecStart command in matterbridge service install script to allow childbridge mode (#9603) 2025-12-02 20:33:37 +01:00
277abdf0e4 Update CHANGELOG.md (#9599)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 16:11:28 +00:00
3ab710472c Open-webui add .env backup and restore functionality from older versions (#9592) 2025-12-02 17:10:59 +01:00
a06cab39a9 Update CHANGELOG.md (#9598)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 15:37:08 +00:00
0f1db8cc8e Refactor: 2FAuth (#9582)
* Refactor

* Update

* Update
2025-12-02 16:36:44 +01:00
fc2f72b2ac Update CHANGELOG.md (#9596)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 13:55:32 +00:00
433aafe365 Refactor: Paperless-AI (#9588)
Co-authored-by: Tobias <96661824+CrazyWolf13@users.noreply.github.com>
2025-12-02 14:55:02 +01:00
7978c3176c Update CHANGELOG.md (#9593)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 13:34:37 +00:00
e53bb2d825 Add configuration and deployment guides to docs (#9591) 2025-12-02 14:34:14 +01:00
d079ac7d67 Update CHANGELOG.md (#9589)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 12:56:47 +00:00
f513fd09db Refactor (#9583) 2025-12-02 13:56:23 +01:00
fb118eb0ca Refactor Node.js setup command for Matterbridge 2025-12-02 13:39:10 +01:00
dd440be505 Update versions.json (#9587)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 13:06:07 +01:00
dcbec67b65 Update CHANGELOG.md (#9586)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 12:04:48 +00:00
34b17c4b18 Update CHANGELOG.md (#9585)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 12:04:24 +00:00
3bc2c968ab Update date in json (#9584)
Co-authored-by: GitHub Actions <github-actions[bot]@users.noreply.github.com>
2025-12-02 12:04:22 +00:00
188e33485b Snowshare (#9578)
* 'Add new script'

* Update logo URL in snowshare.json

* Update snowshare-install.sh

* Update snowshare-install.sh

* Add source comment for snowshare-install.sh

---------

Co-authored-by: push-app-to-main[bot] <203845782+push-app-to-main[bot]@users.noreply.github.com>
Co-authored-by: Tobias <96661824+CrazyWolf13@users.noreply.github.com>
Co-authored-by: Slaviša Arežina <58952836+tremor021@users.noreply.github.com>
2025-12-02 13:03:59 +01:00
b55deb69ac Update CHANGELOG.md (#9580)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 11:04:22 +00:00
787882db51 NetVisor: patch systemd file to fix new OIDC config (#9562) 2025-12-02 12:03:55 +01:00
3e2c9c997c Update CHANGELOG.md (#9577)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 10:04:42 +00:00
55fed2209d CommaFeed: Bump Java and service file (#9564)
* Bump Java and service file

* Update Java
2025-12-02 11:04:22 +01:00
b4feb4331d Update CHANGELOG.md (#9576)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 10:04:18 +00:00
183dc7ac69 Refactor: BookStack (#9567)
* Refactor

* Fix db names
2025-12-02 11:03:56 +01:00
d52908bd6e Update CHANGELOG.md (#9574)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 08:51:13 +00:00
327cb37a55 Add auth via requirepass to Valkey (#9570)
* Add auth via requirepass to Valkey

* Refactor notes in valkey.json for clarity

Updated notes structure to include detailed login instructions.

* Remove password saving message from installation script

Removed message indicating Valkey password saving.

* Fix JSON syntax error in valkey.json

* Update valkey.json

* refactor

---------

Co-authored-by: CanbiZ <47820557+MickLesk@users.noreply.github.com>
Co-authored-by: Tobias <96661824+CrazyWolf13@users.noreply.github.com>
2025-12-02 09:50:48 +01:00
d2f86996db Update CHANGELOG.md (#9573)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 08:45:26 +00:00
8cf12d7f4d Refactor (#9563) 2025-12-02 09:44:59 +01:00
a2c31c7eaf Update CHANGELOG.md (#9572)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 08:16:35 +00:00
fa5ccdf3f1 Cloudflared: Add repo via helper function (#9565)
* Use setup_deb822_repo

* Fixes
2025-12-02 09:16:14 +01:00
bd21c9f8ad Update CHANGELOG.md (#9571)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 06:05:46 +00:00
6341ca0cf7 Booklore: Downgrad Java from 25 to 21 (#9566)
* Downgrade Java version from 25 to 21

https://github.com/booklore-app/booklore/pull/1697/files

* Downgrade Java version from 25 to 21 in installer

https://github.com/booklore-app/booklore/pull/1697/files
2025-12-02 07:05:24 +01:00
2a20c5b22d Update CHANGELOG.md (#9569)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 00:13:29 +00:00
279427f38d Update versions.json (#9568)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-02 01:13:01 +01:00
2bd3b8bffa Update CHANGELOG.md (#9561)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-01 19:50:12 +00:00
c7ecc9cd13 Update CHANGELOG.md (#9560)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-01 19:49:27 +00:00
3d99dfd218 Update date in json (#9559)
Co-authored-by: GitHub Actions <github-actions[bot]@users.noreply.github.com>
2025-12-01 19:49:24 +00:00
11f1fdf2fa Wanderer (#9556)
* 'Add new script'

* refactor

---------

Co-authored-by: push-app-to-main[bot] <203845782+push-app-to-main[bot]@users.noreply.github.com>
Co-authored-by: Tobias <96661824+CrazyWolf13@users.noreply.github.com>
2025-12-01 20:48:49 +01:00
3596312f20 Update CHANGELOG.md (#9558)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-01 19:35:34 +00:00
e5cc0a4726 core: sanitize appname for certificate generation (#9552)
* Update SSL key and certificate paths for Actual Budget

* Use lowercase app name for certificate paths

* revert changes at actualbudget

---------

Co-authored-by: CanbiZ <47820557+MickLesk@users.noreply.github.com>
2025-12-01 20:35:12 +01:00
c34659ced2 Update CHANGELOG.md (#9555)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-01 19:08:13 +00:00
c5eae09b93 Fix Django superuser creation failing with ImproperlyConfigured error (#9554)
* Initial plan

* Fix Django superuser creation by using manage.py shell

Co-authored-by: MickLesk <47820557+MickLesk@users.noreply.github.com>

* Add $STD prefix to superuser creation for consistency

Co-authored-by: MickLesk <47820557+MickLesk@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: MickLesk <47820557+MickLesk@users.noreply.github.com>
2025-12-01 20:07:39 +01:00
fd8a305129 fix unbound env 2025-12-01 19:31:16 +01:00
64d0070756 unbound var 2025-12-01 19:23:08 +01:00
5dcada4ef9 fix wrong var 2025-12-01 19:22:27 +01:00
452007b654 Update CHANGELOG.md (#9549)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-01 17:30:22 +00:00
6cf4eb603a update selfhst icon-URLs to use @master path (#9543)
* update selfhst icon-URLs to use @master path

Changed all icon URLs in JSON files from 'cdn.jsdelivr.net/gh/selfhst/icons/webp/' to 'cdn.jsdelivr.net/gh/selfhst/icons@master/webp/' for consistency and to ensure the latest icons are referenced.

* added missing icons
2025-12-01 18:29:58 +01:00
1b40a62959 Refactor: Mealie (#9308)
* Refactor: Mealie

Updated Node.js version and adjusted database setup. Improved installation steps for Python dependencies and NLTK data.

* Update mealie.sh

* Modify mealie-install.sh for dependencies and config

Updated dependencies and added environment variables for Mealie installation.

* Update logo URL and increase RAM requirement

* Increase default RAM allocation from 2048 to 3072

* Update Mealie installation script for versioning and settings

* Update mealie.sh
2025-12-01 18:29:51 +01:00
01cba0213f Update CHANGELOG.md (#9548)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-01 17:26:57 +00:00
6f12aa7a5d Bump Baikal to deb13 (#9544)
Bump default OS version to Debian 13 and PHP to 8.3 in Baikal install scripts and config. Add curl to PHP modules. Refactor PostgreSQL database setup to use new variable names and helper function for credentials.
2025-12-01 18:26:30 +01:00
ec182aeaaf Update CHANGELOG.md (#9547)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-01 17:25:37 +00:00
4d4095cd7d Enhance MariaDB version fallback logic (#9545)
Updated fallback mechanism for MariaDB version retrieval to use mariadb_repo_setup script when the mirror is unreachable.
2025-12-01 18:25:08 +01:00
40ccccb557 Update CHANGELOG.md (#9546)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-01 17:24:39 +00:00
59b80031fe Refactor: Healthchecks (#9188)
* Refactor: Healthchecks

* Enhance healthchecks update process with backup and venv

Added backup creation for existing healthchecks installation before updating. Enhanced the update process by recreating the Python virtual environment and installing requirements.

* -

Added copyright, author, and license information.
2025-12-01 18:24:16 +01:00
1294b89fcb add comprehensive documentation (#9537) 2025-12-01 13:50:11 +01:00
605c11d43f Update CHANGELOG.md (#9541)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-01 12:50:05 +00:00
b0586e347c core: add cloud-init.func library for VM configuration (#9538) 2025-12-01 13:49:42 +01:00
ce42f9077a Update versions.json (#9539)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-01 13:05:53 +01:00
d0f82d7c23 Update CHANGELOG.md (#9533)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-01 00:17:15 +00:00
1ec9a00abf Update versions.json (#9532)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-12-01 01:16:49 +01:00
8ab9666368 Update CHANGELOG.md (#9530)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-30 22:16:15 +00:00
fc559e0e09 Update CHANGELOG.md (#9529)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-30 18:15:21 +00:00
380bf26d38 fix(recyclarr): remove update script systemctl commands (#9522) 2025-11-30 19:15:01 +01:00
c1f7d3d8d7 Update CHANGELOG.md (#9527)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-30 16:34:42 +00:00
33489e607b Refactor: Actual Budget (#9518)
* Update create_self_signed_cert function

* Refactor

* Remove old version file check
2025-11-30 17:34:14 +01:00
877a25c0cc Update versions.json (#9525)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-30 13:05:24 +01:00
8c0abc9ffb Update CHANGELOG.md (#9520)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-30 00:15:35 +00:00
a43e287db2 Update versions.json (#9519)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-30 01:15:08 +01:00
1cd394a754 Update CHANGELOG.md (#9513)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-29 21:54:23 +00:00
04bd9af89c Update CHANGELOG.md (#9512)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-29 21:54:07 +00:00
4d8fa37ba0 Update date in json (#9511)
Co-authored-by: GitHub Actions <github-actions[bot]@users.noreply.github.com>
2025-11-29 21:54:02 +00:00
b4fe802d49 'Add new script' (#9510)
Co-authored-by: push-app-to-main[bot] <203845782+push-app-to-main[bot]@users.noreply.github.com>
2025-11-29 22:53:41 +01:00
9b6c816c6f Update CHANGELOG.md (#9508)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-29 19:12:54 +00:00
769e541938 Fix duplicate ORIGIN in .env for OpenArchiver install script (#9503)
* Initial plan

* Fix duplicate ORIGIN in .env for OpenArchiver install script

Co-authored-by: MickLesk <47820557+MickLesk@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: MickLesk <47820557+MickLesk@users.noreply.github.com>
2025-11-29 20:12:28 +01:00
af9491d70d Remove Documenso (#9507)
* Delete ct/documenso.sh

* Delete ct/headers/documenso

* Delete install/documenso-install.sh

* Delete frontend/public/json/documenso.json
2025-11-29 19:01:45 +01:00
38dd38a9e2 Update CHANGELOG.md (#9505)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-29 15:13:44 +00:00
5465a5dc58 Update Discord link (#9499) 2025-11-29 16:13:20 +01:00
5c6e73d4b6 Update versions.json (#9501)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-29 13:05:48 +01:00
f3c2ca6f8a Update CHANGELOG.md (#9497)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-29 00:12:48 +00:00
64df48c9b5 Update versions.json (#9496)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-29 01:12:26 +01:00
9f20c898fb Update CHANGELOG.md (#9495)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-28 21:52:55 +00:00
efdb44bc2e Update CHANGELOG.md (#9493)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-28 20:22:29 +00:00
8caec1d13e Update apache-guacamole-install.sh issue #9458 (#9492)
Issue 9458
2025-11-28 21:22:04 +01:00
39388a1b77 Remove Habitica (#9489) 2025-11-28 14:31:47 +01:00
91b80caaa5 Update versions.json (#9488)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-28 13:07:10 +01:00
dc3736146a Update CHANGELOG.md (#9486)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-28 00:14:09 +00:00
40edc3e908 Update versions.json (#9485)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-28 01:13:45 +01:00
92bc24d1e5 Update CHANGELOG.md (#9483)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-27 14:24:38 +00:00
bdef4cbfef PBS: fix typo (#9482)
* fix PBS warning typo

* lowercase IPv6

---------

Co-authored-by: jharmsen <jharmsen@JH-MBA.local>
2025-11-27 15:24:08 +01:00
7d47eb81e9 Update CHANGELOG.md (#9481)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-27 13:31:39 +00:00
276ce230f3 Upgrade pve-scripts-local to node 24 (#9457)
Co-authored-by: CanbiZ <47820557+MickLesk@users.noreply.github.com>
Co-authored-by: Tobias <96661824+CrazyWolf13@users.noreply.github.com>
2025-11-27 14:31:15 +01:00
5f911164e3 Fix MongoDB setup version assignment 2025-11-27 14:02:11 +01:00
8c6843f180 Update versions.json (#9477)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-27 13:05:49 +01:00
5004477246 Update CHANGELOG.md (#9474)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-27 08:14:01 +00:00
8e15e0a524 Update date in json (#9473)
Co-authored-by: GitHub Actions <github-actions[bot]@users.noreply.github.com>
2025-11-27 08:13:36 +00:00
54b634cea4 Qdrant (#9465)
* 'Add new script'

* Update qdrant.sh

* Update qdrant.json

---------

Co-authored-by: push-app-to-main[bot] <203845782+push-app-to-main[bot]@users.noreply.github.com>
Co-authored-by: CanbiZ <47820557+MickLesk@users.noreply.github.com>
2025-11-27 09:13:15 +01:00
d4e1b8f354 Update CHANGELOG.md (#9470)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-27 00:12:56 +00:00
1a4f9ff815 Update versions.json (#9469)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-27 01:12:34 +01:00
ee3d4874d1 Update CHANGELOG.md (#9463)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-26 13:19:49 +00:00
Cam
01442d08ec Fix Open-WebUI install and upgrade commands (#9461) 2025-11-26 14:19:24 +01:00
e1bf05ad69 Update CHANGELOG.md (#9462)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-26 12:49:34 +00:00
7d435a1a5e Increase RAM for LXC (#9460) 2025-11-26 13:49:07 +01:00
7184755a0f Update versions.json (#9459)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-26 13:07:04 +01:00
f0a23be999 Update CHANGELOG.md (#9451)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-26 00:14:31 +00:00
93a764676f Update versions.json (#9450)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-26 01:14:11 +01:00
21e9030946 Update CHANGELOG.md (#9449)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-25 22:59:01 +00:00
01774b1967 Change install command to upgrade for Open-WebUI (#9448) 2025-11-25 23:58:39 +01:00
63c5b922de Remove pip cache purge from cleanup script
Removed pip cache purge command from cleanup function.
2025-11-25 22:24:16 +01:00
789cd3e187 Update CHANGELOG.md (#9446)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-25 21:13:16 +00:00
282e8ef186 Update CHANGELOG.md (#9444)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-25 19:39:04 +00:00
8a0b1d864b Update install scripts for improved dependency handling (#9441)
Replaces 'npm ci' with 'npm install --legacy-peer-deps' in install and update scripts to address peer dependency issues. Adds global npm update and turbo prune steps to the update script for better Docker build support.
2025-11-25 20:38:35 +01:00
d2a103c230 Set default LANG in locale configuration (#9440)
Ensures LANG is set to en_US.UTF-8 by default if not already defined before updating /etc/locale.gen.
2025-11-25 20:32:18 +01:00
949ecc39ad Update CHANGELOG.md (#9443)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-25 19:31:24 +00:00
a9c08a611e Refactor Asterisk installation process (#9429)
Refactor Asterisk installation script to fetch versions directly from Asterisk download URLs and streamline dependency installation.
2025-11-25 20:31:00 +01:00
e13119250d Add missing config files to build output 2025-11-25 18:34:14 +01:00
87f71f75b1 Update CHANGELOG.md (#9439)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-25 17:21:39 +00:00
3b6e5aae5f paperless: patch consume to uv (#9425) 2025-11-25 18:21:15 +01:00
f90fdadbb2 Update CHANGELOG.md (#9438)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-25 17:15:09 +00:00
120affbcc5 Add Zabbix version selection to install and update scripts (#9430)
Prompts user to select Zabbix version (7.0 LTS, 7.4, or latest) during installation and update. Refactors download logic to use the chosen version, improving flexibility and user control over Zabbix deployment.
2025-11-25 18:14:37 +01:00
ae81cafa10 Update CHANGELOG.md (#9437)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-25 17:08:37 +00:00
f60493a862 attempt to fix mtk (#9434) 2025-11-25 18:08:11 +01:00
0cbce2287d Update versions.json (#9428)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-25 13:08:31 +01:00
edfeda61ad Update source URL in domain-locker-install.sh (#9423) 2025-11-25 09:51:25 +01:00
1815fee99b Update CHANGELOG.md (#9424)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-25 07:53:11 +00:00
4bf830c6bf gh: update supported PVE Version (#9422)
* gh: update supported PVE Version

* Update supported versions in SECURITY.md
2025-11-25 08:52:46 +01:00
d0cced9a1d Update CHANGELOG.md (#9419)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-25 00:11:49 +00:00
a56f7cfd45 Update versions.json (#9418)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-25 01:11:30 +01:00
79f7852777 Update CHANGELOG.md (#9416)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-24 21:03:42 +00:00
e54f372079 [Fix]: Wizarr DB error during install (#9415)
* test skip scheduler during install & not running migration

- migration is run by the start script anyway, I think

* restore db upgrade during install/update; add new env vars; patch start.sh
2025-11-24 22:03:19 +01:00
cf89b17b0d Update CHANGELOG.md (#9414)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-24 20:35:25 +00:00
bb40a3fdd3 core: remove Python uv cache clean command (#9413) 2025-11-24 21:34:59 +01:00
4ffa571a34 Update CHANGELOG.md (#9409)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-24 17:24:44 +00:00
48f1f07892 Update CHANGELOG.md (#9408)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-24 17:24:18 +00:00
e5e587aa37 Update gitea.json (#9406) 2025-11-24 18:24:15 +01:00
b4bce4964c Joplin-Server: Bump Node.js version from 22 to 24 (#9405) 2025-11-24 18:23:50 +01:00
c8ed59b148 huntarr: disable on website during install issues (#9403) 2025-11-24 18:23:21 +01:00
ce9323ab17 Update versions.json (#9402)
Co-authored-by: GitHub Actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-24 13:05:43 +01:00
585 changed files with 31088 additions and 4703 deletions

View File

@ -10,8 +10,248 @@
> [!CAUTION] > [!CAUTION]
Exercise vigilance regarding copycat or coat-tailing sites that seek to exploit the project's popularity for potentially malicious purposes. Exercise vigilance regarding copycat or coat-tailing sites that seek to exploit the project's popularity for potentially malicious purposes.
## 2025-12-05
## 2025-12-04
### 🆕 New Scripts
- Three-tier defaults system | security improvements | error_handler | improved logging | improved container creation | improved architecture [@MickLesk](https://github.com/MickLesk) ([#9540](https://github.com/community-scripts/ProxmoxVE/pull/9540))
### 🚀 Updated Scripts
- #### 🐞 Bug Fixes
- Fix kimai.sh update script path typo for local.yaml [@Copilot](https://github.com/Copilot) ([#9645](https://github.com/community-scripts/ProxmoxVE/pull/9645))
- #### ✨ New Features
- core: extend storage type support (rbd, nfs, cifs) and validation (iscidirect, isci, zfs, cephfs, pbs) [@MickLesk](https://github.com/MickLesk) ([#9646](https://github.com/community-scripts/ProxmoxVE/pull/9646))
- #### 🔧 Refactor
- update pdm repo to stable [@CrazyWolf13](https://github.com/CrazyWolf13) ([#9648](https://github.com/community-scripts/ProxmoxVE/pull/9648))
## 2025-12-03
### 🚀 Updated Scripts
- fix(opnsense-vm): improve script and add single-interface mode [@AlphaLawless](https://github.com/AlphaLawless) ([#9614](https://github.com/community-scripts/ProxmoxVE/pull/9614))
- #### 🐞 Bug Fixes
- Fix Homebridge update detection for Debian 13 DEB822 format [@Copilot](https://github.com/Copilot) ([#9629](https://github.com/community-scripts/ProxmoxVE/pull/9629))
- go2rtc: Add WorkingDirectory to go2rtc service configuration [@tremor021](https://github.com/tremor021) ([#9618](https://github.com/community-scripts/ProxmoxVE/pull/9618))
- #### 🔧 Refactor
- explicit node versions [@CrazyWolf13](https://github.com/CrazyWolf13) ([#9594](https://github.com/community-scripts/ProxmoxVE/pull/9594))
### 🌐 Website
- Bump next from 15.5.2 to 15.5.7 in /frontend in the npm_and_yarn group across 1 directory [@dependabot[bot]](https://github.com/dependabot[bot]) ([#9632](https://github.com/community-scripts/ProxmoxVE/pull/9632))
- #### 📝 Script Information
- Update logo URL in swizzin.json [@MickLesk](https://github.com/MickLesk) ([#9627](https://github.com/community-scripts/ProxmoxVE/pull/9627))
## 2025-12-02
### 🆕 New Scripts
- Snowshare ([#9578](https://github.com/community-scripts/ProxmoxVE/pull/9578))
### 🚀 Updated Scripts
- NetVisor: patch systemd file to fix new OIDC config [@vhsdream](https://github.com/vhsdream) ([#9562](https://github.com/community-scripts/ProxmoxVE/pull/9562))
- Refactor: BookStack [@tremor021](https://github.com/tremor021) ([#9567](https://github.com/community-scripts/ProxmoxVE/pull/9567))
- #### 🐞 Bug Fixes
- Matterbridge: Fix ExecStart command in service install script to allow childbridge mode [@jonalbr](https://github.com/jonalbr) ([#9603](https://github.com/community-scripts/ProxmoxVE/pull/9603))
- Open-webui add .env backup and restore functionality from older versions [@DrDonoso](https://github.com/DrDonoso) ([#9592](https://github.com/community-scripts/ProxmoxVE/pull/9592))
- Booklore: Downgrad Java from 25 to 21 [@Pr0mises](https://github.com/Pr0mises) ([#9566](https://github.com/community-scripts/ProxmoxVE/pull/9566))
- #### ✨ New Features
- Set Valkey memory and eviction defaults [@pshankinclarke](https://github.com/pshankinclarke) ([#9602](https://github.com/community-scripts/ProxmoxVE/pull/9602))
- Add auth via requirepass to Valkey [@pshankinclarke](https://github.com/pshankinclarke) ([#9570](https://github.com/community-scripts/ProxmoxVE/pull/9570))
- #### 🔧 Refactor
- Refactor: 2FAuth [@tremor021](https://github.com/tremor021) ([#9582](https://github.com/community-scripts/ProxmoxVE/pull/9582))
- Refactor: Paperless-AI [@MickLesk](https://github.com/MickLesk) ([#9588](https://github.com/community-scripts/ProxmoxVE/pull/9588))
- Refactor: AdventureLog [@tremor021](https://github.com/tremor021) ([#9583](https://github.com/community-scripts/ProxmoxVE/pull/9583))
- CommaFeed: Bump Java and service file [@tremor021](https://github.com/tremor021) ([#9564](https://github.com/community-scripts/ProxmoxVE/pull/9564))
- Refactor: Docmost [@tremor021](https://github.com/tremor021) ([#9563](https://github.com/community-scripts/ProxmoxVE/pull/9563))
- Cloudflared: Add repo via helper function [@tremor021](https://github.com/tremor021) ([#9565](https://github.com/community-scripts/ProxmoxVE/pull/9565))
### 🧰 Maintenance
- #### 📝 Documentation
- add configuration and deployment guides to docs [@MickLesk](https://github.com/MickLesk) ([#9591](https://github.com/community-scripts/ProxmoxVE/pull/9591))
### 🌐 Website
- #### 📝 Script Information
- Update category for "Wanderer" [@Lorondos](https://github.com/Lorondos) ([#9607](https://github.com/community-scripts/ProxmoxVE/pull/9607))
## 2025-12-01
### 🆕 New Scripts
- Wanderer ([#9556](https://github.com/community-scripts/ProxmoxVE/pull/9556))
- core: add cloud-init.func library for VM configuration [@MickLesk](https://github.com/MickLesk) ([#9538](https://github.com/community-scripts/ProxmoxVE/pull/9538))
### 🚀 Updated Scripts
- #### 🐞 Bug Fixes
- core: sanitize appname for certificate generation [@tremor021](https://github.com/tremor021) ([#9552](https://github.com/community-scripts/ProxmoxVE/pull/9552))
- Fix Django superuser creation failing with ImproperlyConfigured error [@Copilot](https://github.com/Copilot) ([#9554](https://github.com/community-scripts/ProxmoxVE/pull/9554))
- #### ✨ New Features
- Bump Baikal to deb13 [@MickLesk](https://github.com/MickLesk) ([#9544](https://github.com/community-scripts/ProxmoxVE/pull/9544))
- Enhance MariaDB version fallback logic [@MickLesk](https://github.com/MickLesk) ([#9545](https://github.com/community-scripts/ProxmoxVE/pull/9545))
- #### 💥 Breaking Changes
- Refactor: Healthchecks [@MickLesk](https://github.com/MickLesk) ([#9188](https://github.com/community-scripts/ProxmoxVE/pull/9188))
- #### 🔧 Refactor
- Refactor: Mealie [@MickLesk](https://github.com/MickLesk) ([#9308](https://github.com/community-scripts/ProxmoxVE/pull/9308))
### 🧰 Maintenance
- #### 📂 Github
- add comprehensive documentation (core, develop, functions, technical guide, contributor guide) [@MickLesk](https://github.com/MickLesk) ([#9537](https://github.com/community-scripts/ProxmoxVE/pull/9537))
### 🌐 Website
- #### 📝 Script Information
- update selfhst icon-URLs to use @master path [@MickLesk](https://github.com/MickLesk) ([#9543](https://github.com/community-scripts/ProxmoxVE/pull/9543))
## 2025-11-30
### 🚀 Updated Scripts
- #### 🐞 Bug Fixes
- fix(recyclarr): remove update script systemctl commands [@vidonnus](https://github.com/vidonnus) ([#9522](https://github.com/community-scripts/ProxmoxVE/pull/9522))
- #### 🔧 Refactor
- Refactor: Actual Budget [@tremor021](https://github.com/tremor021) ([#9518](https://github.com/community-scripts/ProxmoxVE/pull/9518))
## 2025-11-29
### 🆕 New Scripts
- Valkey ([#9510](https://github.com/community-scripts/ProxmoxVE/pull/9510))
### 🚀 Updated Scripts
- #### 🐞 Bug Fixes
- Fix duplicate ORIGIN in .env for OpenArchiver install script [@Copilot](https://github.com/Copilot) ([#9503](https://github.com/community-scripts/ProxmoxVE/pull/9503))
- #### 💥 Breaking Changes
- Remove: Documenso [@michelroegl-brunner](https://github.com/michelroegl-brunner) ([#9507](https://github.com/community-scripts/ProxmoxVE/pull/9507))
### 🌐 Website
- Update Discord link on website [@tremor021](https://github.com/tremor021) ([#9499](https://github.com/community-scripts/ProxmoxVE/pull/9499))
## 2025-11-28
### 🚀 Updated Scripts
- #### 🐞 Bug Fixes
- Apache-guacamole: fixed to early rm [@mtorazzi](https://github.com/mtorazzi) ([#9492](https://github.com/community-scripts/ProxmoxVE/pull/9492))
- #### 💥 Breaking Changes
- Remove: Habitica [@MickLesk](https://github.com/MickLesk) ([#9489](https://github.com/community-scripts/ProxmoxVE/pull/9489))
## 2025-11-27
### 🆕 New Scripts
- Qdrant ([#9465](https://github.com/community-scripts/ProxmoxVE/pull/9465))
### 🚀 Updated Scripts
- #### 💥 Breaking Changes
- Upgrade pve-scripts-local to node 24 [@michelroegl-brunner](https://github.com/michelroegl-brunner) ([#9457](https://github.com/community-scripts/ProxmoxVE/pull/9457))
### 🌐 Website
- #### 🐞 Bug Fixes
- PBS: fix typo [@joshuaharmsen845](https://github.com/joshuaharmsen845) ([#9482](https://github.com/community-scripts/ProxmoxVE/pull/9482))
## 2025-11-26
### 🚀 Updated Scripts
- Joplin Server: Increase RAM for LXC [@tremor021](https://github.com/tremor021) ([#9460](https://github.com/community-scripts/ProxmoxVE/pull/9460))
- #### 🐞 Bug Fixes
- Fix Open WebUI update logic (swap upgrade/install) [@camcop](https://github.com/camcop) ([#9461](https://github.com/community-scripts/ProxmoxVE/pull/9461))
## 2025-11-25
### 🚀 Updated Scripts
- #### 🐞 Bug Fixes
- Open WebUI: Change install command to upgrade for Open-WebUI [@tremor021](https://github.com/tremor021) ([#9448](https://github.com/community-scripts/ProxmoxVE/pull/9448))
- core: set default LANG in locale configuration [@MickLesk](https://github.com/MickLesk) ([#9440](https://github.com/community-scripts/ProxmoxVE/pull/9440))
- documenso: switch to npm peer-.deps to get build running [@MickLesk](https://github.com/MickLesk) ([#9441](https://github.com/community-scripts/ProxmoxVE/pull/9441))
- Refactor Asterisk installation process [@MickLesk](https://github.com/MickLesk) ([#9429](https://github.com/community-scripts/ProxmoxVE/pull/9429))
- Fix the mikrotik VM installer after they reformatted their downloads page [@paul-ridgway](https://github.com/paul-ridgway) ([#9434](https://github.com/community-scripts/ProxmoxVE/pull/9434))
- paperless: patch consume to uv [@MickLesk](https://github.com/MickLesk) ([#9425](https://github.com/community-scripts/ProxmoxVE/pull/9425))
- #### ✨ New Features
- add Zabbix version selection to install and update scripts [@MickLesk](https://github.com/MickLesk) ([#9430](https://github.com/community-scripts/ProxmoxVE/pull/9430))
### 🧰 Maintenance
- #### 📂 Github
- gh: update supported PVE Version [@MickLesk](https://github.com/MickLesk) ([#9422](https://github.com/community-scripts/ProxmoxVE/pull/9422))
## 2025-11-24 ## 2025-11-24
### 🚀 Updated Scripts
- #### 🐞 Bug Fixes
- core: remove uv cache clean command [@MickLesk](https://github.com/MickLesk) ([#9413](https://github.com/community-scripts/ProxmoxVE/pull/9413))
- Joplin-Server: Bump Node.js version from 22 to 24 [@tremor021](https://github.com/tremor021) ([#9405](https://github.com/community-scripts/ProxmoxVE/pull/9405))
- #### 🔧 Refactor
- [Fix]: Wizarr DB error during install [@vhsdream](https://github.com/vhsdream) ([#9415](https://github.com/community-scripts/ProxmoxVE/pull/9415))
### 🌐 Website
- #### 📝 Script Information
- Gitea: Update website [@tremor021](https://github.com/tremor021) ([#9406](https://github.com/community-scripts/ProxmoxVE/pull/9406))
- huntarr: disable on website during install issues [@MickLesk](https://github.com/MickLesk) ([#9403](https://github.com/community-scripts/ProxmoxVE/pull/9403))
## 2025-11-23 ## 2025-11-23
### 🚀 Updated Scripts ### 🚀 Updated Scripts

View File

@ -105,7 +105,7 @@
<tr> <tr>
<td align="center" width="33%"> <td align="center" width="33%">
<h3>🖥️ Proxmox VE</h3> <h3>🖥️ Proxmox VE</h3>
<p>Version 8.4.x or 9.0.x</p> <p>Version: 8.4.x | 9.0.x | 9.1.x</p>
</td> </td>
<td align="center" width="33%"> <td align="center" width="33%">
<h3>🐧 Operating System</h3> <h3>🐧 Operating System</h3>

View File

@ -6,6 +6,7 @@ This project currently supports the following versions of Proxmox VE (PVE):
| Version | Supported | | Version | Supported |
| ------- | ------------------ | | ------- | ------------------ |
| 9.1.x | :white_check_mark: |
| 9.0.x | :white_check_mark: | | 9.0.x | :white_check_mark: |
| 8.4.x | :white_check_mark: | | 8.4.x | :white_check_mark: |
| 8.3.x | Limited support* ❕ | | 8.3.x | Limited support* ❕ |

View File

@ -40,10 +40,7 @@ function update_script() {
msg_ok "Backup Created" msg_ok "Backup Created"
if ! dpkg -l | grep -q 'php8.3'; then if ! dpkg -l | grep -q 'php8.3'; then
$STD apt-get install -y \ PHP_VERSION="8.3" PHP_MODULE="common,ctype,fileinfo,mysql,cli,tokenizer,dom,redis,session,openssl" PHP_FPM="YES" setup_php
lsb-release \
gnupg2
PHP_VERSION="8.3" PHP_MODULE="common,ctype,fileinfo,mysql,cli" PHP_FPM="YES" setup_php
sed -i 's/php8.2/php8.3/g' /etc/nginx/conf.d/2fauth.conf sed -i 's/php8.2/php8.3/g' /etc/nginx/conf.d/2fauth.conf
fi fi
fetch_and_deploy_gh_release "2fauth" "Bubka/2FAuth" fetch_and_deploy_gh_release "2fauth" "Bubka/2FAuth"

View File

@ -24,33 +24,32 @@ function update_script() {
check_container_storage check_container_storage
check_container_resources check_container_resources
if [[ ! -f /opt/actualbudget_version.txt ]]; then if [[ ! -f ~/.actualbudget && ! -f /opt/actualbudget_version.txt ]]; then
msg_error "No ${APP} Installation Found!" msg_error "No ${APP} Installation Found!"
exit exit
fi fi
NODE_VERSION="22" setup_nodejs NODE_VERSION="22" setup_nodejs
RELEASE=$(curl -fsSL https://api.github.com/repos/actualbudget/actual/releases/latest | grep "tag_name" | awk '{print substr($2, 3, length($2)-4) }') RELEASE=$(get_latest_github_release "actualbudget/actual")
if [[ -f /opt/actualbudget-data/config.json ]]; then if [[ -f /opt/actualbudget-data/config.json ]]; then
if [[ ! -f /opt/actualbudget_version.txt ]] || [[ "${RELEASE}" != "$(cat /opt/actualbudget_version.txt)" ]]; then if check_for_gh_release "actualbudget" "actualbudget/actual"; then
msg_info "Stopping Service" msg_info "Stopping Service"
systemctl stop actualbudget systemctl stop actualbudget
msg_ok "Stopped Service" msg_ok "Stopped Service"
msg_info "Updating ${APP} to ${RELEASE}" msg_info "Updating Actual Budget to ${RELEASE}"
$STD npm update -g @actual-app/sync-server $STD npm update -g @actual-app/sync-server
echo "${RELEASE}" >/opt/actualbudget_version.txt echo "${RELEASE}" >~/.actualbudget
msg_ok "Updated ${APP} to ${RELEASE}" msg_ok "Updated Actual Budget to ${RELEASE}"
msg_info "Starting Service" msg_info "Starting Service"
systemctl start actualbudget systemctl start actualbudget
msg_ok "Started Service" msg_ok "Started Service"
msg_ok "Updated successfully!" msg_ok "Updated successfully!"
else
msg_info "${APP} is already up to date"
fi fi
else else
msg_info "Old Installation Found, you need to migrate your data and recreate to a new container" msg_info "Old Installation Found, you need to migrate your data and recreate to a new container"
msg_info "Please follow the instructions on the ${APP} website to migrate your data" msg_info "Please follow the instructions on the Actual Budget website to migrate your data"
msg_info "https://actualbudget.org/docs/backup-restore/backup" msg_info "https://actualbudget.org/docs/backup-restore/backup"
exit exit
fi fi

View File

@ -48,7 +48,7 @@ function update_script() {
msg_info "Updating ${APP}" msg_info "Updating ${APP}"
cp /opt/adventurelog-backup/backend/server/.env /opt/adventurelog/backend/server/.env cp /opt/adventurelog-backup/backend/server/.env /opt/adventurelog/backend/server/.env
cp -r /opt/adventurelog-backup/backend/server/media /opt/adventurelog/backend/server/media cp -r /opt/adventurelog-backup/backend/server/media /opt/adventurelog/backend/server/media
cd /opt/adventurelog/backend/server || exit cd /opt/adventurelog/backend/server
if [[ ! -x .venv/bin/python ]]; then if [[ ! -x .venv/bin/python ]]; then
$STD uv venv .venv $STD uv venv .venv
$STD .venv/bin/python -m ensurepip --upgrade $STD .venv/bin/python -m ensurepip --upgrade
@ -59,7 +59,7 @@ function update_script() {
$STD .venv/bin/python -m manage migrate $STD .venv/bin/python -m manage migrate
cp /opt/adventurelog-backup/frontend/.env /opt/adventurelog/frontend/.env cp /opt/adventurelog-backup/frontend/.env /opt/adventurelog/frontend/.env
cd /opt/adventurelog/frontend || exit cd /opt/adventurelog/frontend
$STD pnpm i $STD pnpm i
$STD pnpm build $STD pnpm build
rm -rf /opt/adventurelog-backup rm -rf /opt/adventurelog-backup

View File

@ -11,7 +11,7 @@ var_cpu="${var_cpu:-1}"
var_ram="${var_ram:-512}" var_ram="${var_ram:-512}"
var_disk="${var_disk:-4}" var_disk="${var_disk:-4}"
var_os="${var_os:-debian}" var_os="${var_os:-debian}"
var_version="${var_version:-12}" var_version="${var_version:-13}"
var_unprivileged="${var_unprivileged:-1}" var_unprivileged="${var_unprivileged:-1}"
header_info "$APP" header_info "$APP"
@ -37,8 +37,9 @@ function update_script() {
mv /opt/baikal /opt/baikal-backup mv /opt/baikal /opt/baikal-backup
msg_ok "Backed up data" msg_ok "Backed up data"
fetch_and_deploy_gh_release "baikal" "sabre-io/Baikal" PHP_APACHE="YES" PHP_MODULE="pgsql,curl" PHP_VERSION="8.3" setup_php
setup_composer setup_composer
fetch_and_deploy_gh_release "baikal" "sabre-io/Baikal"
msg_info "Configuring Baikal" msg_info "Configuring Baikal"
cp -r /opt/baikal-backup/config/baikal.yaml /opt/baikal/config/ cp -r /opt/baikal-backup/config/baikal.yaml /opt/baikal/config/

View File

@ -45,7 +45,7 @@ function update_script() {
$STD npm run build --configuration=production $STD npm run build --configuration=production
msg_ok "Built Frontend" msg_ok "Built Frontend"
JAVA_VERSION="25" setup_java JAVA_VERSION="21" setup_java
msg_info "Building Backend" msg_info "Building Backend"
cd /opt/booklore/booklore-api cd /opt/booklore/booklore-api

View File

@ -11,7 +11,7 @@ var_cpu="${var_cpu:-1}"
var_ram="${var_ram:-1024}" var_ram="${var_ram:-1024}"
var_disk="${var_disk:-4}" var_disk="${var_disk:-4}"
var_os="${var_os:-debian}" var_os="${var_os:-debian}"
var_version="${var_version:-12}" var_version="${var_version:-13}"
var_unprivileged="${var_unprivileged:-1}" var_unprivileged="${var_unprivileged:-1}"
header_info "$APP" header_info "$APP"

View File

@ -28,6 +28,9 @@ function update_script() {
msg_error "No ${APP} Installation Found!" msg_error "No ${APP} Installation Found!"
exit exit
fi fi
JAVA_VERSION="25" setup_java
if check_for_gh_release "commafeed" "Athou/commafeed"; then if check_for_gh_release "commafeed" "Athou/commafeed"; then
msg_info "Stopping Service" msg_info "Stopping Service"
systemctl stop commafeed systemctl stop commafeed

View File

@ -1,74 +0,0 @@
#!/usr/bin/env bash
source <(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/misc/build.func)
# Copyright (c) 2021-2025 community-scripts ORG
# Author: MickLesk (CanbiZ)
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE
# Source: https://github.com/documenso/documenso
APP="Documenso"
var_tags="${var_tags:-document}"
var_disk="${var_disk:-12}"
var_cpu="${var_cpu:-6}"
var_ram="${var_ram:-6144}"
var_os="${var_os:-debian}"
var_version="${var_version:-12}"
var_unprivileged="${var_unprivileged:-1}"
header_info "$APP"
variables
color
catch_errors
function update_script() {
header_info
check_container_storage
check_container_resources
if [[ ! -d /opt/documenso ]]; then
msg_error "No ${APP} Installation Found!"
exit
fi
RELEASE=$(curl -fsSL https://api.github.com/repos/documenso/documenso/releases/latest | grep "tag_name" | awk '{print substr($2, 3, length($2)-4) }')
if [[ ! -f /opt/${APP}_version.txt ]] || [[ "${RELEASE}" != "$(cat /opt/${APP}_version.txt)" ]]; then
msg_info "Stopping Service"
systemctl stop documenso
msg_ok "Stopped Service"
msg_info "Updating ${APP} to ${RELEASE}"
cp /opt/documenso/.env /opt/
rm -rf /opt/documenso
cd /opt
curl -fsSL "https://github.com/documenso/documenso/archive/refs/tags/v${RELEASE}.zip" -o v${RELEASE}.zip
$STD unzip v${RELEASE}.zip
mv documenso-${RELEASE} /opt/documenso
cd /opt/documenso
mv /opt/.env /opt/documenso/.env
export TURBO_CACHE=1
export NEXT_TELEMETRY_DISABLED=1
export CYPRESS_INSTALL_BINARY=0
export NODE_OPTIONS="--max-old-space-size=4096"
$STD npm ci
$STD turbo run build --filter=@documenso/remix
$STD npm run prisma:migrate-deploy
$STD turbo daemon stop
rm -rf /opt/v${RELEASE}.zip
echo "${RELEASE}" >/opt/${APP}_version.txt
msg_ok "Updated ${APP}"
msg_info "Starting Service"
systemctl start documenso
msg_ok "Started Service"
msg_ok "Updated successfully!"
else
msg_ok "No update required. ${APP} is already at ${RELEASE}"
fi
exit
}
start
build_container
description
msg_ok "Completed Successfully!\n"
echo -e "${CREATING}${GN}${APP} setup has been successfully initialized!${CL}"
echo -e "${INFO}${YW} Access it using the following URL:${CL}"
echo -e "${TAB}${GATEWAY}${BGN}http://${IP}:3000${CL}"

View File

@ -34,7 +34,7 @@ function update_script() {
msg_info "Service stopped" msg_info "Service stopped"
PG_VERSION="17" setup_postgresql PG_VERSION="17" setup_postgresql
setup_nodejs NODE_VERSION="22" setup_nodejs
CLEAN_INSTALL=1 fetch_and_deploy_gh_release "domain-locker" "Lissy93/domain-locker" CLEAN_INSTALL=1 fetch_and_deploy_gh_release "domain-locker" "Lissy93/domain-locker"
msg_info "Installing Modules (patience)" msg_info "Installing Modules (patience)"

View File

@ -1,82 +0,0 @@
#!/usr/bin/env bash
source <(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/misc/build.func)
# Copyright (c) 2021-2025 community-scripts ORG
# Author: Slaviša Arežina (tremor021)
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE
# Source: https://github.com/HabitRPG/habitica
APP="Habitica"
var_tags="${var_tags:-gaming}"
var_cpu="${var_cpu:-2}"
var_ram="${var_ram:-4096}"
var_disk="${var_disk:-8}"
var_os="${var_os:-debian}"
var_version="${var_version:-12}"
var_unprivileged="${var_unprivileged:-1}"
header_info "$APP"
variables
color
catch_errors
function update_script() {
header_info
check_container_storage
check_container_resources
if [[ ! -d "/opt/habitica" ]]; then
msg_error "No ${APP} Installation Found!"
exit
fi
NODE_VERSION="20" NODE_MODULE="gulp-cli,mocha" setup_nodejs
if check_for_gh_release "habitica" "HabitRPG/habitica"; then
msg_info "Stopping Service"
systemctl stop habitica-mongodb
systemctl stop habitica
systemctl stop habitica-client
msg_info "Stopped Service"
msg_info "Save configuration"
if [[ -f /opt/habitica/config.json ]]; then
cp /opt/habitica/config.json ~/config.json
msg_ok "Saved configuration"
else
msg_warn "No configuration file found, skipping save"
fi
fetch_and_deploy_gh_release "habitica" "HabitRPG/habitica" "tarball" "latest" "/opt/habitica"
msg_info "Updating $APP"
cd /opt/habitica
$STD npm i
$STD npm run postinstall
$STD npm run client:build
$STD gulp build:prod
msg_ok "Updated $APP"
msg_info "Restoring configuration"
if [[ -f ~/config.json ]]; then
cp ~/config.json /opt/habitica/config.json
msg_ok "Restored configuration"
else
msg_warn "No configuration file found to restore"
fi
msg_info "Starting Service"
systemctl start habitica-mongodb
systemctl start habitica
systemctl start habitica-client
msg_ok "Started Service"
msg_ok "Updated successfully!"
fi
exit
}
start
build_container
description
msg_ok "Completed Successfully!\n"
echo -e "${CREATING}${GN}${APP} setup has been successfully initialized!${CL}"
echo -e "${INFO}${YW} Access it using the following URL:${CL}"
echo -e "${TAB}${GATEWAY}${BGN}http://${IP}:3000${CL}"

View File

@ -1,6 +0,0 @@
____
/ __ \____ _______ ______ ___ ___ ____ _________
/ / / / __ \/ ___/ / / / __ `__ \/ _ \/ __ \/ ___/ __ \
/ /_/ / /_/ / /__/ /_/ / / / / / / __/ / / (__ ) /_/ /
/_____/\____/\___/\__,_/_/ /_/ /_/\___/_/ /_/____/\____/

View File

@ -1,6 +0,0 @@
__ __ __ _ __ _
/ / / /___ _/ /_ (_) /_(_)________ _
/ /_/ / __ `/ __ \/ / __/ / ___/ __ `/
/ __ / /_/ / /_/ / / /_/ / /__/ /_/ /
/_/ /_/\__,_/_.___/_/\__/_/\___/\__,_/

6
ct/headers/qdrant Normal file
View File

@ -0,0 +1,6 @@
____ __ __
/ __ \____/ /________ _____ / /_
/ / / / __ / ___/ __ `/ __ \/ __/
/ /_/ / /_/ / / / /_/ / / / / /_
\___\_\__,_/_/ \__,_/_/ /_/\__/

6
ct/headers/snowshare Normal file
View File

@ -0,0 +1,6 @@
_____ _____ __
/ ___/____ ____ _ __/ ___// /_ ____ _________
\__ \/ __ \/ __ \ | /| / /\__ \/ __ \/ __ `/ ___/ _ \
___/ / / / / /_/ / |/ |/ /___/ / / / / /_/ / / / __/
/____/_/ /_/\____/|__/|__//____/_/ /_/\__,_/_/ \___/

6
ct/headers/valkey Normal file
View File

@ -0,0 +1,6 @@
_ __ ____
| | / /___ _/ / /_____ __ __
| | / / __ `/ / //_/ _ \/ / / /
| |/ / /_/ / / ,< / __/ /_/ /
|___/\__,_/_/_/|_|\___/\__, /
/____/

6
ct/headers/wanderer Normal file
View File

@ -0,0 +1,6 @@
_ __ __
| | / /___ _____ ____/ /__ ________ _____
| | /| / / __ `/ __ \/ __ / _ \/ ___/ _ \/ ___/
| |/ |/ / /_/ / / / / /_/ / __/ / / __/ /
|__/|__/\__,_/_/ /_/\__,_/\___/_/ \___/_/

View File

@ -28,26 +28,42 @@ function update_script() {
msg_error "No ${APP} Installation Found!" msg_error "No ${APP} Installation Found!"
exit exit
fi fi
if check_for_gh_release "healthchecks" "healthchecks/healthchecks"; then if check_for_gh_release "healthchecks" "healthchecks/healthchecks"; then
msg_info "Stopping Services" msg_info "Stopping Services"
systemctl stop healthchecks systemctl stop healthchecks
msg_ok "Stopped Services" msg_ok "Stopped Services"
PYTHON_VERSION="3.13" setup_uv msg_info "Backing up existing installation"
BACKUP="/opt/healthchecks-backup-$(date +%F-%H%M)"
cp -a /opt/healthchecks "$BACKUP"
msg_ok "Backup created at $BACKUP"
fetch_and_deploy_gh_release "healthchecks" "healthchecks/healthchecks" fetch_and_deploy_gh_release "healthchecks" "healthchecks/healthchecks"
msg_info "Updating healthchecks"
cd /opt/healthchecks cd /opt/healthchecks
mkdir -p /opt/healthchecks/static-collected/ if [[ -d venv ]]; then
$STD uv pip install wheel gunicorn -r requirements.txt --system rm -rf venv
$STD uv run -- python manage.py makemigrations fi
$STD uv run -- python manage.py migrate --noinput msg_info "Recreating Python venv"
$STD uv run -- python manage.py collectstatic --noinput $STD python3 -m venv venv
$STD uv run -- python manage.py compress $STD source venv/bin/activate
msg_ok "Updated healthchecks" $STD pip install --upgrade pip wheel
msg_ok "Created venv"
msg_info "Installing requirements"
$STD pip install gunicorn -r requirements.txt
msg_ok "Installed requirements"
msg_info "Running Django migrations"
$STD python manage.py migrate --noinput
$STD python manage.py collectstatic --noinput
$STD python manage.py compress
msg_ok "Completed Django migrations and static build"
msg_info "Starting Services" msg_info "Starting Services"
systemctl start healthchecks systemctl start healthchecks
systemctl restart caddy systemctl reload caddy
msg_ok "Started Services" msg_ok "Started Services"
msg_ok "Updated successfully!" msg_ok "Updated successfully!"
fi fi

View File

@ -23,7 +23,7 @@ function update_script() {
header_info header_info
check_container_storage check_container_storage
check_container_resources check_container_resources
if [[ ! -f /etc/apt/sources.list.d/homebridge.list ]]; then if ! dpkg -s homebridge >/dev/null 2>&1; then
msg_error "No ${APP} Installation Found!" msg_error "No ${APP} Installation Found!"
exit exit
fi fi

View File

@ -8,7 +8,7 @@ source <(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxV
APP="Joplin-Server" APP="Joplin-Server"
var_tags="${var_tags:-notes}" var_tags="${var_tags:-notes}"
var_cpu="${var_cpu:-2}" var_cpu="${var_cpu:-2}"
var_ram="${var_ram:-4096}" var_ram="${var_ram:-6144}"
var_disk="${var_disk:-20}" var_disk="${var_disk:-20}"
var_os="${var_os:-debian}" var_os="${var_os:-debian}"
var_version="${var_version:-13}" var_version="${var_version:-13}"
@ -28,6 +28,8 @@ function update_script() {
exit exit
fi fi
NODE_VERSION=24 NODE_MODULE="yarn,npm,pm2" setup_nodejs
if check_for_gh_release "joplin-server" "laurent22/joplin"; then if check_for_gh_release "joplin-server" "laurent22/joplin"; then
msg_info "Stopping Services" msg_info "Stopping Services"
systemctl stop joplin-server systemctl stop joplin-server

View File

@ -56,7 +56,7 @@ function update_script() {
[ -f "$BACKUP_DIR/local.yaml" ] && cp "$BACKUP_DIR/local.yaml" /opt/kimai/config/packages/ [ -f "$BACKUP_DIR/local.yaml" ] && cp "$BACKUP_DIR/local.yaml" /opt/kimai/config/packages/
rm -rf "$BACKUP_DIR" rm -rf "$BACKUP_DIR"
cd /opt/kimai cd /opt/kimai
sed -i '/^admin_lte:/,/^[^[:space:]]/d' config/local.yaml sed -i '/^admin_lte:/,/^[^[:space:]]/d' config/packages/local.yaml
$STD composer install --no-dev --optimize-autoloader $STD composer install --no-dev --optimize-autoloader
$STD bin/console kimai:update $STD bin/console kimai:update
msg_ok "Updated Kimai" msg_ok "Updated Kimai"

View File

@ -30,13 +30,13 @@ function update_script() {
if check_for_gh_release "librespeed-rust" "librespeed/speedtest-rust"; then if check_for_gh_release "librespeed-rust" "librespeed/speedtest-rust"; then
msg_info "Stopping Services" msg_info "Stopping Services"
systemctl stop librespeed_rs systemctl stop librespeed-rs
msg_ok "Services Stopped" msg_ok "Services Stopped"
fetch_and_deploy_gh_release "librespeed-rust" "librespeed/speedtest-rust" "binary" "latest" "/opt/librespeed-rust" "librespeed-rs-x86_64-unknown-linux-gnu.deb" fetch_and_deploy_gh_release "librespeed-rust" "librespeed/speedtest-rust" "binary" "latest" "/opt/librespeed-rust" "librespeed-rs-x86_64-unknown-linux-gnu.deb"
msg_info "Starting Service" msg_info "Starting Service"
systemctl start librespeed_rs systemctl start librespeed-rs
msg_ok "Started Service" msg_ok "Started Service"
msg_ok "Updated successfully!" msg_ok "Updated successfully!"
fi fi

View File

@ -8,7 +8,7 @@ source <(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxV
APP="Mealie" APP="Mealie"
var_tags="${var_tags:-recipes}" var_tags="${var_tags:-recipes}"
var_cpu="${var_cpu:-2}" var_cpu="${var_cpu:-2}"
var_ram="${var_ram:-2048}" var_ram="${var_ram:-3072}"
var_disk="${var_disk:-10}" var_disk="${var_disk:-10}"
var_os="${var_os:-debian}" var_os="${var_os:-debian}"
var_version="${var_version:-13}" var_version="${var_version:-13}"
@ -30,53 +30,61 @@ function update_script() {
fi fi
if check_for_gh_release "mealie" "mealie-recipes/mealie"; then if check_for_gh_release "mealie" "mealie-recipes/mealie"; then
PYTHON_VERSION="3.12" setup_uv PYTHON_VERSION="3.12" setup_uv
NODE_MODULE="yarn" NODE_VERSION="20" setup_nodejs NODE_MODULE="yarn" NODE_VERSION="24" setup_nodejs
msg_info "Stopping Service" msg_info "Stopping Service"
systemctl stop mealie systemctl stop mealie
msg_info "Stopped Service" msg_ok "Stopped Service"
msg_info "Backing up .env and start.sh" msg_info "Backing up Configuration"
cp -f /opt/mealie/mealie.env /opt/mealie/mealie.env.bak cp -f /opt/mealie/mealie.env /opt/mealie.env
cp -f /opt/mealie/start.sh /opt/mealie/start.sh.bak
msg_ok "Backup completed" msg_ok "Backup completed"
fetch_and_deploy_gh_release "mealie" "mealie-recipes/mealie" "tarball" "latest" "/opt/mealie" CLEAN_INSTALL=1 fetch_and_deploy_gh_release "mealie" "mealie-recipes/mealie" "tarball" "latest" "/opt/mealie"
msg_info "Rebuilding Frontend" msg_info "Installing Python Dependencies with uv"
cd /opt/mealie
$STD uv sync --frozen --extra pgsql
msg_ok "Installed Python Dependencies"
msg_info "Building Frontend"
MEALIE_VERSION=$(<$HOME/.mealie)
$STD sed -i "s|https://github.com/mealie-recipes/mealie/commit/|https://github.com/mealie-recipes/mealie/releases/tag/|g" /opt/mealie/frontend/pages/admin/site-settings.vue
$STD sed -i "s|value: data.buildId,|value: \"v${MEALIE_VERSION}\",|g" /opt/mealie/frontend/pages/admin/site-settings.vue
$STD sed -i "s|value: data.production ? i18n.t(\"about.production\") : i18n.t(\"about.development\"),|value: \"bare-metal\",|g" /opt/mealie/frontend/pages/admin/site-settings.vue
export NUXT_TELEMETRY_DISABLED=1 export NUXT_TELEMETRY_DISABLED=1
cd /opt/mealie/frontend cd /opt/mealie/frontend
$STD yarn install --prefer-offline --frozen-lockfile --non-interactive --production=false --network-timeout 1000000 $STD yarn install --prefer-offline --frozen-lockfile --non-interactive --production=false --network-timeout 1000000
$STD yarn generate $STD yarn generate
cp -r /opt/mealie/frontend/dist /opt/mealie/mealie/frontend msg_ok "Built Frontend"
msg_ok "Frontend rebuilt"
msg_info "Rebuilding Backend Environment" msg_info "Copying Built Frontend"
mkdir -p /opt/mealie/mealie/frontend
cp -r /opt/mealie/frontend/dist/* /opt/mealie/mealie/frontend/
msg_ok "Copied Frontend"
msg_info "Updating NLTK Data"
mkdir -p /nltk_data/
cd /opt/mealie cd /opt/mealie
$STD /opt/mealie/.venv/bin/poetry self add "poetry-plugin-export>=1.9" $STD uv run python -m nltk.downloader -d /nltk_data averaged_perceptron_tagger_eng
MEALIE_VERSION=$(/opt/mealie/.venv/bin/poetry version --short) msg_ok "Updated NLTK Data"
$STD /opt/mealie/.venv/bin/poetry build --output dist
$STD /opt/mealie/.venv/bin/poetry export --only=main --extras=pgsql --output=dist/requirements.txt
echo "mealie[pgsql]==$MEALIE_VERSION \\" >>dist/requirements.txt
/opt/mealie/.venv/bin/poetry run pip hash dist/mealie-$MEALIE_VERSION*.whl | tail -n1 | tr -d '\n' >>dist/requirements.txt
echo " \\" >>dist/requirements.txt
/opt/mealie/.venv/bin/poetry run pip hash dist/mealie-$MEALIE_VERSION*.tar.gz | tail -n1 >>dist/requirements.txt
msg_ok "Backend prepared"
msg_info "Finalize Installation"
$STD /opt/mealie/.venv/bin/uv pip install --require-hashes -r /opt/mealie/dist/requirements.txt --find-links dist
msg_ok "Mealie installed"
msg_info "Restoring Configuration" msg_info "Restoring Configuration"
mv -f /opt/mealie/mealie.env.bak /opt/mealie/mealie.env mv -f /opt/mealie.env /opt/mealie/mealie.env
mv -f /opt/mealie/start.sh.bak /opt/mealie/start.sh cat <<'STARTEOF' >/opt/mealie/start.sh
#!/bin/bash
set -a
source /opt/mealie/mealie.env
set +a
exec uv run mealie
STARTEOF
chmod +x /opt/mealie/start.sh chmod +x /opt/mealie/start.sh
msg_ok "Configuration restored" msg_ok "Configuration restored"
msg_info "Starting Service" msg_info "Starting Service"
systemctl start mealie systemctl start mealie
msg_ok "Started Service" msg_ok "Started Service"
msg_ok "Update Successful" msg_ok "Updated successfully"
fi fi
exit exit
} }
@ -89,3 +97,4 @@ msg_ok "Completed Successfully!\n"
echo -e "${CREATING}${GN}${APP} setup has been successfully initialized!${CL}" echo -e "${CREATING}${GN}${APP} setup has been successfully initialized!${CL}"
echo -e "${INFO}${YW} Access it using the following URL:${CL}" echo -e "${INFO}${YW} Access it using the following URL:${CL}"
echo -e "${TAB}${GATEWAY}${BGN}http://${IP}:9000${CL}" echo -e "${TAB}${GATEWAY}${BGN}http://${IP}:9000${CL}"

View File

@ -79,6 +79,9 @@ function update_script() {
-e 's| --server-port |:|' \ -e 's| --server-port |:|' \
/etc/systemd/system/netvisor-daemon.service /etc/systemd/system/netvisor-daemon.service
sed -i '/^ \"server_target.*$/d' /root/.config/daemon/config.json sed -i '/^ \"server_target.*$/d' /root/.config/daemon/config.json
if ! grep -q "WorkingD" /etc/systemd/system/netvisor-server.service; then
sed -i '\|simple$|a\WorkingDirectory=/opt/netvisor/backend' /etc/systemd/system/netvisor-server.service
fi
systemctl daemon-reload systemctl daemon-reload
msg_info "Starting services" msg_info "Starting services"

View File

@ -30,7 +30,7 @@ function update_script() {
msg_info "Updating MongoDB" msg_info "Updating MongoDB"
if lscpu | grep -q 'avx'; then if lscpu | grep -q 'avx'; then
MONGO_VERSION="8.0" setup_mongodb MONGO_VERSION="8.0"
else else
msg_error "No AVX detected (CPU-Flag)! We have discontinued support for this. You are welcome to try it manually with a Debian LXC, but due to the many issues with Omada, we currently only support AVX CPUs." msg_error "No AVX detected (CPU-Flag)! We have discontinued support for this. You are welcome to try it manually with a Debian LXC, but due to the many issues with Omada, we currently only support AVX CPUs."
exit 10 exit 10

View File

@ -33,6 +33,7 @@ function update_script() {
msg_info "Creating Backup" msg_info "Creating Backup"
mkdir -p /opt/open-webui-backup mkdir -p /opt/open-webui-backup
cp -a /opt/open-webui/backend/data /opt/open-webui-backup/data || true cp -a /opt/open-webui/backend/data /opt/open-webui-backup/data || true
cp -a /opt/open-webui/.env /opt/open-webui-backup/.env || true
msg_ok "Created Backup" msg_ok "Created Backup"
msg_info "Removing legacy installation" msg_info "Removing legacy installation"
@ -48,6 +49,7 @@ function update_script() {
msg_info "Restoring data" msg_info "Restoring data"
mkdir -p /root/.open-webui mkdir -p /root/.open-webui
cp -a /opt/open-webui-backup/data/* /root/.open-webui/ || true cp -a /opt/open-webui-backup/data/* /root/.open-webui/ || true
cp -a /opt/open-webui-backup/.env /root/.env || true
rm -rf /opt/open-webui-backup || true rm -rf /opt/open-webui-backup || true
msg_ok "Restored data" msg_ok "Restored data"
@ -108,7 +110,7 @@ EOF
msg_info "Updating Open WebUI via uv" msg_info "Updating Open WebUI via uv"
PYTHON_VERSION="3.12" setup_uv PYTHON_VERSION="3.12" setup_uv
$STD uv tool install --python 3.12 open-webui[all] $STD uv tool upgrade --python 3.12 open-webui[all]
systemctl restart open-webui systemctl restart open-webui
msg_ok "Updated Open WebUI" msg_ok "Updated Open WebUI"
msg_ok "Updated successfully!" msg_ok "Updated successfully!"

View File

@ -27,58 +27,33 @@ function update_script() {
msg_error "No ${APP} Installation Found!" msg_error "No ${APP} Installation Found!"
exit exit
fi fi
if ! dpkg -s python3-pip >/dev/null 2>&1; then
$STD apt install -y python3-pip if check_for_gh_release "paperless-ai" "clusterzx/paperless-ai"; then
fi
RELEASE=$(curl -fsSL https://api.github.com/repos/clusterzx/paperless-ai/releases/latest | grep "tag_name" | awk '{print substr($2, 3, length($2)-4) }')
if [[ "${RELEASE}" != "$(cat /opt/${APP}_version.txt)" ]] || [[ ! -f /opt/${APP}_version.txt ]]; then
msg_info "Stopping Service" msg_info "Stopping Service"
systemctl stop paperless-ai systemctl stop paperless-ai paperless-rag
msg_info "Stopped Service" msg_ok "Stopped Service"
msg_info "Updating $APP to v${RELEASE}" fetch_and_deploy_gh_release "paperless-ai" "clusterzx/paperless-ai"
cd /opt
mv /opt/paperless-ai /opt/paperless-ai_bak msg_info "Updating Paperless-AI"
curl -fsSL "https://github.com/clusterzx/paperless-ai/archive/refs/tags/v${RELEASE}.zip" -o $(basename "https://github.com/clusterzx/paperless-ai/archive/refs/tags/v${RELEASE}.zip")
$STD unzip v${RELEASE}.zip
mv paperless-ai-${RELEASE} /opt/paperless-ai
mkdir -p /opt/paperless-ai/data
cp -a /opt/paperless-ai_bak/data/. /opt/paperless-ai/data/
cd /opt/paperless-ai cd /opt/paperless-ai
if [[ ! -f /etc/systemd/system/paperless-rag.service ]]; then source /opt/paperless-ai/venv/bin/activate
cat <<EOF >/etc/systemd/system/paperless-rag.service $STD pip install --upgrade pip
[Unit]
Description=PaperlessAI-RAG Service
After=network.target
[Service]
WorkingDirectory=/opt/paperless-ai
ExecStart=/usr/bin/python3 main.py --host 0.0.0.0 --port 8000 --initialize
Restart=always
[Install]
WantedBy=multi-user.target
EOF
echo "RAG_SERVICE_URL=http://localhost:8000" >>/opt/paperless-ai/data/.env
echo "RAG_SERVICE_ENABLED=true" >>/opt/paperless-ai/data/.env
fi
$STD pip install --no-cache-dir -r requirements.txt $STD pip install --no-cache-dir -r requirements.txt
mkdir -p data/chromadb mkdir -p data/chromadb
$STD npm install $STD npm ci --only=production
rm -rf /opt/v${RELEASE}.zip msg_ok "Updated Paperless-AI"
rm -rf /opt/paperless-ai_bak
echo "${RELEASE}" >/opt/${APP}_version.txt
msg_ok "Updated $APP to v${RELEASE}"
msg_info "Starting Service" msg_info "Starting Service"
systemctl start paperless-rag
sleep 3
systemctl start paperless-ai systemctl start paperless-ai
msg_ok "Started Service" msg_ok "Started Service"
msg_ok "Updated successfully!" msg_ok "Updated successfully!"
else
msg_ok "No update required. ${APP} is already at v${RELEASE}"
fi fi
exit exit
} }
start start
build_container build_container
description description

View File

@ -105,6 +105,7 @@ function update_script() {
msg_ok "Backup completed to $BACKUP_DIR" msg_ok "Backup completed to $BACKUP_DIR"
declare -A PATCHES=( declare -A PATCHES=(
["paperless-consumer.service"]="ExecStart=uv run -- python manage.py document_consumer"
["paperless-scheduler.service"]="ExecStart=uv run -- celery --app paperless beat --loglevel INFO" ["paperless-scheduler.service"]="ExecStart=uv run -- celery --app paperless beat --loglevel INFO"
["paperless-task-queue.service"]="ExecStart=uv run -- celery --app paperless worker --loglevel INFO" ["paperless-task-queue.service"]="ExecStart=uv run -- celery --app paperless worker --loglevel INFO"
["paperless-webserver.service"]="ExecStart=uv run -- granian --interface asgi --ws \"paperless.asgi:application\"" ["paperless-webserver.service"]="ExecStart=uv run -- granian --interface asgi --ws \"paperless.asgi:application\""

View File

@ -37,6 +37,20 @@ function update_script() {
msg_ok "Updated old sources" msg_ok "Updated old sources"
fi fi
if grep -q 'Debian GNU/Linux 13' /etc/os-release; then
if [ -f "/etc/apt/sources.list.d/pdm-test.sources" ]; then
if ! grep -qx "Enabled: false" "/etc/apt/sources.list.d/pdm-test.sources"; then
echo "Enabled: false" >> "/etc/apt/sources.list.d/pdm-test.sources"
setup_deb822_repo \
"pdm" \
"https://enterprise.proxmox.com/debian/proxmox-archive-keyring-trixie.gpg" \
"http://download.proxmox.com/debian/pdm" \
"trixie" \
"pdm-no-subscription"
fi
fi
fi
msg_info "Updating $APP LXC" msg_info "Updating $APP LXC"
$STD apt update $STD apt update
$STD apt -y upgrade $STD apt -y upgrade

View File

@ -27,42 +27,9 @@ function update_script() {
msg_error "No ${APP} Installation Found!" msg_error "No ${APP} Installation Found!"
exit exit
fi fi
if check_for_gh_release "ProxmoxVE-Local" "community-scripts/ProxmoxVE-Local"; then msg_custom "🚀" "${GN}" "The app offers a built-in updater. Please use it."
msg_info "Stopping Services"
systemctl stop pvescriptslocal
msg_ok "Stopped Services"
msg_info "Backup Data"
cp /opt/ProxmoxVE-Local/.env /opt/.env.bak
cp -r /opt/ProxmoxVE-Local/data /opt/data.bak
msg_ok "Backed up Data"
CLEAN_INSTALL=1 fetch_and_deploy_gh_release "ProxmoxVE-Local" "community-scripts/ProxmoxVE-Local"
msg_info "Restoring Data"
if [[ -f /opt/.env.bak ]]; then
mv /opt/.env.bak /opt/ProxmoxVE-Local/.env
fi
if [[ -d /opt/data.bak ]]; then
rm -rf /opt/ProxmoxVE-Local/data
mv /opt/data.bak /opt/ProxmoxVE-Local/data
fi
msg_ok "Restored Data"
msg_info "Updating PVE Scripts local"
cd /opt/ProxmoxVE-Local
chmod 755 data
$STD npm install
$STD npm run build
msg_ok "Updated PVE Scripts local"
msg_info "Starting Services"
systemctl start pvescriptslocal
msg_ok "Started Services"
msg_ok "Updated successfully!"
fi
exit
} }
start start

45
ct/qdrant.sh Normal file
View File

@ -0,0 +1,45 @@
#!/usr/bin/env bash
source <(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/misc/build.func)
# Copyright (c) 2021-2025 community-scripts ORG
# Author: MickLesk (CanbiZ)
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE
# Source: https://github.com/qdrant/qdrant
APP="Qdrant"
var_tags="${var_tags:-database;vector}"
var_cpu="${var_cpu:-1}"
var_ram="${var_ram:-1024}"
var_disk="${var_disk:-5}"
var_os="${var_os:-debian}"
var_version="${var_version:-13}"
var_unprivileged="${var_unprivileged:-1}"
header_info "$APP"
variables
color
catch_errors
function update_script() {
header_info
check_container_storage
check_container_resources
if [[ ! -d /var/lib/qdrant ]]; then
msg_error "No ${APP} Installation Found!"
exit
fi
if check_for_gh_release "qdrant" "qdrant/qdrant"; then
fetch_and_deploy_gh_release "qdrant" "qdrant/qdrant" "binary" "latest" "/usr/bin/qdrant"
chown -R root:root /var/lib/qdrant
chmod -R 755 /var/lib/qdrant
fi
exit
}
start
build_container
description
msg_ok "Completed Successfully!\n"
echo -e "${CREATING}${GN}${APP} setup has been successfully initialized!${CL}"
echo -e "${INFO}${YW} Access it using the following URL:${CL}"
echo -e "${TAB}${GATEWAY}${BGN}http://${IP}:6333/dashboard${CL}"

View File

@ -29,15 +29,10 @@ function update_script() {
fi fi
if check_for_gh_release "recyclarr" "recyclarr/recyclarr"; then if check_for_gh_release "recyclarr" "recyclarr/recyclarr"; then
msg_info "Stopping Service" msg_info "Updating ${APP}"
systemctl stop recyclarr
msg_ok "Stopped Service"
fetch_and_deploy_gh_release "recyclarr" "recyclarr/recyclarr" "prebuild" "latest" "/usr/local/bin" "recyclarr-linux-x64.tar.xz" fetch_and_deploy_gh_release "recyclarr" "recyclarr/recyclarr" "prebuild" "latest" "/usr/local/bin" "recyclarr-linux-x64.tar.xz"
msg_info "Starting Service"
systemctl start recyclarr
msg_ok "Started Service"
msg_ok "Updated successfully!" msg_ok "Updated successfully!"
fi fi
exit exit

60
ct/snowshare.sh Normal file
View File

@ -0,0 +1,60 @@
#!/usr/bin/env bash
source <(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/misc/build.func)
# Copyright (c) 2021-2025 community-scripts ORG
# Author: TuroYT
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE
# Source: https://github.com/TuroYT/snowshare
APP="SnowShare"
var_tags="${var_tags:-file-sharing}"
var_cpu="${var_cpu:-1}"
var_ram="${var_ram:-1024}"
var_disk="${var_disk:-5}"
var_os="${var_os:-debian}"
var_version="${var_version:-13}"
var_unprivileged="${var_unprivileged:-1}"
header_info "$APP"
variables
color
catch_errors
function update_script() {
header_info
check_container_storage
check_container_resources
if [[ ! -d /opt/snowshare ]]; then
msg_error "No ${APP} Installation Found!"
exit
fi
if check_for_gh_release "snowshare" "TuroYT/snowshare"; then
msg_info "Stopping Service"
systemctl stop snowshare
msg_ok "Stopped Service"
fetch_and_deploy_gh_release "snowshare" "TuroYT/snowshare"
msg_info "Updating Snowshare"
cd /opt/snowshare
$STD npm ci
$STD npx prisma generate
$STD npm run build
msg_ok "Updated Snowshare"
msg_info "Starting Service"
systemctl start snowshare
msg_ok "Started Service"
msg_ok "Updated successfully!"
fi
exit
}
start
build_container
description
msg_ok "Completed Successfully!\n"
echo -e "${CREATING}${GN}${APP} setup has been successfully initialized!${CL}"
echo -e "${INFO}${YW} Access it using the following URL:${CL}"
echo -e "${TAB}${GATEWAY}${BGN}http://${IP}:3000${CL}"

View File

@ -65,7 +65,7 @@ EOF
fi fi
msg_ok "Corrected Services" msg_ok "Corrected Services"
setup_nodejs NODE_VERSION="22" setup_nodejs
CLEAN_INSTALL=1 fetch_and_deploy_gh_release "tracktor" "javedh-dev/tracktor" "tarball" "latest" "/opt/tracktor" CLEAN_INSTALL=1 fetch_and_deploy_gh_release "tracktor" "javedh-dev/tracktor" "tarball" "latest" "/opt/tracktor"
msg_info "Updating tracktor" msg_info "Updating tracktor"

45
ct/valkey.sh Normal file
View File

@ -0,0 +1,45 @@
#!/usr/bin/env bash
source <(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/misc/build.func)
# Copyright (c) 2021-2025 community-scripts ORG
# Author: pshankinclarke (lazarillo)
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE
# Source: https://valkey.io/
APP="Valkey"
var_tags="${var_tags:-database}"
var_cpu="${var_cpu:-1}"
var_ram="${var_ram:-1024}"
var_disk="${var_disk:-4}"
var_os="${var_os:-debian}"
var_version="${var_version:-13}"
var_unprivileged="${var_unprivileged:-1}"
header_info "$APP"
variables
color
catch_errors
function update_script() {
header_info
check_container_storage
check_container_resources
if [[ ! -f /lib/systemd/system/valkey-server.service ]]; then
msg_error "No Valkey Installation Found!"
exit
fi
msg_info "Updating Valkey LXC"
$STD apt update
$STD apt -y upgrade
msg_ok "Updated Valkey LXC"
msg_ok "Updated successfully!"
exit
}
start
build_container
description
msg_ok "Completed Successfully!\n"
echo -e "${CREATING}${GN}${APP} setup has been successfully initialized!${CL}"
echo -e "${INFO}${YW} Access it using the following URL:${CL}"
echo -e "${TAB}${GATEWAY}${BGN}http://${IP}:6379${CL}"

75
ct/wanderer.sh Normal file
View File

@ -0,0 +1,75 @@
#!/usr/bin/env bash
source <(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/misc/build.func)
# Copyright (c) 2021-2025 community-scripts ORG
# Author: rrole
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE
# Source: https://wanderer.to
APP="Wanderer"
var_tags="${var_tags:-travelling;sport}"
var_cpu="${var_cpu:-2}"
var_ram="${var_ram:-4096}"
var_disk="${var_disk:-8}"
var_os="${var_os:-debian}"
var_version="${var_version:-13}"
var_unprivileged="${var_unprivileged:-1}"
header_info "$APP"
variables
color
catch_errors
function update_script() {
header_info
check_container_storage
check_container_resources
if [[ ! -f /opt/wanderer/start.sh ]]; then
msg_error "No wanderer Installation Found!"
exit
fi
if check_for_gh_release "wanderer" "Flomp/wanderer"; then
msg_info "Stopping service"
systemctl stop wanderer-web
msg_ok "Stopped service"
fetch_and_deploy_gh_release "wanderer" "Flomp/wanderer" "tarball" "latest" "/opt/wanderer/source"
msg_info "Updating wanderer"
cd /opt/wanderer/source/db
$STD go mod tidy
$STD go build
cd /opt/wanderer/source/web
$STD npm ci --omit=dev
$STD npm run build
msg_ok "Updated wanderer"
msg_info "Starting service"
systemctl start wanderer-web
msg_ok "Started service"
msg_ok "Update Successful"
fi
if check_for_gh_release "meilisearch" "meilisearch/meilisearch"; then
msg_info "Stopping service"
systemctl stop wanderer-web
msg_ok "Stopped service"
fetch_and_deploy_gh_release "meilisearch" "meilisearch/meilisearch" "binary" "latest" "/opt/wanderer/source/search"
msg_info "Starting service"
systemctl start wanderer-web
msg_ok "Started service"
msg_ok "Update Successful"
fi
exit
}
start
build_container
description
msg_ok "Completed Successfully!\n"
echo -e "${CREATING}${GN}${APP} setup has been successfully initialized!${CL}"
echo -e "${INFO}${YW} Access it using the following URL:${CL}"
echo -e "${TAB}${GATEWAY}${BGN}http://${IP}:3000${CL}"

View File

@ -52,11 +52,21 @@ function update_script() {
$STD npm --prefix app/static run build:css $STD npm --prefix app/static run build:css
mkdir -p ./.cache mkdir -p ./.cache
$STD tar -xf "$BACKUP_FILE" --directory=/ $STD tar -xf "$BACKUP_FILE" --directory=/
$STD /usr/local/bin/uv run --frozen flask db upgrade if grep -q 'workers' /opt/wizarr/start.sh; then
if ! grep -q 'frozen' /opt/wizarr/start.sh; then sed -i 's/--workers 4//' /opt/wizarr/start.sh
sed -i 's/run/& --frozen/' /opt/wizarr/start.sh fi
if ! grep -qE 'FLASK|WORKERS|VERSION' /opt/wizarr/.env; then
{
echo "FLASK_ENV=production"
echo "GUNICORN_WORKERS=4"
echo "APP_VERSION=$(sed 's/^20/v&/' ~/.wizarr)"
} >>/opt/wizarr/.env
else
sed -i "s/_VERSION=v.*$/_VERSION=v$(cat ~/.wizarr)/" /opt/wizarr/.env
fi fi
rm -rf "$BACKUP_FILE" rm -rf "$BACKUP_FILE"
export FLASK_SKIP_SCHEDULER=true
$STD /usr/local/bin/uv run --frozen flask db upgrade
msg_ok "Updated Wizarr" msg_ok "Updated Wizarr"
msg_info "Starting Service" msg_info "Starting Service"

View File

@ -46,7 +46,20 @@ function update_script() {
systemctl stop "$AGENT_SERVICE" systemctl stop "$AGENT_SERVICE"
msg_ok "Stopped Services" msg_ok "Stopped Services"
msg_info "Updating Zabbix" read -rp "Choose Zabbix version [1] 7.0 LTS [2] 7.4 (Latest Stable) [3] Latest available (default: 2): " ZABBIX_CHOICE
ZABBIX_CHOICE=${ZABBIX_CHOICE:-2}
case "$ZABBIX_CHOICE" in
1) ZABBIX_VERSION="7.0" ;;
2) ZABBIX_VERSION="7.4" ;;
3) ZABBIX_VERSION=$(curl -fsSL https://repo.zabbix.com/zabbix/ |
grep -oP '(?<=href=")[0-9]+\.[0-9]+(?=/")' | sort -V | tail -n1) ;;
*)
ZABBIX_VERSION="7.4"
echo "Invalid choice. Defaulting to 7.4."
;;
esac
msg_info "Updating Zabbix to $ZABBIX_VERSION"
mkdir -p /opt/zabbix-backup/ mkdir -p /opt/zabbix-backup/
cp /etc/zabbix/zabbix_server.conf /opt/zabbix-backup/ cp /etc/zabbix/zabbix_server.conf /opt/zabbix-backup/
cp /etc/apache2/conf-enabled/zabbix.conf /opt/zabbix-backup/ cp /etc/apache2/conf-enabled/zabbix.conf /opt/zabbix-backup/
@ -54,10 +67,8 @@ function update_script() {
rm -Rf /etc/apt/sources.list.d/zabbix.list rm -Rf /etc/apt/sources.list.d/zabbix.list
cd /tmp cd /tmp
curl -fsSL "$(curl -fsSL https://repo.zabbix.com/zabbix/ | ZABBIX_DEB_URL="https://repo.zabbix.com/zabbix/${ZABBIX_VERSION}/release/debian/pool/main/z/zabbix-release/zabbix-release_latest+debian13_all.deb"
grep -oP '(?<=href=")[0-9]+\.[0-9]+(?=/")' | sort -V | tail -n1 | curl -fsSL "$ZABBIX_DEB_URL" -o /tmp/zabbix-release_latest+debian13_all.deb
xargs -I{} echo "https://repo.zabbix.com/zabbix/{}/release/debian/pool/main/z/zabbix-release/zabbix-release_latest+debian13_all.deb")" \
-o /tmp/zabbix-release_latest+debian13_all.deb
$STD dpkg -i zabbix-release_latest+debian13_all.deb $STD dpkg -i zabbix-release_latest+debian13_all.deb
rm -rf /tmp/zabbix-release_latest+debian13_all.deb rm -rf /tmp/zabbix-release_latest+debian13_all.deb
$STD apt update $STD apt update

532
docs/DEV_MODE.md Normal file
View File

@ -0,0 +1,532 @@
# Dev Mode - Debugging & Development Guide
Development modes provide powerful debugging and testing capabilities for container creation and installation processes.
## Quick Start
```bash
# Single mode
export dev_mode="motd"
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/ct/wallabag.sh)"
# Multiple modes (comma-separated)
export dev_mode="motd,keep,trace"
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/ct/wallabag.sh)"
# Combine with verbose output
export var_verbose="yes"
export dev_mode="pause,logs"
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/ct/wallabag.sh)"
```
## Available Modes
### 1. **motd** - Early SSH/MOTD Setup
Sets up SSH access and MOTD **before** the main application installation.
**Use Case**:
- Quick access to container for manual debugging
- Continue installation manually if something goes wrong
- Verify container networking before main install
**Behavior**:
```
✔ Container created
✔ Network configured
[DEV] Setting up MOTD and SSH before installation
✔ [DEV] MOTD/SSH ready - container accessible
# Container is now accessible via SSH while installation proceeds
```
**Combined with**: `keep`, `breakpoint`, `logs`
---
### 2. **keep** - Preserve Container on Failure
Never delete the container when installation fails. Skips cleanup prompt.
**Use Case**:
- Repeated tests of the same installation
- Debugging failed installations
- Manual fix attempts
**Behavior**:
```
✖ Installation failed in container 107 (exit code: 1)
✔ Container creation log: /tmp/create-lxc-107-abc12345.log
✔ Installation log: /tmp/install-lxc-107-abc12345.log
🔧 [DEV] Keep mode active - container 107 preserved
root@proxmox:~#
```
**Container remains**: `pct enter 107` to access and debug
**Combined with**: `motd`, `trace`, `logs`
---
### 3. **trace** - Bash Command Tracing
Enables `set -x` for complete command-line tracing. Shows every command before execution.
**Use Case**:
- Deep debugging of installation logic
- Understanding script flow
- Identifying where errors occur exactly
**Behavior**:
```
+(/opt/wallabag/bin/console): /opt/wallabag/bin/console cache:warmup
+(/opt/wallabag/bin/console): env APP_ENV=prod /opt/wallabag/bin/console cache:warmup
+(/opt/wallabag/bin/console): [[ -d /opt/wallabag/app/cache ]]
+(/opt/wallabag/bin/console): rm -rf /opt/wallabag/app/cache/*
```
**⚠️ Warning**: Exposes passwords and secrets in log output! Only use in isolated environments.
**Log Output**: All trace output saved to logs (see `logs` mode)
**Combined with**: `keep`, `pause`, `logs`
---
### 4. **pause** - Step-by-Step Execution
Pauses after each major step (`msg_info`). Requires manual Enter press to continue.
**Use Case**:
- Inspect container state between steps
- Understand what each step does
- Identify which step causes problems
**Behavior**:
```
⏳ Setting up Container OS
[PAUSE] Press Enter to continue...
⏳ Updating Container OS
[PAUSE] Press Enter to continue...
⏳ Installing Dependencies
[PAUSE] Press Enter to continue...
```
**Between pauses**: You can open another terminal and inspect the container
```bash
# In another terminal while paused
pct enter 107
root@container:~# df -h # Check disk usage
root@container:~# ps aux # Check running processes
```
**Combined with**: `motd`, `keep`, `logs`
---
### 5. **breakpoint** - Interactive Shell on Error
Opens interactive shell inside the container when an error occurs instead of cleanup prompt.
**Use Case**:
- Live debugging in the actual container
- Manual command testing
- Inspect container state at point of failure
**Behavior**:
```
✖ Installation failed in container 107 (exit code: 1)
✔ Container creation log: /tmp/create-lxc-107-abc12345.log
✔ Installation log: /tmp/install-lxc-107-abc12345.log
🐛 [DEV] Breakpoint mode - opening shell in container 107
Type 'exit' to return to host
root@wallabag:~#
# Now you can debug:
root@wallabag:~# tail -f /root/.install-abc12345.log
root@wallabag:~# mysql -u root -p$PASSWORD wallabag
root@wallabag:~# apt-get install -y strace
root@wallabag:~# exit
Container 107 still running. Remove now? (y/N): n
🔧 Container 107 kept for debugging
```
**Combined with**: `keep`, `logs`, `trace`
---
### 6. **logs** - Persistent Logging
Saves all logs to `/var/log/community-scripts/` with timestamps. Logs persist even on successful installation.
**Use Case**:
- Post-mortem analysis
- Performance analysis
- Automated testing with log collection
- CI/CD integration
**Behavior**:
```
Logs location: /var/log/community-scripts/
create-lxc-abc12345-20251117_143022.log (host-side creation)
install-abc12345-20251117_143022.log (container-side installation)
```
**Access logs**:
```bash
# View creation log
tail -f /var/log/community-scripts/create-lxc-*.log
# Search for errors
grep ERROR /var/log/community-scripts/*.log
# Analyze performance
grep "msg_info\|msg_ok" /var/log/community-scripts/create-*.log
```
**With trace mode**: Creates detailed trace of all commands
```bash
grep "^+" /var/log/community-scripts/install-*.log
```
**Combined with**: All other modes (recommended for CI/CD)
---
### 7. **dryrun** - Simulation Mode
Shows all commands that would be executed without actually running them.
**Use Case**:
- Test script logic without making changes
- Verify command syntax
- Understand what will happen
- Pre-flight checks
**Behavior**:
```
[DRYRUN] apt-get update
[DRYRUN] apt-get install -y curl
[DRYRUN] mkdir -p /opt/wallabag
[DRYRUN] cd /opt/wallabag
[DRYRUN] git clone https://github.com/wallabag/wallabag.git .
```
**No actual changes made**: Container/system remains unchanged
**Combined with**: `trace` (shows dryrun trace), `logs` (shows what would run)
---
## Mode Combinations
### Development Workflow
```bash
# First test: See what would happen
export dev_mode="dryrun,logs"
bash -c "$(curl ...)"
# Then test with tracing and pauses
export dev_mode="pause,trace,logs"
bash -c "$(curl ...)"
# Finally full debug with early SSH access
export dev_mode="motd,keep,breakpoint,logs"
bash -c "$(curl ...)"
```
### CI/CD Integration
```bash
# Automated testing with full logging
export dev_mode="logs"
export var_verbose="yes"
bash -c "$(curl ...)"
# Capture logs for analysis
tar czf installation-logs-$(date +%s).tar.gz /var/log/community-scripts/
```
### Production-like Testing
```bash
# Keep containers for manual verification
export dev_mode="keep,logs"
for i in {1..5}; do
bash -c "$(curl ...)"
done
# Inspect all created containers
pct list
pct enter 100
```
### Live Debugging
```bash
# SSH in early, step through installation, debug on error
export dev_mode="motd,pause,breakpoint,keep"
bash -c "$(curl ...)"
```
---
## Environment Variables Reference
### Dev Mode Variables
- `dev_mode` (string): Comma-separated list of modes
- Format: `"motd,keep,trace"`
- Default: Empty (no dev modes)
### Output Control
- `var_verbose="yes"`: Show all command output (disables silent mode)
- Pairs well with: `trace`, `pause`, `logs`
### Examples with vars
```bash
# Maximum verbosity and debugging
export var_verbose="yes"
export dev_mode="motd,trace,pause,logs"
bash -c "$(curl ...)"
# Silent debug (logs only)
export dev_mode="keep,logs"
bash -c "$(curl ...)"
# Interactive debugging
export var_verbose="yes"
export dev_mode="motd,breakpoint"
bash -c "$(curl ...)"
```
---
## Troubleshooting with Dev Mode
### "Installation failed at step X"
```bash
export dev_mode="pause,logs"
# Step through until the failure point
# Check container state between pauses
pct enter 107
```
### "Password/credentials not working"
```bash
export dev_mode="motd,keep,trace"
# With trace mode, see exact password handling (be careful with logs!)
# Use motd to SSH in and test manually
ssh root@container-ip
```
### "Permission denied errors"
```bash
export dev_mode="breakpoint,keep"
# Get shell at failure point
# Check file permissions, user context, SELinux status
ls -la /path/to/file
whoami
```
### "Networking issues"
```bash
export dev_mode="motd"
# SSH in with motd mode before main install
ssh root@container-ip
ping 8.8.8.8
nslookup example.com
```
### "Need to manually complete installation"
```bash
export dev_mode="motd,keep"
# Container accessible via SSH while installation runs
# After failure, SSH in and manually continue
ssh root@container-ip
# ... manual commands ...
exit
# Then use 'keep' mode to preserve container for inspection
```
---
## Log Files Locations
### Default (without `logs` mode)
- Host creation: `/tmp/create-lxc-<SESSION_ID>.log`
- Container install: Copied to `/tmp/install-lxc-<CTID>-<SESSION_ID>.log` on failure
### With `logs` mode
- Host creation: `/var/log/community-scripts/create-lxc-<SESSION_ID>-<TIMESTAMP>.log`
- Container install: `/var/log/community-scripts/install-<SESSION_ID>-<TIMESTAMP>.log`
### View logs
```bash
# Tail in real-time
tail -f /var/log/community-scripts/*.log
# Search for errors
grep -r "exit code [1-9]" /var/log/community-scripts/
# Filter by session
grep "ed563b19" /var/log/community-scripts/*.log
```
---
## Best Practices
### ✅ DO
- Use `logs` mode for CI/CD and automated testing
- Use `motd` for early SSH access during long installations
- Use `pause` when learning the installation flow
- Use `trace` when debugging logic issues (watch for secrets!)
- Combine modes for comprehensive debugging
- Archive logs after successful tests
### ❌ DON'T
- Use `trace` in production or with untrusted networks (exposes secrets)
- Leave `keep` mode enabled for unattended scripts (containers accumulate)
- Use `dryrun` and expect actual changes
- Commit `dev_mode` exports to production deployment scripts
- Use `breakpoint` in non-interactive environments (will hang)
---
## Examples
### Example 1: Debug a Failed Installation
```bash
# Initial test to see the failure
export dev_mode="keep,logs"
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/ct/wallabag.sh)"
# Container 107 kept, check logs
tail /var/log/community-scripts/install-*.log
# SSH in to debug
pct enter 107
root@wallabag:~# cat /root/.install-*.log | tail -100
root@wallabag:~# apt-get update # Retry the failing command
root@wallabag:~# exit
# Re-run with manual step-through
export dev_mode="motd,pause,keep"
bash -c "$(curl ...)"
```
### Example 2: Verify Installation Steps
```bash
export dev_mode="pause,logs"
export var_verbose="yes"
bash -c "$(curl ...)"
# Press Enter through each step
# Monitor container in another terminal
# pct enter 107
# Review logs in real-time
```
### Example 3: CI/CD Pipeline Integration
```bash
#!/bin/bash
export dev_mode="logs"
export var_verbose="no"
for app in wallabag nextcloud wordpress; do
echo "Testing $app installation..."
APP="$app" bash -c "$(curl ...)" || {
echo "FAILED: $app"
tar czf logs-$app.tar.gz /var/log/community-scripts/
exit 1
}
echo "SUCCESS: $app"
done
echo "All installations successful"
tar czf all-logs.tar.gz /var/log/community-scripts/
```
---
## Advanced Usage
### Custom Log Analysis
```bash
# Extract all errors
grep "ERROR\|exit code [1-9]" /var/log/community-scripts/*.log
# Performance timeline
grep "^$(date +%Y-%m-%d)" /var/log/community-scripts/*.log | grep "msg_"
# Memory usage during install
grep "free\|available" /var/log/community-scripts/*.log
```
### Integration with External Tools
```bash
# Send logs to Elasticsearch
curl -X POST "localhost:9200/installation-logs/_doc" \
-H 'Content-Type: application/json' \
-d @/var/log/community-scripts/install-*.log
# Archive for compliance
tar czf installation-records-$(date +%Y%m).tar.gz \
/var/log/community-scripts/
gpg --encrypt installation-records-*.tar.gz
```
---
## Support & Issues
When reporting installation issues, always include:
```bash
# Collect all relevant information
export dev_mode="logs"
# Run the failing installation
# Then provide:
tar czf debug-logs.tar.gz /var/log/community-scripts/
```
Include the `debug-logs.tar.gz` when reporting issues for better diagnostics.

298
docs/EXIT_CODES.md Normal file
View File

@ -0,0 +1,298 @@
# Exit Code Reference
Comprehensive documentation of all exit codes used in ProxmoxVE scripts.
## Table of Contents
- [Generic/Shell Errors (1-255)](#genericshell-errors)
- [Package Manager Errors (100-101, 255)](#package-manager-errors)
- [Node.js/npm Errors (243-254)](#nodejsnpm-errors)
- [Python/pip Errors (210-212)](#pythonpip-errors)
- [Database Errors (231-254)](#database-errors)
- [Proxmox Custom Codes (200-231)](#proxmox-custom-codes)
---
## Generic/Shell Errors
Standard Unix/Linux exit codes used across all scripts.
| Code | Description | Common Causes | Solutions |
| ------- | --------------------------------------- | ----------------------------------------- | ---------------------------------------------- |
| **1** | General error / Operation not permitted | Permission denied, general failure | Check user permissions, run as root if needed |
| **2** | Misuse of shell builtins | Syntax error in script | Review script syntax, check bash version |
| **126** | Command cannot execute | Permission problem, not executable | `chmod +x script.sh` or check file permissions |
| **127** | Command not found | Missing binary, wrong PATH | Install required package, check PATH variable |
| **128** | Invalid argument to exit | Invalid exit code passed | Use exit codes 0-255 only |
| **130** | Terminated by Ctrl+C (SIGINT) | User interrupted script | Expected behavior, no action needed |
| **137** | Killed (SIGKILL) | Out of memory, forced termination | Check memory usage, increase RAM allocation |
| **139** | Segmentation fault | Memory access violation, corrupted binary | Reinstall package, check system stability |
| **143** | Terminated (SIGTERM) | Graceful shutdown signal | Expected during container stops |
---
## Package Manager Errors
APT, DPKG, and package installation errors.
| Code | Description | Common Causes | Solutions |
| ------- | -------------------------- | --------------------------------------- | ------------------------------------------------- |
| **100** | APT: Package manager error | Broken packages, dependency conflicts | `apt --fix-broken install`, `dpkg --configure -a` |
| **101** | APT: Configuration error | Malformed sources.list, bad repo config | Check `/etc/apt/sources.list`, run `apt update` |
| **255** | DPKG: Fatal internal error | Corrupted package database | `dpkg --configure -a`, restore from backup |
---
## Node.js/npm Errors
Node.js runtime and package manager errors.
| Code | Description | Common Causes | Solutions |
| ------- | ------------------------------------------ | ------------------------------ | ---------------------------------------------- |
| **243** | Node.js: Out of memory | JavaScript heap exhausted | Increase `--max-old-space-size`, optimize code |
| **245** | Node.js: Invalid command-line option | Wrong Node.js flags | Check Node.js version, verify CLI options |
| **246** | Node.js: Internal JavaScript Parse Error | Syntax error in JS code | Review JavaScript syntax, check dependencies |
| **247** | Node.js: Fatal internal error | Node.js runtime crash | Update Node.js, check for known bugs |
| **248** | Node.js: Invalid C++ addon / N-API failure | Native module incompatibility | Rebuild native modules, update packages |
| **249** | Node.js: Inspector error | Debug/inspect protocol failure | Disable inspector, check port conflicts |
| **254** | npm/pnpm/yarn: Unknown fatal error | Package manager crash | Clear cache, reinstall package manager |
---
## Python/pip Errors
Python runtime and package installation errors.
| Code | Description | Common Causes | Solutions |
| ------- | ------------------------------------ | --------------------------------------- | -------------------------------------------------------- |
| **210** | Python: Virtualenv missing or broken | venv not created, corrupted environment | `python3 -m venv venv`, recreate virtualenv |
| **211** | Python: Dependency resolution failed | Conflicting package versions | Use `pip install --upgrade`, check requirements.txt |
| **212** | Python: Installation aborted | EXTERNALLY-MANAGED, permission denied | Use `--break-system-packages` or venv, check permissions |
---
## Database Errors
### PostgreSQL (231-234)
| Code | Description | Common Causes | Solutions |
| ------- | ----------------------- | ---------------------------------- | ----------------------------------------------------- |
| **231** | Connection failed | Server not running, wrong socket | `systemctl start postgresql`, check connection string |
| **232** | Authentication failed | Wrong credentials | Verify username/password, check `pg_hba.conf` |
| **233** | Database does not exist | Database not created | `CREATE DATABASE`, restore from backup |
| **234** | Fatal error in query | Syntax error, constraint violation | Review SQL syntax, check constraints |
### MySQL/MariaDB (241-244)
| Code | Description | Common Causes | Solutions |
| ------- | ----------------------- | ---------------------------------- | ---------------------------------------------------- |
| **241** | Connection failed | Server not running, wrong socket | `systemctl start mysql`, check connection parameters |
| **242** | Authentication failed | Wrong credentials | Verify username/password, grant privileges |
| **243** | Database does not exist | Database not created | `CREATE DATABASE`, restore from backup |
| **244** | Fatal error in query | Syntax error, constraint violation | Review SQL syntax, check constraints |
### MongoDB (251-254)
| Code | Description | Common Causes | Solutions |
| ------- | --------------------- | -------------------- | ------------------------------------------ |
| **251** | Connection failed | Server not running | `systemctl start mongod`, check port 27017 |
| **252** | Authentication failed | Wrong credentials | Verify username/password, create user |
| **253** | Database not found | Database not created | Database auto-created on first write |
| **254** | Fatal query error | Invalid query syntax | Review MongoDB query syntax |
---
## Proxmox Custom Codes
Custom exit codes specific to ProxmoxVE scripts.
### Container Creation Errors (200-209)
| Code | Description | Common Causes | Solutions |
| ------- | ---------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------- |
| **200** | Failed to create lock file | Permission denied, disk full | Check `/tmp` permissions, free disk space |
| **203** | Missing CTID variable | Script configuration error | Set CTID in script or via prompt |
| **204** | Missing PCT_OSTYPE variable | Template selection failed | Verify template availability |
| **205** | Invalid CTID (<100) | CTID below minimum value | Use CTID 100 (1-99 reserved for Proxmox) |
| **206** | CTID already in use | Container/VM with same ID exists | Check `pct list` and `/etc/pve/lxc/`, use different ID |
| **207** | Password contains unescaped special characters | Special chars like `-`, `/`, `\`, `*` at start/end | Avoid leading special chars, use alphanumeric passwords |
| **208** | Invalid configuration | DNS format (`.home` vs `home`), MAC format (`-` vs `:`) | Remove leading dots from DNS, use `:` in MAC addresses |
| **209** | Container creation failed | Multiple possible causes | Check logs in `/tmp/pct_create_*.log`, verify template |
### Cluster & Storage Errors (210, 214, 217)
| Code | Description | Common Causes | Solutions |
| ------- | --------------------------------- | ---------------------------------- | ----------------------------------------------------------- |
| **210** | Cluster not quorate | Cluster nodes down, network issues | Check cluster status: `pvecm status`, fix node connectivity |
| **211** | Timeout waiting for template lock | Concurrent download in progress | Wait for other download to complete (60s timeout) |
| **214** | Not enough storage space | Disk full, quota exceeded | Free disk space, increase storage allocation |
| **217** | Storage does not support rootdir | Wrong storage type selected | Use storage supporting containers (dir, zfspool, lvm-thin) |
### Container Verification Errors (215-216)
| Code | Description | Common Causes | Solutions |
| ------- | -------------------------------- | -------------------------------- | --------------------------------------------------------- |
| **215** | Container created but not listed | Ghost state, incomplete creation | Check `/etc/pve/lxc/CTID.conf`, remove manually if needed |
| **216** | RootFS entry missing in config | Incomplete container creation | Delete container, retry creation |
### Template Errors (218, 220-223, 225)
| Code | Description | Common Causes | Solutions |
| ------- | ----------------------------------------- | ------------------------------------------------ | ----------------------------------------------------------- |
| **218** | Template file corrupted or incomplete | Download interrupted, file <1MB, invalid archive | Delete template, run `pveam update && pveam download` |
| **220** | Unable to resolve template path | Template storage not accessible | Check storage availability, verify permissions |
| **221** | Template file exists but not readable | Permission denied | `chmod 644 template.tar.zst`, check storage permissions |
| **222** | Template download failed after 3 attempts | Network issues, storage problems | Check internet connectivity, verify storage space |
| **223** | Template not available after download | Storage sync issue, I/O delay | Wait a few seconds, verify storage is mounted |
| **225** | No template available for OS/Version | Unsupported OS version, catalog outdated | Run `pveam update`, check `pveam available -section system` |
### LXC Stack Errors (231)
| Code | Description | Common Causes | Solutions |
| ------- | ------------------------------ | ------------------------------------------- | -------------------------------------------- |
| **231** | LXC stack upgrade/retry failed | Outdated `pve-container`, Debian 13.1 issue | See [Debian 13.1 Fix Guide](#debian-131-fix) |
---
## Special Case: Debian 13.1 "unsupported version" Error
### Problem
```
TASK ERROR: unable to create CT 129 - unsupported debian version '13.1'
```
### Root Cause
Outdated `pve-container` package doesn't recognize Debian 13 (Trixie).
### Solutions
#### Option 1: Full System Upgrade (Recommended)
```bash
apt update
apt full-upgrade -y
reboot
```
Verify fix:
```bash
dpkg -l pve-container
# PVE 8: Should show 5.3.3+
# PVE 9: Should show 6.0.13+
```
#### Option 2: Update Only pve-container
```bash
apt update
apt install --only-upgrade pve-container -y
```
**Warning:** If Proxmox fails to boot after this, your system was inconsistent. Perform Option 1 instead.
#### Option 3: Verify Repository Configuration
Many users disable Enterprise repos but forget to add no-subscription repos.
**For PVE 9 (Trixie):**
```bash
cat /etc/apt/sources.list.d/pve-no-subscription.list
```
Should contain:
```
deb http://download.proxmox.com/debian/pve trixie pve-no-subscription
deb http://download.proxmox.com/debian/ceph-squid trixie no-subscription
```
**For PVE 8 (Bookworm):**
```
deb http://download.proxmox.com/debian/pve bookworm pve-no-subscription
deb http://download.proxmox.com/debian/ceph-quincy bookworm no-subscription
```
Then:
```bash
apt update
apt full-upgrade -y
```
### Reference
Official discussion: [GitHub #8126](https://github.com/community-scripts/ProxmoxVE/discussions/8126)
---
## Troubleshooting Tips
### Finding Error Details
1. **Check logs:**
```bash
tail -n 50 /tmp/pct_create_*.log
```
2. **Enable verbose mode:**
```bash
bash -x script.sh # Shows every command executed
```
3. **Check container status:**
```bash
pct list
pct status CTID
```
4. **Verify storage:**
```bash
pvesm status
df -h
```
### Common Patterns
- **Exit 0 with error message:** Configuration validation failed (check DNS, MAC, password format)
- **Exit 206 but container not visible:** Ghost container state - check `/etc/pve/lxc/` manually
- **Exit 209 generic error:** Check `/tmp/pct_create_*.log` for specific `pct create` failure reason
- **Exit 218 or 222:** Template issues - delete and re-download template
---
## Quick Reference Chart
| Exit Code Range | Category | Typical Issue |
| --------------- | ------------------ | ------------------------------------------- |
| 1-2, 126-143 | Shell/System | Permissions, signals, missing commands |
| 100-101, 255 | Package Manager | APT/DPKG errors, broken packages |
| 200-209 | Container Creation | CTID, password, configuration |
| 210-217 | Storage/Cluster | Disk space, quorum, storage type |
| 218-225 | Templates | Download, corruption, availability |
| 231-254 | Databases/Runtime | PostgreSQL, MySQL, MongoDB, Node.js, Python |
---
## Contributing
Found an undocumented exit code or have a solution to share? Please:
1. Open an issue on [GitHub](https://github.com/community-scripts/ProxmoxVE/issues)
2. Include:
- Exit code number
- Error message
- Steps to reproduce
- Solution that worked for you
---
_Last updated: November 2025_
_ProxmoxVE Version: 2.x_

298
docs/README.md Normal file
View File

@ -0,0 +1,298 @@
# 📚 ProxmoxVE Documentation
Complete guide to all ProxmoxVE documentation - quickly find what you need.
---
## 🎯 **Quick Navigation by Goal**
### 👤 **I want to...**
**Contribute a new application**
→ Start with: [contribution/README.md](contribution/README.md)
→ Then: [ct/DETAILED_GUIDE.md](ct/DETAILED_GUIDE.md) + [install/DETAILED_GUIDE.md](install/DETAILED_GUIDE.md)
**Understand the architecture**
→ Read: [TECHNICAL_REFERENCE.md](TECHNICAL_REFERENCE.md)
→ Then: [misc/README.md](misc/README.md)
**Debug a failed installation**
→ Check: [EXIT_CODES.md](EXIT_CODES.md)
→ Then: [DEV_MODE.md](DEV_MODE.md)
→ See also: [misc/error_handler.func/](misc/error_handler.func/)
**Configure system defaults**
→ Read: [guides/DEFAULTS_SYSTEM_GUIDE.md](guides/DEFAULTS_SYSTEM_GUIDE.md)
**Deploy containers automatically**
→ Read: [guides/UNATTENDED_DEPLOYMENTS.md](guides/UNATTENDED_DEPLOYMENTS.md)
**Develop a function library**
→ Study: [misc/](misc/) documentation
---
## 👤 **Quick Start by Role**
### **I'm a...**
**New Contributor**
→ Start: [contribution/README.md](contribution/README.md)
→ Then: Choose your path below
**Container Creator**
→ Read: [ct/README.md](ct/README.md)
→ Deep Dive: [ct/DETAILED_GUIDE.md](ct/DETAILED_GUIDE.md)
→ Reference: [misc/build.func/](misc/build.func/)
**Installation Script Developer**
→ Read: [install/README.md](install/README.md)
→ Deep Dive: [install/DETAILED_GUIDE.md](install/DETAILED_GUIDE.md)
→ Reference: [misc/tools.func/](misc/tools.func/)
**VM Provisioner**
→ Read: [vm/README.md](vm/README.md)
→ Reference: [misc/cloud-init.func/](misc/cloud-init.func/)
**Tools Developer**
→ Read: [tools/README.md](tools/README.md)
→ Reference: [misc/build.func/](misc/build.func/)
**API Integrator**
→ Read: [api/README.md](api/README.md)
→ Reference: [misc/api.func/](misc/api.func/)
**System Operator**
→ Start: [EXIT_CODES.md](EXIT_CODES.md)
→ Then: [guides/DEFAULTS_SYSTEM_GUIDE.md](guides/DEFAULTS_SYSTEM_GUIDE.md)
→ Automate: [guides/UNATTENDED_DEPLOYMENTS.md](guides/UNATTENDED_DEPLOYMENTS.md)
→ Debug: [DEV_MODE.md](DEV_MODE.md)
**Architect**
→ Read: [TECHNICAL_REFERENCE.md](TECHNICAL_REFERENCE.md)
→ Deep Dive: [misc/README.md](misc/README.md)
---
## 📂 **Documentation Structure**
### Project-Mirrored Directories
Each major project directory has documentation:
```
ProxmoxVE/
├─ ct/ ↔ docs/ct/ (README.md + DETAILED_GUIDE.md)
├─ install/ ↔ docs/install/ (README.md + DETAILED_GUIDE.md)
├─ vm/ ↔ docs/vm/ (README.md)
├─ tools/ ↔ docs/tools/ (README.md)
├─ api/ ↔ docs/api/ (README.md)
├─ misc/ ↔ docs/misc/ (9 function libraries)
└─ [system-wide] ↔ docs/guides/ (configuration & deployment guides)
```
### Core Documentation
| Document | Purpose | Audience |
|----------|---------|----------|
| [contribution/README.md](contribution/README.md) | How to contribute | Contributors |
| [ct/DETAILED_GUIDE.md](ct/DETAILED_GUIDE.md) | Create ct scripts | Container developers |
| [install/DETAILED_GUIDE.md](install/DETAILED_GUIDE.md) | Create install scripts | Installation developers |
| [TECHNICAL_REFERENCE.md](TECHNICAL_REFERENCE.md) | Architecture deep-dive | Architects, advanced users |
| [guides/DEFAULTS_SYSTEM_GUIDE.md](guides/DEFAULTS_SYSTEM_GUIDE.md) | Configuration system | Operators, power users |
| [guides/CONFIGURATION_REFERENCE.md](guides/CONFIGURATION_REFERENCE.md) | Configuration options reference | Advanced users |
| [guides/UNATTENDED_DEPLOYMENTS.md](guides/UNATTENDED_DEPLOYMENTS.md) | Automated deployments | DevOps, automation |
| [EXIT_CODES.md](EXIT_CODES.md) | Exit code reference | Troubleshooters |
| [DEV_MODE.md](DEV_MODE.md) | Debugging tools | Developers |
---
## 📂 **Directory Guide**
### [ct/](ct/) - Container Scripts
Documentation for `/ct` - Container creation scripts that run on the Proxmox host.
**Includes**:
- Overview of container creation process
- Deep dive: [DETAILED_GUIDE.md](ct/DETAILED_GUIDE.md) - Complete reference with examples
- Reference to [misc/build.func/](misc/build.func/)
- Quick start for creating new containers
### [install/](install/) - Installation Scripts
Documentation for `/install` - Scripts that run inside containers to install applications.
**Includes**:
- Overview of 10-phase installation pattern
- Deep dive: [DETAILED_GUIDE.md](install/DETAILED_GUIDE.md) - Complete reference with examples
- Reference to [misc/tools.func/](misc/tools.func/)
- Alpine vs Debian differences
### [vm/](vm/) - Virtual Machine Scripts
Documentation for `/vm` - VM creation scripts using cloud-init provisioning.
**Includes**:
- Overview of VM provisioning
- Link to [misc/cloud-init.func/](misc/cloud-init.func/)
- VM vs Container comparison
- Cloud-init examples
### [tools/](tools/) - Tools & Utilities
Documentation for `/tools` - Management tools and add-ons.
**Includes**:
- Overview of tools structure
- Integration points
- Contributing new tools
- Common operations
### [api/](api/) - API Integration
Documentation for `/api` - Telemetry and API backend.
**Includes**:
- API overview
- Integration methods
- API endpoints
- Privacy information
### [misc/](misc/) - Function Libraries
Documentation for `/misc` - 9 core function libraries with complete references.
**Contains**:
- **build.func/** - Container orchestration (7 files)
- **core.func/** - Utilities and messaging (5 files)
- **error_handler.func/** - Error handling (5 files)
- **api.func/** - API integration (5 files)
- **install.func/** - Container setup (5 files)
- **tools.func/** - Package installation (6 files)
- **alpine-install.func/** - Alpine setup (5 files)
- **alpine-tools.func/** - Alpine tools (5 files)
- **cloud-init.func/** - VM provisioning (5 files)
---
## 🎓 **Learning Paths**
### Path 1: First-Time Contributor (2-3 hours)
1. [contribution/README.md](contribution/README.md) - Quick Start
2. Pick your area:
- Containers → [ct/README.md](ct/README.md) + [ct/DETAILED_GUIDE.md](ct/DETAILED_GUIDE.md)
- Installation → [install/README.md](install/README.md) + [install/DETAILED_GUIDE.md](install/DETAILED_GUIDE.md)
- VMs → [vm/README.md](vm/README.md)
3. Study existing similar script
4. Create your contribution
5. Submit PR
### Path 2: Intermediate Developer (4-6 hours)
1. [TECHNICAL_REFERENCE.md](TECHNICAL_REFERENCE.md)
2. Dive into function libraries:
- [misc/build.func/README.md](misc/build.func/README.md)
- [misc/tools.func/README.md](misc/tools.func/README.md)
- [misc/install.func/README.md](misc/install.func/README.md)
3. Study advanced examples
4. Create complex applications
### Path 3: Advanced Architect (8+ hours)
1. All of Intermediate Path
2. Study all 9 function libraries in depth
3. [guides/DEFAULTS_SYSTEM_GUIDE.md](guides/DEFAULTS_SYSTEM_GUIDE.md) - Configuration system
4. [DEV_MODE.md](DEV_MODE.md) - Debugging and development
5. Design new features or function libraries
### Path 4: Troubleshooter (30 minutes - 1 hour)
1. [EXIT_CODES.md](EXIT_CODES.md) - Find error code
2. [DEV_MODE.md](DEV_MODE.md) - Run with debugging
3. Check relevant function library docs
4. Review logs and fix
---
## 📊 **By the Numbers**
| Metric | Count |
|--------|:---:|
| **Documentation Files** | 63 |
| **Total Lines** | 15,000+ |
| **Function Libraries** | 9 |
| **Functions Documented** | 150+ |
| **Code Examples** | 50+ |
| **Flowcharts** | 15+ |
| **Do/Don't Sections** | 20+ |
| **Real-World Examples** | 30+ |
---
## 🔍 **Find It Fast**
### By Feature
- **How do I create a container?** → [ct/DETAILED_GUIDE.md](ct/DETAILED_GUIDE.md)
- **How do I create an install script?** → [install/DETAILED_GUIDE.md](install/DETAILED_GUIDE.md)
- **How do I create a VM?** → [vm/README.md](vm/README.md)
- **How do I install Node.js?** → [misc/tools.func/](misc/tools.func/)
- **How do I debug?** → [DEV_MODE.md](DEV_MODE.md)
### By Error
- **Exit code 206?** → [EXIT_CODES.md](EXIT_CODES.md)
- **Network failed?** → [misc/install.func/](misc/install.func/)
- **Package error?** → [misc/tools.func/](misc/tools.func/)
### By Role
- **Contributor** → [contribution/README.md](contribution/README.md)
- **Operator** → [guides/DEFAULTS_SYSTEM_GUIDE.md](guides/DEFAULTS_SYSTEM_GUIDE.md)
- **Automation** → [guides/UNATTENDED_DEPLOYMENTS.md](guides/UNATTENDED_DEPLOYMENTS.md)
- **Developer** → [TECHNICAL_REFERENCE.md](TECHNICAL_REFERENCE.md)
- **Architect** → [misc/README.md](misc/README.md)
---
## ✅ **Documentation Features**
-**Project-mirrored structure** - Organized like the actual project
-**Complete function references** - Every function documented
-**Real-world examples** - Copy-paste ready code
-**Visual flowcharts** - ASCII diagrams of workflows
-**Integration guides** - How components connect
-**Troubleshooting** - Common issues and solutions
-**Best practices** - DO/DON'T sections throughout
-**Learning paths** - Structured curriculum by role
-**Quick references** - Fast lookup by error code
-**Comprehensive navigation** - This page
---
## 🚀 **Start Here**
**New to ProxmoxVE?** → [contribution/README.md](contribution/README.md)
**Looking for something specific?** → Choose your role above or browse by directory
**Need to debug?** → [EXIT_CODES.md](EXIT_CODES.md)
**Want to understand architecture?** → [TECHNICAL_REFERENCE.md](TECHNICAL_REFERENCE.md)
---
## 🤝 **Contributing Documentation**
Found an error? Want to improve docs?
1. See: [contribution/README.md](contribution/README.md) for full contribution guide
2. Open issue: [GitHub Issues](https://github.com/community-scripts/ProxmoxVE/issues)
3. Or submit PR with improvements
---
## 📝 **Status**
- **Last Updated**: December 2025
- **Version**: 2.3 (Consolidated & Reorganized)
- **Completeness**: ✅ 100% - All components documented
- **Quality**: ✅ Production-ready
- **Structure**: ✅ Clean and organized
---
**Welcome to ProxmoxVE! Start with [CONTRIBUTION_GUIDE.md](CONTRIBUTION_GUIDE.md) or choose your role above.** 🚀

881
docs/TECHNICAL_REFERENCE.md Normal file
View File

@ -0,0 +1,881 @@
# Technical Reference: Configuration System Architecture
> **For Developers and Advanced Users**
>
> *Deep dive into how the defaults and configuration system works*
---
## Table of Contents
1. [System Architecture](#system-architecture)
2. [File Format Specifications](#file-format-specifications)
3. [Function Reference](#function-reference)
4. [Variable Precedence](#variable-precedence)
5. [Data Flow Diagrams](#data-flow-diagrams)
6. [Security Model](#security-model)
7. [Implementation Details](#implementation-details)
---
## System Architecture
### Component Overview
```
┌─────────────────────────────────────────────────────────────┐
│ Installation Script │
│ (pihole-install.sh, docker-install.sh, etc.) │
└────────────────────┬────────────────────────────────────────┘
v
┌─────────────────────────────────────────────────────────────┐
│ build.func Library │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ variables() │ │
│ │ - Initialize NSAPP, var_install, etc. │ │
│ └──────────────────────────────────────────────────────┘ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ install_script() │ │
│ │ - Display mode menu │ │
│ │ - Route to appropriate workflow │ │
│ └──────────────────────────────────────────────────────┘ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ base_settings() │ │
│ │ - Apply built-in defaults │ │
│ │ - Read environment variables (var_*) │ │
│ └──────────────────────────────────────────────────────┘ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ load_vars_file() │ │
│ │ - Safe file parsing (NO source/eval) │ │
│ │ - Whitelist validation │ │
│ │ - Value sanitization │ │
│ └──────────────────────────────────────────────────────┘ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ default_var_settings() │ │
│ │ - Load user defaults │ │
│ │ - Display summary │ │
│ └──────────────────────────────────────────────────────┘ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ maybe_offer_save_app_defaults() │ │
│ │ - Offer to save current settings │ │
│ │ - Handle updates vs. new saves │ │
│ └──────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
v
┌─────────────────────────────────────────────────────────────┐
│ Configuration Files (on Disk) │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ /usr/local/community-scripts/default.vars │ │
│ │ (User global defaults) │ │
│ └──────────────────────────────────────────────────────┘ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ /usr/local/community-scripts/defaults/*.vars │ │
│ │ (App-specific defaults) │ │
│ └──────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
```
---
## File Format Specifications
### User Defaults: `default.vars`
**Location**: `/usr/local/community-scripts/default.vars`
**MIME Type**: `text/plain`
**Encoding**: UTF-8 (no BOM)
**Format Specification**:
```
# File Format: Simple key=value pairs
# Purpose: Store global user defaults
# Security: Sanitized values, whitelist validation
# Comments and blank lines are ignored
# Line format: var_name=value
# No spaces around the equals sign
# String values do not need quoting (but may be quoted)
[CONTENT]
var_cpu=4
var_ram=2048
var_disk=20
var_hostname=mydefault
var_brg=vmbr0
var_gateway=192.168.1.1
```
**Formal Grammar**:
```
FILE := (BLANK_LINE | COMMENT_LINE | VAR_LINE)*
BLANK_LINE := \n
COMMENT_LINE := '#' [^\n]* \n
VAR_LINE := VAR_NAME '=' VAR_VALUE \n
VAR_NAME := 'var_' [a-z_]+
VAR_VALUE := [^\n]* # Any printable characters except newline
```
**Constraints**:
| Constraint | Value |
|-----------|-------|
| Max file size | 64 KB |
| Max line length | 1024 bytes |
| Max variables | 100 |
| Allowed var names | `var_[a-z_]+` |
| Value validation | Whitelist + Sanitization |
**Example Valid File**:
```bash
# Global User Defaults
# Created: 2024-11-28
# Resource defaults
var_cpu=4
var_ram=2048
var_disk=20
# Network defaults
var_brg=vmbr0
var_gateway=192.168.1.1
var_mtu=1500
var_vlan=100
# System defaults
var_timezone=Europe/Berlin
var_hostname=default-container
# Storage
var_container_storage=local
var_template_storage=local
# Security
var_ssh=yes
var_protection=0
var_unprivileged=1
```
### App Defaults: `<app>.vars`
**Location**: `/usr/local/community-scripts/defaults/<appname>.vars`
**Format**: Identical to `default.vars`
**Naming Convention**: `<nsapp>.vars`
- `nsapp` = lowercase app name with spaces removed
- Examples:
- `pihole``pihole.vars`
- `opnsense``opnsense.vars`
- `docker compose``dockercompose.vars`
**Example App Defaults**:
```bash
# App-specific defaults for PiHole (pihole)
# Generated on 2024-11-28T15:32:00Z
# These override user defaults when installing pihole
var_unprivileged=1
var_cpu=2
var_ram=1024
var_disk=10
var_brg=vmbr0
var_net=veth
var_gateway=192.168.1.1
var_hostname=pihole
var_timezone=Europe/Berlin
var_container_storage=local
var_template_storage=local
var_tags=dns,pihole
```
---
## Function Reference
### `load_vars_file()`
**Purpose**: Safely load variables from .vars files without using `source` or `eval`
**Signature**:
```bash
load_vars_file(filepath)
```
**Parameters**:
| Param | Type | Required | Example |
|-------|------|----------|---------|
| filepath | String | Yes | `/usr/local/community-scripts/default.vars` |
**Returns**:
- `0` on success
- `1` on error (file missing, parse error, etc.)
**Environment Side Effects**:
- Sets all parsed `var_*` variables as shell variables
- Does NOT unset variables if file missing (safe)
- Does NOT affect other variables
**Implementation Pattern**:
```bash
load_vars_file() {
local file="$1"
# File must exist
[ -f "$file" ] || return 0
# Parse line by line (not with source/eval)
local line key val
while IFS='=' read -r key val || [ -n "$key" ]; do
# Skip comments and empty lines
[[ "$key" =~ ^[[:space:]]*# ]] && continue
[[ -z "$key" ]] && continue
# Validate key is in whitelist
_is_whitelisted_key "$key" || continue
# Sanitize and export value
val="$(_sanitize_value "$val")"
[ $? -eq 0 ] && export "$key=$val"
done < "$file"
return 0
}
```
**Usage Examples**:
```bash
# Load user defaults
load_vars_file "/usr/local/community-scripts/default.vars"
# Load app-specific defaults
load_vars_file "$(get_app_defaults_path)"
# Check if successful
if load_vars_file "$vars_path"; then
echo "Settings loaded successfully"
else
echo "Failed to load settings"
fi
# Values are now available as variables
echo "Using $var_cpu cores"
echo "Allocating ${var_ram} MB RAM"
```
---
### `get_app_defaults_path()`
**Purpose**: Get the full path for app-specific defaults file
**Signature**:
```bash
get_app_defaults_path()
```
**Parameters**: None
**Returns**:
- String: Full path to app defaults file
**Implementation**:
```bash
get_app_defaults_path() {
local n="${NSAPP:-${APP,,}}"
echo "/usr/local/community-scripts/defaults/${n}.vars"
}
```
**Usage Examples**:
```bash
# Get app defaults path
app_defaults="$(get_app_defaults_path)"
echo "App defaults at: $app_defaults"
# Check if app defaults exist
if [ -f "$(get_app_defaults_path)" ]; then
echo "App defaults available"
fi
# Load app defaults
load_vars_file "$(get_app_defaults_path)"
```
---
### `default_var_settings()`
**Purpose**: Load and display user global defaults
**Signature**:
```bash
default_var_settings()
```
**Parameters**: None
**Returns**:
- `0` on success
- `1` on error
**Workflow**:
```
1. Find default.vars location
(usually /usr/local/community-scripts/default.vars)
2. Create if missing
3. Load variables from file
4. Map var_verbose → VERBOSE variable
5. Call base_settings (apply to container config)
6. Call echo_default (display summary)
```
**Implementation Pattern**:
```bash
default_var_settings() {
local VAR_WHITELIST=(
var_apt_cacher var_apt_cacher_ip var_brg var_cpu var_disk var_fuse
var_gateway var_hostname var_ipv6_method var_mac var_mtu
var_net var_ns var_pw var_ram var_tags var_tun var_unprivileged
var_verbose var_vlan var_ssh var_ssh_authorized_key
var_container_storage var_template_storage
)
# Ensure file exists
_ensure_default_vars
# Find and load
local dv="$(_find_default_vars)"
load_vars_file "$dv"
# Map verbose flag
if [[ -n "${var_verbose:-}" ]]; then
case "${var_verbose,,}" in
1 | yes | true | on) VERBOSE="yes" ;;
*) VERBOSE="${var_verbose}" ;;
esac
fi
# Apply and display
base_settings "$VERBOSE"
echo_default
}
```
---
### `maybe_offer_save_app_defaults()`
**Purpose**: Offer to save current settings as app-specific defaults
**Signature**:
```bash
maybe_offer_save_app_defaults()
```
**Parameters**: None
**Returns**: None (side effects only)
**Behavior**:
1. After advanced installation completes
2. Offers user: "Save as App Defaults for <APP>?"
3. If yes:
- Saves to `/usr/local/community-scripts/defaults/<app>.vars`
- Only whitelisted variables included
- Previous defaults backed up (if exists)
4. If no:
- No action taken
**Flow**:
```bash
maybe_offer_save_app_defaults() {
local app_vars_path="$(get_app_defaults_path)"
# Build current settings from memory
local new_tmp="$(_build_current_app_vars_tmp)"
# Check if already exists
if [ -f "$app_vars_path" ]; then
# Show diff and ask: Update? Keep? View Diff?
_show_app_defaults_diff_menu "$new_tmp" "$app_vars_path"
else
# New defaults - just save
if whiptail --yesno "Save as App Defaults for $APP?" 10 60; then
mv "$new_tmp" "$app_vars_path"
chmod 644 "$app_vars_path"
fi
fi
}
```
---
### `_sanitize_value()`
**Purpose**: Remove dangerous characters/patterns from configuration values
**Signature**:
```bash
_sanitize_value(value)
```
**Parameters**:
| Param | Type | Required |
|-------|------|----------|
| value | String | Yes |
**Returns**:
- `0` (success) + sanitized value on stdout
- `1` (failure) + nothing if dangerous
**Dangerous Patterns**:
| Pattern | Threat | Example |
|---------|--------|---------|
| `$(...)` | Command substitution | `$(rm -rf /)` |
| `` ` ` `` | Command substitution | `` `whoami` `` |
| `;` | Command separator | `value; rm -rf /` |
| `&` | Background execution | `value & malicious` |
| `<(` | Process substitution | `<(cat /etc/passwd)` |
**Implementation**:
```bash
_sanitize_value() {
case "$1" in
*'$('* | *'`'* | *';'* | *'&'* | *'<('*)
echo ""
return 1 # Reject dangerous value
;;
esac
echo "$1"
return 0
}
```
**Usage Examples**:
```bash
# Safe value
_sanitize_value "192.168.1.1" # Returns: 192.168.1.1 (status: 0)
# Dangerous value
_sanitize_value "$(whoami)" # Returns: (empty) (status: 1)
# Usage in code
if val="$(_sanitize_value "$user_input")"; then
export var_hostname="$val"
else
msg_error "Invalid value: contains dangerous characters"
fi
```
---
### `_is_whitelisted_key()`
**Purpose**: Check if variable name is in allowed whitelist
**Signature**:
```bash
_is_whitelisted_key(key)
```
**Parameters**:
| Param | Type | Required | Example |
|-------|------|----------|---------|
| key | String | Yes | `var_cpu` |
**Returns**:
- `0` if key is whitelisted
- `1` if key is NOT whitelisted
**Implementation**:
```bash
_is_whitelisted_key() {
local k="$1"
local w
for w in "${VAR_WHITELIST[@]}"; do
[ "$k" = "$w" ] && return 0
done
return 1
}
```
**Usage Examples**:
```bash
# Check if variable can be saved
if _is_whitelisted_key "var_cpu"; then
echo "var_cpu can be saved"
fi
# Reject unknown variables
if ! _is_whitelisted_key "var_custom"; then
msg_error "var_custom is not supported"
fi
```
---
## Variable Precedence
### Loading Order
When a container is being created, variables are resolved in this order:
```
Step 1: Read ENVIRONMENT VARIABLES
├─ Check if var_cpu is already set in shell environment
├─ Check if var_ram is already set
└─ ...all var_* variables
Step 2: Load APP-SPECIFIC DEFAULTS
├─ Check if /usr/local/community-scripts/defaults/pihole.vars exists
├─ Load all var_* from that file
└─ These override built-ins but NOT environment variables
Step 3: Load USER GLOBAL DEFAULTS
├─ Check if /usr/local/community-scripts/default.vars exists
├─ Load all var_* from that file
└─ These override built-ins but NOT app-specific
Step 4: Use BUILT-IN DEFAULTS
└─ Hardcoded in script (lowest priority)
```
### Precedence Examples
**Example 1: Environment Variable Wins**
```bash
# Shell environment has highest priority
$ export var_cpu=16
$ bash pihole-install.sh
# Result: Container gets 16 cores
# (ignores app defaults, user defaults, built-ins)
```
**Example 2: App Defaults Override User Defaults**
```bash
# User Defaults: var_cpu=4
# App Defaults: var_cpu=2
$ bash pihole-install.sh
# Result: Container gets 2 cores
# (app-specific setting takes precedence)
```
**Example 3: All Defaults Missing (Built-ins Used)**
```bash
# No environment variables set
# No app defaults file
# No user defaults file
$ bash pihole-install.sh
# Result: Uses built-in defaults
# (var_cpu might be 2 by default)
```
### Implementation in Code
```bash
# Typical pattern in build.func
base_settings() {
# Priority 1: Environment variables (already set if export used)
CT_TYPE=${var_unprivileged:-"1"} # Use existing or default
# Priority 2: Load app defaults (may override above)
if [ -f "$(get_app_defaults_path)" ]; then
load_vars_file "$(get_app_defaults_path)"
fi
# Priority 3: Load user defaults
if [ -f "/usr/local/community-scripts/default.vars" ]; then
load_vars_file "/usr/local/community-scripts/default.vars"
fi
# Priority 4: Apply built-in defaults (lowest)
CORE_COUNT=${var_cpu:-"${APP_CPU_DEFAULT:-2}"}
RAM_SIZE=${var_ram:-"${APP_RAM_DEFAULT:-1024}"}
# Result: var_cpu has been set through precedence chain
}
```
---
## Data Flow Diagrams
### Installation Flow: Advanced Settings
```
┌──────────────┐
│ Start Script│
└──────┬───────┘
v
┌──────────────────────────────┐
│ Display Installation Mode │
│ Menu (5 options) │
└──────┬───────────────────────┘
│ User selects "Advanced Settings"
v
┌──────────────────────────────────┐
│ Call: base_settings() │
│ (Apply built-in defaults) │
└──────┬───────────────────────────┘
v
┌──────────────────────────────────┐
│ Call: advanced_settings() │
│ (Show 19-step wizard) │
│ - Ask CPU, RAM, Disk, Network... │
└──────┬───────────────────────────┘
v
┌──────────────────────────────────┐
│ Show Summary │
│ Review all chosen values │
└──────┬───────────────────────────┘
│ User confirms
v
┌──────────────────────────────────┐
│ Create Container │
│ Using current variable values │
└──────┬───────────────────────────┘
v
┌──────────────────────────────────┐
│ Installation Complete │
└──────┬───────────────────────────┘
v
┌──────────────────────────────────────┐
│ Offer: Save as App Defaults? │
│ (Save current settings) │
└──────┬───────────────────────────────┘
├─ YES → Save to defaults/<app>.vars
└─ NO → Exit
```
### Variable Resolution Flow
```
CONTAINER CREATION STARTED
v
┌─────────────────────┐
│ Check ENVIRONMENT │
│ for var_cpu, var_..│
└──────┬──────────────┘
│ Found? Use them (Priority 1)
│ Not found? Continue...
v
┌──────────────────────────┐
│ Load App Defaults │
│ /defaults/<app>.vars │
└──────┬───────────────────┘
│ File exists? Parse & load (Priority 2)
│ Not found? Continue...
v
┌──────────────────────────┐
│ Load User Defaults │
│ /default.vars │
└──────┬───────────────────┘
│ File exists? Parse & load (Priority 3)
│ Not found? Continue...
v
┌──────────────────────────┐
│ Use Built-in Defaults │
│ (Hardcoded values) │
└──────┬───────────────────┘
v
┌──────────────────────────┐
│ All Variables Resolved │
│ Ready for container │
│ creation │
└──────────────────────────┘
```
---
## Security Model
### Threat Model
| Threat | Mitigation |
|--------|-----------|
| **Arbitrary Code Execution** | No `source` or `eval`; manual parsing only |
| **Variable Injection** | Whitelist of allowed variable names |
| **Command Substitution** | `_sanitize_value()` blocks `$()`, backticks, etc. |
| **Path Traversal** | Files locked to `/usr/local/community-scripts/` |
| **Permission Escalation** | Files created with restricted permissions |
| **Information Disclosure** | Sensitive variables not logged |
### Security Controls
#### 1. Input Validation
```bash
# Only specific variables allowed
if ! _is_whitelisted_key "$key"; then
skip_this_variable
fi
# Values sanitized
if ! val="$(_sanitize_value "$value")"; then
reject_entire_line
fi
```
#### 2. Safe File Parsing
```bash
# ❌ DANGEROUS (OLD)
source /path/to/config.conf
# Could execute: rm -rf / or any code
# ✅ SAFE (NEW)
load_vars_file "/path/to/config.conf"
# Only reads var_name=value pairs, no execution
```
#### 3. Whitelisting
```bash
# Only these variables can be configured
var_cpu, var_ram, var_disk, var_brg, ...
var_hostname, var_pw, var_ssh, ...
# NOT allowed:
var_malicious, var_hack, custom_var, ...
```
#### 4. Value Constraints
```bash
# No command injection patterns
if [[ "$value" =~ ($|`|;|&|<\() ]]; then
reject_value
fi
```
---
## Implementation Details
### Module: `build.func`
**Load Order** (in actual scripts):
1. `#!/usr/bin/env bash` - Shebang
2. `source /dev/stdin <<<$(curl ... api.func)` - API functions
3. `source /dev/stdin <<<$(curl ... build.func)` - Build functions
4. `variables()` - Initialize variables
5. `check_root()` - Security check
6. `install_script()` - Main flow
**Key Sections**:
```bash
# Section 1: Initialization & Variables
- variables()
- NSAPP, var_install, INTEGER pattern, etc.
# Section 2: Storage Management
- storage_selector()
- ensure_storage_selection_for_vars_file()
# Section 3: Base Settings
- base_settings() # Apply defaults to all var_*
- echo_default() # Display current settings
# Section 4: Variable Loading
- load_vars_file() # Safe parsing
- _is_whitelisted_key() # Validation
- _sanitize_value() # Threat mitigation
# Section 5: Defaults Management
- default_var_settings() # Load user defaults
- get_app_defaults_path() # Get app defaults path
- maybe_offer_save_app_defaults() # Save option
# Section 6: Installation Flow
- install_script() # Main entry point
- advanced_settings() # 19-step wizard
```
### Regex Patterns Used
| Pattern | Purpose | Example Match |
|---------|---------|---|
| `^[0-9]+([.][0-9]+)?$` | Integer validation | `4`, `192.168` |
| `^var_[a-z_]+$` | Variable name | `var_cpu`, `var_ssh` |
| `*'$('*` | Command substitution | `$(whoami)` |
| `*\`*` | Backtick substitution | `` `cat /etc/passwd` `` |
---
## Appendix: Migration Reference
### Old Pattern (Deprecated)
```bash
# ❌ OLD: config-file.func
source config-file.conf # Executes arbitrary code
if [ "$USE_DEFAULTS" = "yes" ]; then
apply_settings_directly
fi
```
### New Pattern (Current)
```bash
# ✅ NEW: load_vars_file()
if load_vars_file "$(get_app_defaults_path)"; then
echo "Settings loaded securely"
fi
```
### Function Mapping
| Old | New | Location |
|-----|-----|----------|
| `read_config()` | `load_vars_file()` | build.func |
| `write_config()` | `_build_current_app_vars_tmp()` | build.func |
| None | `maybe_offer_save_app_defaults()` | build.func |
| None | `get_app_defaults_path()` | build.func |
---
**End of Technical Reference**

146
docs/api/README.md Normal file
View File

@ -0,0 +1,146 @@
# API Integration Documentation (/api)
This directory contains comprehensive documentation for API integration and the `/api` directory.
## Overview
The `/api` directory contains the Proxmox Community Scripts API backend for diagnostic reporting, telemetry, and analytics integration.
## Key Components
### Main API Service
Located in `/api/main.go`:
- RESTful API for receiving telemetry data
- Installation statistics tracking
- Error reporting and analytics
- Performance monitoring
### Integration with Scripts
The API is integrated into all installation scripts via `api.func`:
- Sends installation start/completion events
- Reports errors and exit codes
- Collects anonymous usage statistics
- Enables project analytics
## Documentation Structure
API documentation covers:
- API endpoint specifications
- Integration methods
- Data formats and schemas
- Error handling
- Privacy and data handling
## Key Resources
- **[misc/api.func/](../misc/api.func/)** - API function library documentation
- **[misc/api.func/README.md](../misc/api.func/README.md)** - Quick reference
- **[misc/api.func/API_FUNCTIONS_REFERENCE.md](../misc/api.func/API_FUNCTIONS_REFERENCE.md)** - Complete function reference
## API Functions
The `api.func` library provides:
### `post_to_api()`
Send container installation data to API.
**Usage**:
```bash
post_to_api CTID STATUS APP_NAME
```
### `post_update_to_api()`
Report application update status.
**Usage**:
```bash
post_update_to_api CTID APP_NAME VERSION
```
### `get_error_description()`
Get human-readable error description from exit code.
**Usage**:
```bash
ERROR_DESC=$(get_error_description EXIT_CODE)
```
## API Integration Points
### In Container Creation (`ct/AppName.sh`)
- Called by build.func to report container creation
- Sends initial container setup data
- Reports success or failure
### In Installation Scripts (`install/appname-install.sh`)
- Called at start of installation
- Called on installation completion
- Called on error conditions
### Data Collected
- Container/VM ID
- Application name and version
- Installation duration
- Success/failure status
- Error codes (if failure)
- Anonymous usage metrics
## Privacy
All API data:
- ✅ Anonymous (no personal data)
- ✅ Aggregated for statistics
- ✅ Used only for project improvement
- ✅ No tracking of user identities
- ✅ Can be disabled if desired
## API Architecture
```
Installation Scripts
├─ Call: api.func functions
└─ POST to: https://api.community-scripts.org
├─ Receives data
├─ Validates format
├─ Stores metrics
└─ Aggregates statistics
└─ Used for:
├─ Download tracking
├─ Error trending
├─ Feature usage stats
└─ Project health monitoring
```
## Common API Tasks
- **Enable API reporting** → Built-in by default, no configuration needed
- **Disable API** → Set `api_disable="yes"` before running
- **View API data** → Visit https://community-scripts.org/stats
- **Report API errors** → [GitHub Issues](https://github.com/community-scripts/ProxmoxVE/issues)
## Debugging API Issues
If API calls fail:
1. Check internet connectivity
2. Verify API endpoint availability
3. Review error codes in [EXIT_CODES.md](../EXIT_CODES.md)
4. Check API function logs
5. Report issues on GitHub
## API Endpoint
**Base URL**: `https://api.community-scripts.org`
**Endpoints**:
- `POST /install` - Report container installation
- `POST /update` - Report application update
- `GET /stats` - Public statistics
---
**Last Updated**: December 2025
**Maintainers**: community-scripts team

View File

@ -0,0 +1,14 @@
<div align="center">
<img src="https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/misc/images/logo.png" height="100px" />
</div>
<h2><div align="center">Exploring the Scripts and Steps Involved in an Application LXC Installation</div></h2>
1) [adguard.sh](https://github.com/community-scripts/ProxmoxVE/blob/main/ct/adguard.sh): This script collects system parameters. (Also holds the function to update the application.)
2) [build.func](https://github.com/community-scripts/ProxmoxVE/blob/main/misc/build.func): Adds user settings and integrates collected information.
3) [create_lxc.sh](https://github.com/community-scripts/ProxmoxVE/blob/main/misc/create_lxc.sh): Constructs the LXC container.
4) [adguard-install.sh](https://github.com/community-scripts/ProxmoxVE/blob/main/install/adguard-install.sh): Executes functions from [install.func](https://github.com/community-scripts/ProxmoxVE/blob/main/misc/install.func), and installs the application.
5) [adguard.sh](https://github.com/community-scripts/ProxmoxVE/blob/main/ct/adguard.sh) (again): To display the completion message.
The installation process uses reusable scripts: [build.func](https://github.com/community-scripts/ProxmoxVE/blob/main/misc/build.func), [create_lxc.sh](https://github.com/community-scripts/ProxmoxVE/blob/main/misc/create_lxc.sh), and [install.func](https://github.com/community-scripts/ProxmoxVE/blob/main/misc/install.func), which are not specific to any particular application.
To gain a better understanding, focus on reviewing [adguard-install.sh](https://github.com/community-scripts/ProxmoxVE/blob/main/install/adguard-install.sh). This script contains the commands and configurations for installing and configuring AdGuard Home within the LXC container.

View File

@ -0,0 +1,106 @@
# Community Scripts Contribution Guide
## **Welcome to the communty-scripts Repository!**
📜 These documents outline the essential coding standards for all our scripts and JSON files. Adhering to these standards ensures that our codebase remains consistent, readable, and maintainable. By following these guidelines, we can improve collaboration, reduce errors, and enhance the overall quality of our project.
### Why Coding Standards Matter
Coding standards are crucial for several reasons:
1. **Consistency**: Consistent code is easier to read, understand, and maintain. It helps new team members quickly get up to speed and reduces the learning curve.
2. **Readability**: Clear and well-structured code is easier to debug and extend. It allows developers to quickly identify and fix issues.
3. **Maintainability**: Code that follows a standard structure is easier to refactor and update. It ensures that changes can be made with minimal risk of introducing new bugs.
4. **Collaboration**: When everyone follows the same standards, it becomes easier to collaborate on code. It reduces friction and misunderstandings during code reviews and merges.
### Scope of These Documents
These documents cover the coding standards for the following types of files in our project:
- **`install/$AppName-install.sh` Scripts**: These scripts are responsible for the installation of applications.
- **`ct/$AppName.sh` Scripts**: These scripts handle the creation and updating of containers.
- **`json/$AppName.json`**: These files store structured data and are used for the website.
Each section provides detailed guidelines on various aspects of coding, including shebang usage, comments, variable naming, function naming, indentation, error handling, command substitution, quoting, script structure, and logging. Additionally, examples are provided to illustrate the application of these standards.
By following the coding standards outlined in this document, we ensure that our scripts and JSON files are of high quality, making our project more robust and easier to manage. Please refer to this guide whenever you create or update scripts and JSON files to maintain a high standard of code quality across the project. 📚🔍
Let's work together to keep our codebase clean, efficient, and maintainable! 💪🚀
## Getting Started
Before contributing, please ensure that you have the following setup:
1. **Visual Studio Code** (recommended for script development)
2. **Recommended VS Code Extensions:**
- [Shell Syntax](https://marketplace.visualstudio.com/items?itemName=bmalehorn.shell-syntax)
- [ShellCheck](https://marketplace.visualstudio.com/items?itemName=timonwong.shellcheck)
- [Shell Format](https://marketplace.visualstudio.com/items?itemName=foxundermoon.shell-format)
### Important Notes
- Use [AppName.sh](https://github.com/community-scripts/ProxmoxVE/blob/main/.github/CONTRIBUTOR_AND_GUIDES/ct/AppName.sh) and [AppName-install.sh](https://github.com/community-scripts/ProxmoxVE/blob/main/.github/CONTRIBUTOR_AND_GUIDES/install/AppName-install.sh) as templates when creating new scripts.
---
# 🚀 The Application Script (ct/AppName.sh)
- You can find all coding standards, as well as the structure for this file [here](https://github.com/community-scripts/ProxmoxVE/blob/main/.github/CONTRIBUTOR_AND_GUIDES/ct/AppName.md).
- These scripts are responsible for container creation, setting the necessary variables and handling the update of the application once installed.
---
# 🛠 The Installation Script (install/AppName-install.sh)
- You can find all coding standards, as well as the structure for this file [here](https://github.com/community-scripts/ProxmoxVE/blob/main/.github/CONTRIBUTOR_AND_GUIDES/install/AppName-install.md).
- These scripts are responsible for the installation of the application.
---
## 🚀 Building Your Own Scripts
Start with the [template script](https://github.com/community-scripts/ProxmoxVE/blob/main/.github/CONTRIBUTOR_AND_GUIDES/install/AppName-install.sh)
---
## 🤝 Contribution Process
### 1. Fork the repository
Fork to your GitHub account
### 2. Clone your fork on your local environment
```bash
git clone https://github.com/yourUserName/ForkName
```
### 3. Create a new branch
```bash
git switch -c your-feature-branch
```
### 4. Change paths in build.func install.func and AppName.sh
To be able to develop from your own branch you need to change `https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main` to `https://raw.githubusercontent.com/[USER]/[REPOSITORY]/refs/heads/[BRANCH]`. You need to make this change atleast in misc/build.func misc/install.func and in your ct/AppName.sh. This change is only for testing. Before opening a Pull Request you should change this line change all this back to point to `https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main`.
### 4. Commit changes (without build.func and install.func!)
```bash
git commit -m "Your commit message"
```
### 5. Push to your fork
```bash
git push origin your-feature-branch
```
### 6. Create a Pull Request
Open a Pull Request from your feature branch to the main repository branch. You must only include your **$AppName.sh**, **$AppName-install.sh** and **$AppName.json** files in the pull request.
---
## 📚 Pages
- [CT Template: AppName.sh](https://github.com/community-scripts/ProxmoxVE/blob/main/.github/CONTRIBUTOR_AND_GUIDES/ct/AppName.sh)
- [Install Template: AppName-install.sh](https://github.com/community-scripts/ProxmoxVE/blob/main/.github/CONTRIBUTOR_AND_GUIDES/install/AppName-install.sh)
- [JSON Template: AppName.json](https://github.com/community-scripts/ProxmoxVE/blob/main/.github/CONTRIBUTOR_AND_GUIDES/json/AppName.json)

View File

@ -0,0 +1,186 @@
# 🍴 Fork Setup Guide
**Just forked ProxmoxVE? Run this first!**
## Quick Start
```bash
# Clone your fork
git clone https://github.com/YOUR_USERNAME/ProxmoxVE.git
cd ProxmoxVE
# Run setup script (auto-detects your username from git)
bash setup-fork.sh
```
That's it! ✅
---
## What Does It Do?
The `setup-fork.sh` script automatically:
1. **Detects** your GitHub username from git config
2. **Updates** 22 hardcoded links in documentation to point to your fork
3. **Creates** `.git-setup-info` with recommended git workflows
4. **Backs up** all modified files (*.backup)
---
## Usage
### Auto-Detect (Recommended)
```bash
bash setup-fork.sh
```
Automatically reads your GitHub username from `git remote origin url`
### Specify Username
```bash
bash setup-fork.sh john
```
Updates links to `github.com/john/ProxmoxVE`
### Custom Repository Name
```bash
bash setup-fork.sh john my-fork
```
Updates links to `github.com/john/my-fork`
---
## What Gets Updated?
The script updates these documentation files:
- `docs/CONTRIBUTION_GUIDE.md` (4 links)
- `docs/README.md` (1 link)
- `docs/INDEX.md` (3 links)
- `docs/EXIT_CODES.md` (2 links)
- `docs/DEFAULTS_SYSTEM_GUIDE.md` (2 links)
- `docs/api/README.md` (1 link)
- `docs/APP-ct.md` (1 link)
- `docs/APP-install.md` (1 link)
- `docs/alpine-install.func.md` (2 links)
- `docs/install.func.md` (1 link)
- And code examples in documentation
---
## After Setup
1. **Review changes**
```bash
git diff docs/
```
2. **Read git workflow tips**
```bash
cat .git-setup-info
```
3. **Start contributing**
```bash
git checkout -b feature/my-app
# Make your changes...
git commit -m "feat: add my awesome app"
```
4. **Follow the guide**
```bash
cat docs/CONTRIBUTION_GUIDE.md
```
---
## Common Workflows
### Keep Your Fork Updated
```bash
# Add upstream if you haven't already
git remote add upstream https://github.com/community-scripts/ProxmoxVE.git
# Get latest from upstream
git fetch upstream
git rebase upstream/main
git push origin main
```
### Create a Feature Branch
```bash
git checkout -b feature/docker-improvements
# Make changes...
git push origin feature/docker-improvements
# Then create PR on GitHub
```
### Sync Before Contributing
```bash
git fetch upstream
git rebase upstream/main
git push -f origin main # Update your fork's main
git checkout -b feature/my-feature
```
---
## Troubleshooting
### "Git is not installed" or "not a git repository"
```bash
# Make sure you cloned the repo first
git clone https://github.com/YOUR_USERNAME/ProxmoxVE.git
cd ProxmoxVE
bash setup-fork.sh
```
### "Could not auto-detect GitHub username"
```bash
# Your git origin URL isn't set up correctly
git remote -v
# Should show your fork URL, not community-scripts
# Fix it:
git remote set-url origin https://github.com/YOUR_USERNAME/ProxmoxVE.git
bash setup-fork.sh
```
### "Permission denied"
```bash
# Make script executable
chmod +x setup-fork.sh
bash setup-fork.sh
```
### Reverted Changes by Accident?
```bash
# Backups are created automatically
git checkout docs/*.backup
# Or just re-run setup-fork.sh
```
---
## Next Steps
1. ✅ Run `bash setup-fork.sh`
2. 📖 Read [docs/CONTRIBUTION_GUIDE.md](docs/CONTRIBUTION_GUIDE.md)
3. 🍴 Choose your contribution path:
- **Containers** → [docs/ct/README.md](docs/ct/README.md)
- **Installation** → [docs/install/README.md](docs/install/README.md)
- **VMs** → [docs/vm/README.md](docs/vm/README.md)
- **Tools** → [docs/tools/README.md](docs/tools/README.md)
4. 💻 Create your feature branch and contribute!
---
## Questions?
- **Fork Setup Issues?** → See [Troubleshooting](#troubleshooting) above
- **How to Contribute?** → [docs/CONTRIBUTION_GUIDE.md](docs/CONTRIBUTION_GUIDE.md)
- **Git Workflows?** → `cat .git-setup-info`
- **Project Structure?** → [docs/README.md](docs/README.md)
---
**Happy Contributing! 🚀**

1053
docs/contribution/GUIDE.md Normal file

File diff suppressed because it is too large Load Diff

341
docs/contribution/README.md Normal file
View File

@ -0,0 +1,341 @@
# 🤝 Contributing to ProxmoxVE
Complete guide to contributing to the ProxmoxVE project - from your first fork to submitting your pull request.
---
## 📋 Table of Contents
- [Quick Start](#quick-start)
- [Setting Up Your Fork](#setting-up-your-fork)
- [Coding Standards](#coding-standards)
- [Code Audit](#code-audit)
- [Guides & Resources](#guides--resources)
- [FAQ](#faq)
---
## 🚀 Quick Start
### 60 Seconds to Contributing
```bash
# 1. Fork on GitHub
# Visit: https://github.com/community-scripts/ProxmoxVE → Fork (top right)
# 2. Clone your fork
git clone https://github.com/YOUR_USERNAME/ProxmoxVE.git
cd ProxmoxVE
# 3. Auto-configure your fork
bash docs/contribution/setup-fork.sh
# 4. Create a feature branch
git checkout -b feature/my-awesome-app
# 5. Read the guides
cat docs/README.md # Documentation overview
cat docs/ct/DETAILED_GUIDE.md # For container scripts
cat docs/install/DETAILED_GUIDE.md # For install scripts
# 6. Create your contribution
cp ct/example.sh ct/myapp.sh
cp install/example-install.sh install/myapp-install.sh
# ... edit files ...
# 7. Test and commit
bash ct/myapp.sh
git add ct/myapp.sh install/myapp-install.sh
git commit -m "feat: add MyApp"
git push origin feature/my-awesome-app
# 8. Create Pull Request on GitHub
```
---
## 🍴 Setting Up Your Fork
### Automatic Setup (Recommended)
When you clone your fork, run the setup script to automatically configure everything:
```bash
bash docs/contribution/setup-fork.sh
```
This will:
- Auto-detect your GitHub username
- Update all documentation links to point to your fork
- Create `.git-setup-info` with recommended git workflows
**See**: [FORK_SETUP.md](FORK_SETUP.md) for detailed instructions
### Manual Setup
If the script doesn't work, manually configure:
```bash
# Set git user
git config user.name "Your Name"
git config user.email "your.email@example.com"
# Add upstream remote for syncing
git remote add upstream https://github.com/community-scripts/ProxmoxVE.git
# Verify remotes
git remote -v
```
---
## 📖 Coding Standards
All scripts and configurations must follow our coding standards to ensure consistency and quality.
### Available Guides
- **[CONTRIBUTING.md](CONTRIBUTING.md)** - Essential coding standards and best practices
- **[CODE_AUDIT.md](CODE_AUDIT.md)** - Code review checklist and audit procedures
- **Container Scripts** - `/ct/` templates and guidelines
- **Install Scripts** - `/install/` templates and guidelines
- **JSON Configurations** - `/json/` structure and format
### Quick Checklist
- ✅ Use `/ct/example.sh` as template for container scripts
- ✅ Use `/install/example-install.sh` as template for install scripts
- ✅ Follow naming conventions: `appname.sh` and `appname-install.sh`
- ✅ Include proper shebang: `#!/usr/bin/env bash`
- ✅ Add copyright header with author
- ✅ Handle errors properly with `msg_error`, `msg_ok`, etc.
- ✅ Test before submitting PR
- ✅ Update documentation if needed
---
## 🔍 Code Audit
Before submitting a pull request, ensure your code passes our audit:
**See**: [CODE_AUDIT.md](CODE_AUDIT.md) for complete audit checklist
Key points:
- Code consistency with existing scripts
- Proper error handling
- Correct variable naming
- Adequate comments and documentation
- Security best practices
---
## 📚 Guides & Resources
### Documentation
- **[docs/README.md](../README.md)** - Main documentation hub
- **[docs/ct/README.md](../ct/README.md)** - Container scripts overview
- **[docs/install/README.md](../install/README.md)** - Installation scripts overview
- **[docs/ct/DETAILED_GUIDE.md](../ct/DETAILED_GUIDE.md)** - Complete ct/ script reference
- **[docs/install/DETAILED_GUIDE.md](../install/DETAILED_GUIDE.md)** - Complete install/ script reference
- **[docs/TECHNICAL_REFERENCE.md](../TECHNICAL_REFERENCE.md)** - Architecture deep-dive
- **[docs/EXIT_CODES.md](../EXIT_CODES.md)** - Exit codes reference
- **[docs/DEV_MODE.md](../DEV_MODE.md)** - Debugging guide
### Community Guides
See [USER_SUBMITTED_GUIDES.md](USER_SUBMITTED_GUIDES.md) for excellent community-written guides:
- Home Assistant installation and configuration
- Frigate setup on Proxmox
- Docker and Portainer installation
- Database setup and optimization
- And many more!
### Templates
Use these templates when creating new scripts:
```bash
# Container script
cp ct/example.sh ct/my-app.sh
# Installation script
cp install/example-install.sh install/my-app-install.sh
# JSON configuration (if needed)
cp json/example.json json/my-app.json
```
---
## 🔄 Git Workflow
### Keep Your Fork Updated
```bash
# Fetch latest from upstream
git fetch upstream
# Rebase your work on latest main
git rebase upstream/main
# Push to your fork
git push -f origin main
```
### Create Feature Branch
```bash
# Create and switch to new branch
git checkout -b feature/my-feature
# Make changes...
git add .
git commit -m "feat: description of changes"
# Push to your fork
git push origin feature/my-feature
# Create Pull Request on GitHub
```
### Before Submitting PR
1. **Sync with upstream**
```bash
git fetch upstream
git rebase upstream/main
```
2. **Test your changes**
```bash
bash ct/my-app.sh
# Follow prompts and test the container
```
3. **Check code standards**
- [ ] Follows template structure
- [ ] Proper error handling
- [ ] Documentation updated (if needed)
- [ ] No hardcoded values
- [ ] Version tracking implemented
4. **Push final changes**
```bash
git push origin feature/my-feature
```
---
## 📋 Pull Request Checklist
Before opening a PR:
- [ ] Code follows coding standards (see CONTRIBUTING.md)
- [ ] All templates used correctly
- [ ] Tested on Proxmox VE
- [ ] Error handling implemented
- [ ] Documentation updated (if applicable)
- [ ] No merge conflicts
- [ ] Synced with upstream/main
- [ ] Clear PR title and description
---
## ❓ FAQ
### How do I test my changes?
```bash
# For container scripts
bash ct/my-app.sh
# For install scripts (runs inside container)
# The ct script will call it automatically
# For advanced debugging
VERBOSE=yes bash ct/my-app.sh
```
### What if my PR has conflicts?
```bash
# Sync with upstream
git fetch upstream
git rebase upstream/main
# Resolve conflicts in your editor
git add .
git rebase --continue
git push -f origin your-branch
```
### How do I keep my fork updated?
See "Keep Your Fork Updated" section above, or run:
```bash
bash docs/contribution/setup-fork.sh
```
### Where do I ask questions?
- **GitHub Issues**: For bugs and feature requests
- **GitHub Discussions**: For general questions
- **Discord**: Community-scripts server
---
## 🎓 Learning Resources
### For First-Time Contributors
1. Read: [docs/README.md](../README.md) - Documentation overview
2. Read: [docs/contribution/FORK_SETUP.md](FORK_SETUP.md) - Fork setup guide
3. Choose your path:
- Containers → [docs/ct/DETAILED_GUIDE.md](../ct/DETAILED_GUIDE.md)
- Installation → [docs/install/DETAILED_GUIDE.md](../install/DETAILED_GUIDE.md)
4. Study existing scripts in same category
5. Create your contribution
### For Experienced Developers
1. Review [CONTRIBUTING.md](CONTRIBUTING.md) - Coding standards
2. Review [CODE_AUDIT.md](CODE_AUDIT.md) - Audit checklist
3. Check templates in `/ct/` and `/install/`
4. Submit PR with confidence
### For Reviewers/Maintainers
1. Use [CODE_AUDIT.md](CODE_AUDIT.md) as review guide
2. Reference [docs/TECHNICAL_REFERENCE.md](../TECHNICAL_REFERENCE.md) for architecture
3. Check [docs/EXIT_CODES.md](../EXIT_CODES.md) for error handling
---
## 🚀 Ready to Contribute?
1. **Fork** the repository
2. **Clone** your fork and **setup** with `bash docs/contribution/setup-fork.sh`
3. **Choose** your contribution type (container, installation, tools, etc.)
4. **Read** the appropriate detailed guide
5. **Create** your feature branch
6. **Develop** and **test** your changes
7. **Commit** with clear messages
8. **Push** to your fork
9. **Create** Pull Request
---
## 📞 Contact & Support
- **GitHub**: https://github.com/community-scripts/ProxmoxVE
- **Issues**: https://github.com/community-scripts/ProxmoxVE/issues
- **Discussions**: https://github.com/community-scripts/ProxmoxVE/discussions
- **Discord**: [Join Server](https://discord.gg/UHrpNWGwkH)
---
**Thank you for contributing to ProxmoxVE!** 🙏
Your efforts help make Proxmox VE automation accessible to everyone. Happy coding! 🚀

View File

@ -0,0 +1,44 @@
<div align="center">
<a href="#">
<img src="https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/misc/images/logo.png" height="100px" />
</a>
</div>
<h2 align="center">User Submitted Guides </h2>
<sub> In order to contribute a guide on installing with Proxmox VE Helper Scripts, you should open a pull request that adds the guide to the `USER_SUBMITTED_GUIDES.md` file. </sub>
[Proxmox Automation with Proxmox Helper Scripts!](https://www.youtube.com/watch?v=kcpu4z5eSEU)
[Installing Home Assistant OS using Proxmox 8](https://community.home-assistant.io/t/installing-home-assistant-os-using-proxmox-8/201835)
[How To Separate Zigbee2MQTT From Home Assistant In Proxmox](https://smarthomescene.com/guides/how-to-separate-zigbee2mqtt-from-home-assistant-in-proxmox/)
[How To Install Home Assistant On Proxmox: The Easy Way](https://smarthomescene.com/guides/how-to-install-home-assistant-on-proxmox-the-easy-way/)
[Home Assistant: Installing InfluxDB (LXC)](https://www.derekseaman.com/2023/04/home-assistant-installing-influxdb-lxc.html)
[Home Assistant: Proxmox Quick Start Guide](https://www.derekseaman.com/2023/10/home-assistant-proxmox-ve-8-0-quick-start-guide-2.html)
[Home Assistant: Installing Grafana (LXC) with Lets Encrypt SSL](https://www.derekseaman.com/2023/04/home-assistant-installing-grafana-lxc.html)
[Proxmox: Plex LXC with Alder Lake Transcoding](https://www.derekseaman.com/2023/04/proxmox-plex-lxc-with-alder-lake-transcoding.html)
[How To Backup Home Assistant In Proxmox](https://smarthomescene.com/guides/how-to-backup-home-assistant-in-proxmox/)
[Running Frigate on Proxmox](https://www.homeautomationguy.io/blog/running-frigate-on-proxmox)
[Frigate VM on Proxmox with PCIe Coral TPU](https://www.derekseaman.com/2023/06/home-assistant-frigate-vm-on-proxmox-with-pcie-coral-tpu.html)
[Moving Home Assistants Database To MariaDB On Proxmox](https://smarthomescene.com/guides/moving-home-assistants-database-to-mariadb-on-proxmox/)
[How-to: Proxmox VE 7.4 to 8.0 Upgrade](https://www.derekseaman.com/2023/06/how-to-proxmox-7-4-to-8-0-upgrade.html)
[iGPU Transcoding In Proxmox with Jellyfin](https://www.youtube.com/watch?v=XAa_qpNmzZs)
[Proxmox + NetData](<https://dbt3ch.com/books/proxmox-netdata-for-better-insights-and-notifications/page/proxmox-netdata-for-better-insights-and-notifications>)
[Proxmox Homelab Series](<https://blog.kye.dev/proxmox-series>)
[The fastest installation of Docker and Portainer on Proxmox VE](https://lavr.site/en-fastest-install-docker-portainer-proxmox/)
[How To Setup Proxmox Backuper Server Using Helper Scripts](<https://youtu.be/6C2JOsrZZZw?si=kkrrcL_nLCDBJkOB>)

View File

@ -0,0 +1,313 @@
#!/bin/bash
################################################################################
# ProxmoxVE Fork Setup Script
#
# Automatically configures documentation and scripts for your fork
# Detects your GitHub username and repository from git config
# Updates all hardcoded links to point to your fork
#
# Usage:
# ./setup-fork.sh # Auto-detect from git config
# ./setup-fork.sh YOUR_USERNAME # Specify username
# ./setup-fork.sh YOUR_USERNAME REPO_NAME # Specify both
#
# Examples:
# ./setup-fork.sh john # Uses john/ProxmoxVE
# ./setup-fork.sh john my-fork # Uses john/my-fork
################################################################################
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Default values
REPO_NAME="ProxmoxVE"
USERNAME=""
AUTO_DETECT=true
################################################################################
# FUNCTIONS
################################################################################
print_header() {
echo -e "\n${BLUE}╔════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}${NC} ProxmoxVE Fork Setup Script"
echo -e "${BLUE}${NC} Configuring for your fork..."
echo -e "${BLUE}╚════════════════════════════════════════════════════════════╝${NC}\n"
}
print_info() {
echo -e "${BLUE}${NC} $1"
}
print_success() {
echo -e "${GREEN}${NC} $1"
}
print_warning() {
echo -e "${YELLOW}${NC} $1"
}
print_error() {
echo -e "${RED}${NC} $1"
}
# Detect username from git remote
detect_username() {
local remote_url
# Try to get from origin
if ! remote_url=$(git config --get remote.origin.url 2>/dev/null); then
return 1
fi
# Extract username from SSH or HTTPS URL
if [[ $remote_url =~ git@github.com:([^/]+) ]]; then
echo "${BASH_REMATCH[1]}"
elif [[ $remote_url =~ github.com/([^/]+) ]]; then
echo "${BASH_REMATCH[1]}"
else
return 1
fi
}
# Detect repo name from git remote
detect_repo_name() {
local remote_url
if ! remote_url=$(git config --get remote.origin.url 2>/dev/null); then
return 1
fi
# Extract repo name (remove .git if present)
if [[ $remote_url =~ /([^/]+?)(.git)?$ ]]; then
local repo="${BASH_REMATCH[1]}"
echo "${repo%.git}"
else
return 1
fi
}
# Ask user for confirmation
confirm() {
local prompt="$1"
local response
read -p "$(echo -e ${YELLOW})$prompt (y/n)${NC} " -r response
[[ $response =~ ^[Yy]$ ]]
}
# Update links in files
update_links() {
local old_repo="community-scripts"
local old_name="ProxmoxVE"
local new_owner="$1"
local new_repo="$2"
local files_updated=0
print_info "Scanning for hardcoded links..."
# Find all markdown and shell files
local -a files_to_update=(
"docs/DEFAULTS_SYSTEM_GUIDE.md"
"docs/alpine-install.func.md"
"docs/install.func.md"
"docs/APP-install.md"
"docs/APP-ct.md"
"docs/CONTRIBUTION_GUIDE.md"
"docs/INDEX.md"
"docs/README.md"
"docs/EXIT_CODES.md"
"docs/api/README.md"
)
echo ""
for file in "${files_to_update[@]}"; do
if [[ -f "$file" ]]; then
# Count occurrences
local count=$(grep -c "github.com/$old_repo/$old_name" "$file" 2>/dev/null || echo 0)
if [[ $count -gt 0 ]]; then
# Backup original
cp "$file" "$file.backup"
# Replace links
sed -i "s|github.com/$old_repo/$old_name|github.com/$new_owner/$new_repo|g" "$file"
((files_updated++))
print_success "Updated $file ($count links)"
fi
fi
done
return $files_updated
}
# Create user git config setup info
create_git_setup_info() {
local username="$1"
cat >.git-setup-info <<'EOF'
# Git Configuration for ProxmoxVE Development
## Recommended Git Configuration
### Set up remotes for easy syncing with upstream:
```bash
# View your current remotes
git remote -v
# If you don't have 'upstream' configured, add it:
git remote add upstream https://github.com/community-scripts/ProxmoxVE.git
# Verify both remotes exist:
git remote -v
# Should show:
# origin https://github.com/YOUR_USERNAME/ProxmoxVE.git (fetch)
# origin https://github.com/YOUR_USERNAME/ProxmoxVE.git (push)
# upstream https://github.com/community-scripts/ProxmoxVE.git (fetch)
# upstream https://github.com/community-scripts/ProxmoxVE.git (push)
```
### Configure Git User (if not done globally)
```bash
git config user.name "Your Name"
git config user.email "your.email@example.com"
# Or configure globally:
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
```
### Useful Git Workflows
**Keep your fork up-to-date:**
```bash
git fetch upstream
git rebase upstream/main
git push origin main
```
**Create feature branch:**
```bash
git checkout -b feature/my-awesome-app
# Make changes...
git commit -m "feat: add my awesome app"
git push origin feature/my-awesome-app
```
**Pull latest from upstream:**
```bash
git fetch upstream
git merge upstream/main
```
---
For more help, see: docs/CONTRIBUTION_GUIDE.md
EOF
print_success "Created .git-setup-info file"
}
################################################################################
# MAIN LOGIC
################################################################################
print_header
# Parse command line arguments
if [[ $# -gt 0 ]]; then
USERNAME="$1"
AUTO_DETECT=false
if [[ $# -gt 1 ]]; then
REPO_NAME="$2"
fi
else
# Try auto-detection
if username=$(detect_username); then
USERNAME="$username"
print_success "Detected GitHub username: $USERNAME"
else
print_error "Could not auto-detect GitHub username from git config"
echo -e "${YELLOW}Please run:${NC}"
echo " ./setup-fork.sh YOUR_USERNAME"
exit 1
fi
if repo_name=$(detect_repo_name); then
REPO_NAME="$repo_name"
if [[ "$REPO_NAME" != "ProxmoxVE" ]]; then
print_info "Detected custom repo name: $REPO_NAME"
else
print_success "Using default repo name: ProxmoxVE"
fi
fi
fi
# Validate inputs
if [[ -z "$USERNAME" ]]; then
print_error "Username cannot be empty"
exit 1
fi
if [[ -z "$REPO_NAME" ]]; then
print_error "Repository name cannot be empty"
exit 1
fi
# Show what we'll do
echo -e "${BLUE}Configuration Summary:${NC}"
echo " Repository URL: https://github.com/$USERNAME/$REPO_NAME"
echo " Files to update: 10 files with documentation"
echo ""
# Ask for confirmation
if ! confirm "Apply these changes?"; then
print_warning "Setup cancelled"
exit 0
fi
echo ""
# Update all links
if update_links "$USERNAME" "$REPO_NAME"; then
links_changed=$?
print_success "Updated $links_changed files"
else
print_warning "No links needed updating or some files not found"
fi
# Create git setup info file
create_git_setup_info "$USERNAME"
# Final summary
echo ""
echo -e "${GREEN}╔════════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}${NC} Fork Setup Complete! ${GREEN}${NC}"
echo -e "${GREEN}╚════════════════════════════════════════════════════════════╝${NC}"
echo ""
print_success "All documentation links updated to point to your fork"
print_info "Your fork: https://github.com/$USERNAME/$REPO_NAME"
print_info "Upstream: https://github.com/community-scripts/ProxmoxVE"
echo ""
echo -e "${BLUE}Next Steps:${NC}"
echo " 1. Review the changes: git diff"
echo " 2. Check .git-setup-info for recommended git workflow"
echo " 3. Start developing: git checkout -b feature/my-app"
echo " 4. Read: docs/CONTRIBUTION_GUIDE.md"
echo ""
print_success "Happy contributing! 🚀"

View File

@ -0,0 +1,286 @@
# **AppName<span></span>.sh Scripts**
`AppName.sh` scripts found in the `/ct` directory. These scripts are responsible for the installation of the desired application. For this guide we take `/ct/snipeit.sh` as example.
## Table of Contents
- [**AppName.sh Scripts**](#appnamesh-scripts)
- [Table of Contents](#table-of-contents)
- [1. **File Header**](#1-file-header)
- [1.1 **Shebang**](#11-shebang)
- [1.2 **Import Functions**](#12-import-functions)
- [1.3 **Metadata**](#13-metadata)
- [2 **Variables and function import**](#2-variables-and-function-import)
- [2.1 **Default Values**](#21-default-values)
- [2.2 **📋 App output \& base settings**](#22--app-output--base-settings)
- [2.3 **🛠 Core functions**](#23--core-functions)
- [3 **Update function**](#3-update-function)
- [3.1 **Function Header**](#31-function-header)
- [3.2 **Check APP**](#32-check-app)
- [3.3 **Check version**](#33-check-version)
- [3.4 **Verbosity**](#34-verbosity)
- [3.5 **Backups**](#35-backups)
- [3.6 **Cleanup**](#36-cleanup)
- [3.7 **No update function**](#37-no-update-function)
- [4 **End of the script**](#4-end-of-the-script)
- [5. **Contribution checklist**](#5-contribution-checklist)
## 1. **File Header**
### 1.1 **Shebang**
- Use `#!/usr/bin/env bash` as the shebang.
```bash
#!/usr/bin/env bash
```
### 1.2 **Import Functions**
- Import the build.func file.
- When developing your own script, change the URL to your own repository.
> [!IMPORTANT]
> You also need to change all apperances of this URL in `misc/build.func` and `misc/install.func`
Example for development:
```bash
source <(curl -s https://raw.githubusercontent.com/[USER]/[REPO]/refs/heads/[BRANCH]/misc/build.func)
```
Final script:
```bash
source <(curl -s https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/misc/build.func)
```
> [!CAUTION]
> Before opening a Pull Request, change the URLs to point to the community-scripts repo.
### 1.3 **Metadata**
- Add clear comments for script metadata, including author, copyright, and license information.
Example:
```bash
# Copyright (c) 2021-2025 community-scripts ORG
# Author: [YourUserName]
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE
# Source: [SOURCE_URL]
```
> [!NOTE]:
>
> - Add your username and source URL
> - For existing scripts, add "| Co-Author [YourUserName]" after the current author
---
## 2 **Variables and function import**
>
> [!NOTE]
> You need to have all this set in your script, otherwise it will not work!
### 2.1 **Default Values**
- This section sets the default values for the container.
- `APP` needs to be set to the application name and must be equal to the filenames of your scripts.
- `var_tags`: You can set Tags for the CT wich show up in the Proxmox UI. Don´t overdo it!
>[!NOTE]
>Description for all Default Values
>
>| Variable | Description | Notes |
>|----------|-------------|-------|
>| `APP` | Application name | Must match ct\AppName.sh |
>| `var_tags` | Proxmox display tags without Spaces, only ; | Limit the number |
>| `var_cpu` | CPU cores | Number of cores |
>| `var_ram` | RAM | In MB |
>| `var_disk` | Disk capacity | In GB |
>| `var_os` | Operating system | alpine, debian, ubuntu |
>| `var_version` | OS version | e.g., 3.20, 11, 12, 20.04 |
>| `var_unprivileged` | Container type | 1 = Unprivileged, 0 = Privileged |
Example:
```bash
APP="SnipeIT"
var_tags="asset-management;foss"
var_cpu="2"
var_ram="2048"
var_disk="4"
var_os="debian"
var_version="12"
var_unprivileged="1"
```
## 2.2 **📋 App output & base settings**
```bash
header_info "$APP"
```
- `header_info`: Generates ASCII header for APP
## 2.3 **🛠 Core functions**
```bash
variables
color
catch_errors
```
- `variables`: Processes input and prepares variables
- `color`: Sets icons, colors, and formatting
- `catch_errors`: Enables error handling
---
## 3 **Update function**
### 3.1 **Function Header**
- If applicable write a function that updates the application and the OS in the container.
- Each update function starts with the same code:
```bash
function update_script() {
header_info
check_container_storage
check_container_resources
```
### 3.2 **Check APP**
- Before doing anything update-wise, check if the app is installed in the container.
Example:
```bash
if [[ ! -d /opt/snipe-it ]]; then
msg_error "No ${APP} Installation Found!"
exit
fi
```
### 3.3 **Check version**
- Before updating, check if a new version exists.
- We use the `${APPLICATION}_version.txt` file created in `/opt` during the install to compare new versions against the currently installed version.
Example with a Github Release:
```bash
RELEASE=$(curl -fsSL https://api.github.com/repos/snipe/snipe-it/releases/latest | grep "tag_name" | awk '{print substr($2, 3, length($2)-4) }')
if [[ ! -f /opt/${APP}_version.txt ]] || [[ "${RELEASE}" != "$(cat /opt/${APP}_version.txt)" ]]; then
msg_info "Updating ${APP} to v${RELEASE}"
#DO UPDATE
else
msg_ok "No update required. ${APP} is already at v${RELEASE}."
fi
exit
}
```
### 3.4 **Verbosity**
- Use the appropriate flag (**-q** in the examples) for a command to suppress its output.
Example:
```bash
curl -fsSL
unzip -q
```
- If a command does not come with this functionality use `$STD` to suppress it's output.
Example:
```bash
$STD php artisan migrate --force
$STD php artisan config:clear
```
### 3.5 **Backups**
- Backup user data if necessary.
- Move all user data back in the directory when the update is finished.
>[!NOTE]
>This is not meant to be a permanent backup
Example backup:
```bash
mv /opt/snipe-it /opt/snipe-it-backup
```
Example config restore:
```bash
cp /opt/snipe-it-backup/.env /opt/snipe-it/.env
cp -r /opt/snipe-it-backup/public/uploads/ /opt/snipe-it/public/uploads/
cp -r /opt/snipe-it-backup/storage/private_uploads /opt/snipe-it/storage/private_uploads
```
### 3.6 **Cleanup**
- Do not forget to remove any temporary files/folders such as zip-files or temporary backups.
Example:
```bash
rm -rf /opt/v${RELEASE}.zip
rm -rf /opt/snipe-it-backup
```
### 3.7 **No update function**
- In case you can not provide an update function use the following code to provide user feedback.
```bash
function update_script() {
header_info
check_container_storage
check_container_resources
if [[ ! -d /opt/snipeit ]]; then
msg_error "No ${APP} Installation Found!"
exit
fi
msg_error "Currently we don't provide an update function for this ${APP}."
exit
}
```
---
## 4 **End of the script**
- `start`: Launches Whiptail dialogue
- `build_container`: Collects and integrates user settings
- `description`: Sets LXC container description
- With `echo -e "${TAB}${GATEWAY}${BGN}http://${IP}${CL}"` you can point the user to the IP:PORT/folder needed to access the app.
```bash
start
build_container
description
msg_ok "Completed Successfully!\n"
echo -e "${CREATING}${GN}${APP} setup has been successfully initialized!${CL}"
echo -e "${INFO}${YW} Access it using the following URL:${CL}"
echo -e "${TAB}${GATEWAY}${BGN}http://${IP}${CL}"
```
---
## 5. **Contribution checklist**
- [ ] Shebang is correctly set (`#!/usr/bin/env bash`).
- [ ] Correct link to *build.func*
- [ ] Metadata (author, license) is included at the top.
- [ ] Variables follow naming conventions.
- [ ] Update function exists.
- [ ] Update functions checks if app is installed and for new version.
- [ ] Update function cleans up temporary files.
- [ ] Script ends with a helpful message for the user to reach the application.

View File

@ -0,0 +1,86 @@
#!/usr/bin/env bash
source <(curl -s https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/misc/build.func)
# Copyright (c) 2021-2025 community-scripts ORG
# Author: [YourUserName]
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE
# Source: [SOURCE_URL]
# App Default Values
APP="[APP_NAME]"
# Name of the app (e.g. Google, Adventurelog, Apache-Guacamole"
var_tags="[TAGS]"
# Tags for Proxmox VE, maximum 2 pcs., no spaces allowed, separated by a semicolon ; (e.g. database | adblock;dhcp)
var_cpu="[CPU]"
# Number of cores (1-X) (e.g. 4) - default are 2
var_ram="[RAM]"
# Amount of used RAM in MB (e.g. 2048 or 4096)
var_disk="[DISK]"
# Amount of used disk space in GB (e.g. 4 or 10)
var_os="[OS]"
# Default OS (e.g. debian, ubuntu, alpine)
var_version="[VERSION]"
# Default OS version (e.g. 12 for debian, 24.04 for ubuntu, 3.20 for alpine)
var_unprivileged="[UNPRIVILEGED]"
# 1 = unprivileged container, 0 = privileged container
header_info "$APP"
variables
color
catch_errors
function update_script() {
header_info
check_container_storage
check_container_resources
# Check if installation is present | -f for file, -d for folder
if [[ ! -f [INSTALLATION_CHECK_PATH] ]]; then
msg_error "No ${APP} Installation Found!"
exit
fi
# Crawling the new version and checking whether an update is required
RELEASE=$(curl -fsSL [RELEASE_URL] | [PARSE_RELEASE_COMMAND])
if [[ "${RELEASE}" != "$(cat /opt/${APP}_version.txt)" ]] || [[ ! -f /opt/${APP}_version.txt ]]; then
# Stopping Services
msg_info "Stopping $APP"
systemctl stop [SERVICE_NAME]
msg_ok "Stopped $APP"
# Creating Backup
msg_info "Creating Backup"
tar -czf "/opt/${APP}_backup_$(date +%F).tar.gz" [IMPORTANT_PATHS]
msg_ok "Backup Created"
# Execute Update
msg_info "Updating $APP to v${RELEASE}"
[UPDATE_COMMANDS]
msg_ok "Updated $APP to v${RELEASE}"
# Starting Services
msg_info "Starting $APP"
systemctl start [SERVICE_NAME]
msg_ok "Started $APP"
# Cleaning up
msg_info "Cleaning Up"
rm -rf [TEMP_FILES]
msg_ok "Cleanup Completed"
# Last Action
echo "${RELEASE}" >/opt/${APP}_version.txt
msg_ok "Update Successful"
else
msg_ok "No update required. ${APP} is already at v${RELEASE}"
fi
exit
}
start
build_container
description
msg_ok "Completed Successfully!\n"
echo -e "${CREATING}${GN}${APP} setup has been successfully initialized!${CL}"
echo -e "${INFO}${YW} Access it using the following URL:${CL}"
echo -e "${TAB}${GATEWAY}${BGN}http://${IP}:[PORT]${CL}"

View File

@ -0,0 +1,353 @@
# **AppName<span></span>-install.sh Scripts**
`AppName-install.sh` scripts found in the `/install` directory. These scripts are responsible for the installation of the application. For this guide we take `/install/snipeit-install.sh` as example.
## Table of Contents
- [**AppName-install.sh Scripts**](#appname-installsh-scripts)
- [Table of Contents](#table-of-contents)
- [1. **File header**](#1-file-header)
- [1.1 **Shebang**](#11-shebang)
- [1.2 **Comments**](#12-comments)
- [1.3 **Variables and function import**](#13-variables-and-function-import)
- [2. **Variable naming and management**](#2-variable-naming-and-management)
- [2.1 **Naming conventions**](#21-naming-conventions)
- [3. **Dependencies**](#3-dependencies)
- [3.1 **Install all at once**](#31-install-all-at-once)
- [3.2 **Collapse dependencies**](#32-collapse-dependencies)
- [4. **Paths to application files**](#4-paths-to-application-files)
- [5. **Version management**](#5-version-management)
- [5.1 **Install the latest release**](#51-install-the-latest-release)
- [5.2 **Save the version for update checks**](#52-save-the-version-for-update-checks)
- [6. **Input and output management**](#6-input-and-output-management)
- [6.1 **User feedback**](#61-user-feedback)
- [6.2 **Verbosity**](#62-verbosity)
- [7. **String/File Manipulation**](#7-stringfile-manipulation)
- [7.1 **File Manipulation**](#71-file-manipulation)
- [8. **Security practices**](#8-security-practices)
- [8.1 **Password generation**](#81-password-generation)
- [8.2 **File permissions**](#82-file-permissions)
- [9. **Service Configuration**](#9-service-configuration)
- [9.1 **Configuration files**](#91-configuration-files)
- [9.2 **Credential management**](#92-credential-management)
- [9.3 **Enviroment files**](#93-enviroment-files)
- [9.4 **Services**](#94-services)
- [10. **Cleanup**](#10-cleanup)
- [10.1 **Remove temporary files**](#101-remove-temporary-files)
- [10.2 **Autoremove and autoclean**](#102-autoremove-and-autoclean)
- [11. **Best Practices Checklist**](#11-best-practices-checklist)
- [Example: High-Level Script Flow](#example-high-level-script-flow)
## 1. **File header**
### 1.1 **Shebang**
- Use `#!/usr/bin/env bash` as the shebang.
```bash
#!/usr/bin/env bash
```
### 1.2 **Comments**
- Add clear comments for script metadata, including author, copyright, and license information.
- Use meaningful inline comments to explain complex commands or logic.
Example:
```bash
# Copyright (c) 2021-2025 community-scripts ORG
# Author: [YourUserName]
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE
# Source: [SOURCE_URL]
```
> [!NOTE]:
>
> - Add your username
> - When updating/reworking scripts, add "| Co-Author [YourUserName]"
### 1.3 **Variables and function import**
- This sections adds the support for all needed functions and variables.
```bash
source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
color
verb_ip6
catch_errors
setting_up_container
network_check
update_os
```
---
## 2. **Variable naming and management**
### 2.1 **Naming conventions**
- Use uppercase names for constants and environment variables.
- Use lowercase names for local script variables.
Example:
```bash
DB_NAME=snipeit_db # Environment-like variable (constant)
db_user="snipeit" # Local variable
```
---
## 3. **Dependencies**
### 3.1 **Install all at once**
- Install all dependencies with a single command if possible
Example:
```bash
$STD apt-get install -y \
curl \
composer \
git \
sudo \
mc \
nginx
```
### 3.2 **Collapse dependencies**
Collapse dependencies to keep the code readable.
Example:
Use
```bash
php8.2-{bcmath,common,ctype}
```
instead of
```bash
php8.2-bcmath php8.2-common php8.2-ctype
```
---
## 4. **Paths to application files**
If possible install the app and all necessary files in `/opt/`
---
## 5. **Version management**
### 5.1 **Install the latest release**
- Always try and install the latest release
- Do not hardcode any version if not absolutely necessary
Example for a git release:
```bash
RELEASE=$(curl -fsSL https://api.github.com/repos/snipe/snipe-it/releases/latest | grep "tag_name" | awk '{print substr($2, 3, length($2)-4) }')
curl -fsSL "https://github.com/snipe/snipe-it/archive/refs/tags/v${RELEASE}.zip"
```
### 5.2 **Save the version for update checks**
- Write the installed version into a file.
- This is used for the update function in **AppName.sh** to check for if a Update is needed.
Example:
```bash
echo "${RELEASE}" >"/opt/AppName_version.txt"
```
---
## 6. **Input and output management**
### 6.1 **User feedback**
- Use standard functions like `msg_info`, `msg_ok` or `msg_error` to print status messages.
- Each `msg_info` must be followed with a `msg_ok` before any other output is made.
- Display meaningful progress messages at key stages.
Example:
```bash
msg_info "Installing Dependencies"
$STD apt-get install -y ...
msg_ok "Installed Dependencies"
```
### 6.2 **Verbosity**
- Use the appropiate flag (**-q** in the examples) for a command to suppres its output
Example:
```bash
curl -fsSL
unzip -q
```
- If a command dose not come with such a functionality use `$STD` (a custom standard redirection variable) for managing output verbosity.
Example:
```bash
$STD apt-get install -y nginx
```
---
## 7. **String/File Manipulation**
### 7.1 **File Manipulation**
- Use `sed` to replace placeholder values in configuration files.
Example:
```bash
sed -i -e "s|^DB_DATABASE=.*|DB_DATABASE=$DB_NAME|" \
-e "s|^DB_USERNAME=.*|DB_USERNAME=$DB_USER|" \
-e "s|^DB_PASSWORD=.*|DB_PASSWORD=$DB_PASS|" .env
```
---
## 8. **Security practices**
### 8.1 **Password generation**
- Use `openssl` to generate random passwords.
- Use only alphanumeric values to not introduce unknown behaviour.
Example:
```bash
DB_PASS=$(openssl rand -base64 18 | tr -dc 'a-zA-Z0-9' | head -c13)
```
### 8.2 **File permissions**
Explicitly set secure ownership and permissions for sensitive files.
Example:
```bash
chown -R www-data: /opt/snipe-it
chmod -R 755 /opt/snipe-it
```
---
## 9. **Service Configuration**
### 9.1 **Configuration files**
Use `cat <<EOF` to write configuration files in a clean and readable way.
Example:
```bash
cat <<EOF >/etc/nginx/conf.d/snipeit.conf
server {
listen 80;
root /opt/snipe-it/public;
index index.php;
}
EOF
```
### 9.2 **Credential management**
Store the generated credentials in a file.
Example:
```bash
USERNAME=username
PASSWORD=$(openssl rand -base64 18 | tr -dc 'a-zA-Z0-9' | head -c13)
{
echo "Application-Credentials"
echo "Username: $USERNAME"
echo "Password: $PASSWORD"
} >> ~/application.creds
```
### 9.3 **Enviroment files**
Use `cat <<EOF` to write enviromental files in a clean and readable way.
Example:
```bash
cat <<EOF >/path/to/.env
VARIABLE="value"
PORT=3000
DB_NAME="${DB_NAME}"
EOF
```
### 9.4 **Services**
Enable affected services after configuration changes and start them right away.
Example:
```bash
systemctl enable -q --now nginx
```
---
## 10. **Cleanup**
### 10.1 **Remove temporary files**
Remove temporary files and downloads after use.
Example:
```bash
rm -rf /opt/v${RELEASE}.zip
```
### 10.2 **Autoremove and autoclean**
Remove unused dependencies to reduce disk space usage.
Example:
```bash
apt-get -y autoremove
apt-get -y autoclean
```
---
## 11. **Best Practices Checklist**
- [ ] Shebang is correctly set (`#!/usr/bin/env bash`).
- [ ] Metadata (author, license) is included at the top.
- [ ] Variables follow naming conventions.
- [ ] Sensitive values are dynamically generated.
- [ ] Files and services have proper permissions.
- [ ] Script cleans up temporary files.
---
### Example: High-Level Script Flow
1. Dependencies installation
2. Database setup
3. Download and configure application
4. Service configuration
5. Final cleanup

View File

@ -0,0 +1,83 @@
#!/usr/bin/env bash
# Copyright (c) 2021-2025 community-scripts ORG
# Author: [YourUserName]
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE
# Source: [SOURCE_URL]
# Import Functions und Setup
source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
color
verb_ip6
catch_errors
setting_up_container
network_check
update_os
# Installing Dependencies with the 3 core dependencies (curl;sudo;mc)
msg_info "Installing Dependencies"
$STD apt-get install -y \
curl \
sudo \
mc \
[PACKAGE_1] \
[PACKAGE_2] \
[PACKAGE_3]
msg_ok "Installed Dependencies"
# Template: MySQL Database
msg_info "Setting up Database"
DB_NAME=[DB_NAME]
DB_USER=[DB_USER]
DB_PASS=$(openssl rand -base64 18 | tr -dc 'a-zA-Z0-9' | head -c13)
$STD mysql -u root -e "CREATE DATABASE $DB_NAME;"
$STD mysql -u root -e "CREATE USER '$DB_USER'@'localhost' IDENTIFIED WITH mysql_native_password AS PASSWORD('$DB_PASS');"
$STD mysql -u root -e "GRANT ALL ON $DB_NAME.* TO '$DB_USER'@'localhost'; FLUSH PRIVILEGES;"
{
echo "${APPLICATION} Credentials"
echo "Database User: $DB_USER"
echo "Database Password: $DB_PASS"
echo "Database Name: $DB_NAME"
} >>~/$APP_NAME.creds
msg_ok "Set up Database"
# Temp
# Setup App
msg_info "Setup ${APPLICATION}"
RELEASE=$(curl -s https://api.github.com/repos/[REPO]/releases/latest | grep "tag_name" | awk '{print substr($2, 2, length($2)-3) }')
curl -fsSL "https://github.com/[REPO]/archive/refs/tags/${RELEASE}.zip"
unzip -q ${RELEASE}.zip
mv ${APPLICATION}-${RELEASE}/ /opt/${APPLICATION}
#
#
#
echo "${RELEASE}" >/opt/${APPLICATION}_version.txt
msg_ok "Setup ${APPLICATION}"
# Creating Service (if needed)
msg_info "Creating Service"
cat <<EOF >/etc/systemd/system/${APPLICATION}.service
[Unit]
Description=${APPLICATION} Service
After=network.target
[Service]
ExecStart=[START_COMMAND]
Restart=always
[Install]
WantedBy=multi-user.target
EOF
systemctl enable -q --now ${APPLICATION}.service
msg_ok "Created Service"
motd_ssh
customize
# Cleanup
msg_info "Cleaning up"
rm -f ${RELEASE}.zip
$STD apt-get -y autoremove
$STD apt-get -y autoclean
msg_ok "Cleaned"

472
docs/ct/DETAILED_GUIDE.md Normal file
View File

@ -0,0 +1,472 @@
# 🚀 **Application Container Scripts (ct/AppName.sh)**
**Modern Guide to Creating LXC Container Installation Scripts**
> **Updated**: December 2025
> **Context**: Fully integrated with build.func, advanced_settings wizard, and defaults system
> **Example Used**: `/ct/pihole.sh`, `/ct/docker.sh`
---
## 📋 Table of Contents
- [Overview](#overview)
- [Architecture & Flow](#architecture--flow)
- [File Structure](#file-structure)
- [Complete Script Template](#complete-script-template)
- [Function Reference](#function-reference)
- [Advanced Features](#advanced-features)
- [Real Examples](#real-examples)
- [Troubleshooting](#troubleshooting)
- [Contribution Checklist](#contribution-checklist)
---
## Overview
### Purpose
Container scripts (`ct/AppName.sh`) are **entry points for creating LXC containers** with specific applications pre-installed. They:
1. Define container defaults (CPU, RAM, disk, OS)
2. Call the main build orchestrator (`build.func`)
3. Implement application-specific update mechanisms
4. Provide user-facing success messages
### Execution Context
```
Proxmox Host
ct/AppName.sh sourced (runs as root on host)
build.func: Creates LXC container + runs install script inside
install/AppName-install.sh (runs inside container)
Container ready with app installed
```
### Key Integration Points
- **build.func** - Main orchestrator (container creation, storage, variable management)
- **install.func** - Container-specific setup (OS update, package management)
- **tools.func** - Tool installation helpers (repositories, GitHub releases)
- **core.func** - UI/messaging functions (colors, spinners, validation)
- **error_handler.func** - Error handling and signal management
---
## Architecture & Flow
### Container Creation Flow
```
START: bash ct/pihole.sh
[1] Set APP, var_*, defaults
[2] header_info() → Display ASCII art
[3] variables() → Parse arguments & load build.func
[4] color() → Setup ANSI codes
[5] catch_errors() → Setup trap handlers
[6] install_script() → Show mode menu (5 options)
├─ INSTALL_MODE="0" (Default)
├─ INSTALL_MODE="1" (Advanced - 19-step wizard)
├─ INSTALL_MODE="2" (User Defaults)
├─ INSTALL_MODE="3" (App Defaults)
└─ INSTALL_MODE="4" (Settings Menu)
[7] advanced_settings() → Collect user configuration (if mode=1)
[8] start() → Confirm or re-edit settings
[9] build_container() → Create LXC + execute install script
[10] description() → Set container description
[11] SUCCESS → Display access URL
END
```
### Default Values Precedence
```
Priority 1 (Highest): Environment Variables (var_cpu, var_ram, etc.)
Priority 2: App-Specific Defaults (/defaults/AppName.vars)
Priority 3: User Global Defaults (/default.vars)
Priority 4 (Lowest): Built-in Defaults (in build.func)
```
---
## File Structure
### Minimal ct/AppName.sh Template
```
#!/usr/bin/env bash # [1] Shebang
# [2] Copyright/License
source <(curl -s .../misc/build.func) # [3] Import functions
# [4] APP metadata
APP="AppName" # [5] Default values
var_tags="tag1;tag2"
var_cpu="2"
var_ram="2048"
...
header_info "$APP" # [6] Display header
variables # [7] Process arguments
color # [8] Setup colors
catch_errors # [9] Setup error handling
function update_script() { ... } # [10] Update function (optional)
start # [11] Launch container creation
build_container
description
msg_ok "Completed Successfully!\n"
```
---
## Complete Script Template
### 1. File Header & Imports
```bash
#!/usr/bin/env bash
# Copyright (c) 2021-2025 community-scripts ORG
# Author: YourUsername
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE
# Source: https://github.com/example/project
# Import main orchestrator
source <(curl -fsSL https://git.community-scripts.org/community-scripts/ProxmoxVE/raw/branch/main/misc/build.func)
```
> **⚠️ IMPORTANT**: Before opening a PR, change URL to `community-scripts` repo!
### 2. Application Metadata
```bash
# Application Configuration
APP="ApplicationName"
var_tags="tag1;tag2;tag3" # Max 3-4 tags, no spaces, semicolon-separated
# Container Resources
var_cpu="2" # CPU cores
var_ram="2048" # RAM in MB
var_disk="10" # Disk in GB
# Container Type & OS
var_os="debian" # Options: alpine, debian, ubuntu
var_version="12" # Alpine: 3.20+, Debian: 11-13, Ubuntu: 20.04+
var_unprivileged="1" # 1=unprivileged (secure), 0=privileged (rarely needed)
```
**Variable Naming Convention**:
- Variables exposed to user: `var_*` (e.g., `var_cpu`, `var_hostname`, `var_ssh`)
- Internal variables: lowercase (e.g., `container_id`, `app_version`)
### 3. Display & Initialization
```bash
# Display header ASCII art
header_info "$APP"
# Process command-line arguments and load configuration
variables
# Setup ANSI color codes and formatting
color
# Initialize error handling (trap ERR, EXIT, INT, TERM)
catch_errors
```
### 4. Update Function (Highly Recommended)
```bash
function update_script() {
header_info
# Always start with these checks
check_container_storage
check_container_resources
# Verify app is installed
if [[ ! -d /opt/appname ]]; then
msg_error "No ${APP} Installation Found!"
exit
fi
# Get latest version from GitHub
RELEASE=$(curl -fsSL https://api.github.com/repos/user/repo/releases/latest | \
grep "tag_name" | awk '{print substr($2, 2, length($2)-3)}')
# Compare with saved version
if [[ ! -f /opt/${APP}_version.txt ]] || [[ "${RELEASE}" != "$(cat /opt/${APP}_version.txt)" ]]; then
msg_info "Updating ${APP} to v${RELEASE}"
# Backup user data
cp -r /opt/appname /opt/appname-backup
# Perform update
cd /opt
wget -q "https://github.com/user/repo/releases/download/v${RELEASE}/app-${RELEASE}.tar.gz"
tar -xzf app-${RELEASE}.tar.gz
# Restore user data
cp /opt/appname-backup/config/* /opt/appname/config/
# Cleanup
rm -rf app-${RELEASE}.tar.gz /opt/appname-backup
# Save new version
echo "${RELEASE}" > /opt/${APP}_version.txt
msg_ok "Updated ${APP} to v${RELEASE}"
else
msg_ok "No update required. ${APP} is already at v${RELEASE}."
fi
exit
}
```
### 5. Script Launch
```bash
# Start the container creation workflow
start
# Build the container with selected configuration
build_container
# Set container description/notes in Proxmox UI
description
# Display success message
msg_ok "Completed Successfully!\n"
echo -e "${CREATING}${GN}${APP} setup has been successfully initialized!${CL}"
echo -e "${INFO}${YW} Access it using the following URL:${CL}"
echo -e "${TAB}${GATEWAY}${BGN}http://${IP}:8080${CL}"
```
---
## Function Reference
### Core Functions (From build.func)
#### `variables()`
**Purpose**: Initialize container variables, load user arguments, setup orchestration
**Triggered by**: Called automatically at script start
**Behavior**:
1. Parse command-line arguments (if any)
2. Generate random UUID for session tracking
3. Load container storage from Proxmox
4. Initialize application-specific defaults
5. Setup SSH/environment configuration
#### `start()`
**Purpose**: Launch the container creation menu with 5 installation modes
**Menu Options**:
```
1. Default Installation (Quick setup, predefined settings)
2. Advanced Installation (19-step wizard with full control)
3. User Defaults (Load ~/.community-scripts/default.vars)
4. App Defaults (Load /defaults/AppName.vars)
5. Settings Menu (Interactive mode selection)
```
#### `build_container()`
**Purpose**: Main orchestrator for LXC container creation
**Operations**:
1. Validates all variables
2. Creates LXC container via `pct create`
3. Executes `install/AppName-install.sh` inside container
4. Monitors installation progress
5. Handles errors and rollback on failure
#### `description()`
**Purpose**: Set container description/notes visible in Proxmox UI
---
## Advanced Features
### 1. Custom Configuration Menus
If your app has additional setup beyond standard vars:
```bash
custom_app_settings() {
CONFIGURE_DB=$(whiptail --title "Database Setup" \
--yesno "Would you like to configure a custom database?" 8 60)
if [[ $? -eq 0 ]]; then
DB_HOST=$(whiptail --inputbox "Database Host:" 8 60 3>&1 1>&2 2>&3)
DB_PORT=$(whiptail --inputbox "Database Port:" 8 60 "3306" 3>&1 1>&2 2>&3)
fi
}
custom_app_settings
```
### 2. Update Function Patterns
Save installed version for update checks
### 3. Health Check Functions
Add custom validation:
```bash
function health_check() {
header_info
if [[ ! -d /opt/appname ]]; then
msg_error "Application not found!"
exit 1
fi
if ! systemctl is-active --quiet appname; then
msg_error "Application service not running"
exit 1
fi
msg_ok "Health check passed"
}
```
---
## Real Examples
### Example 1: Simple Web App (Debian-based)
```bash
#!/usr/bin/env bash
source <(curl -fsSL https://git.community-scripts.org/community-scripts/ProxmoxVE/raw/branch/main/misc/build.func)
APP="Homarr"
var_tags="dashboard;homepage"
var_cpu="2"
var_ram="1024"
var_disk="5"
var_os="debian"
var_version="12"
var_unprivileged="1"
header_info "$APP"
variables
color
catch_errors
function update_script() {
# Update logic here
}
start
build_container
description
msg_ok "Completed Successfully!\n"
```
---
## Troubleshooting
### Container Creation Fails
**Symptom**: `pct create` exits with error code 209
**Solution**:
```bash
# Check existing containers
pct list | grep CTID
# Remove conflicting container
pct destroy CTID
# Retry ct/AppName.sh
```
### Update Function Doesn't Detect New Version
**Debug**:
```bash
# Check version file
cat /opt/AppName_version.txt
# Test GitHub API
curl -fsSL https://api.github.com/repos/user/repo/releases/latest | grep tag_name
```
---
## Contribution Checklist
Before submitting a PR:
### Script Structure
- [ ] Shebang is `#!/usr/bin/env bash`
- [ ] Imports `build.func` from community-scripts repo
- [ ] Copyright header with author and source URL
- [ ] APP variable matches filename
- [ ] `var_tags` are semicolon-separated (no spaces)
### Default Values
- [ ] `var_cpu` set appropriately (2-4 for most apps)
- [ ] `var_ram` set appropriately (1024-4096 MB minimum)
- [ ] `var_disk` sufficient for app + data (5-20 GB)
- [ ] `var_os` is realistic
### Functions
- [ ] `update_script()` implemented
- [ ] Update function checks if app installed
- [ ] Proper error handling with `msg_error`
### Testing
- [ ] Script tested with default installation
- [ ] Script tested with advanced (19-step) installation
- [ ] Update function tested on existing installation
---
## Best Practices
### ✅ DO:
1. **Use meaningful defaults**
2. **Implement version tracking**
3. **Handle edge cases**
4. **Use proper messaging with msg_info/msg_ok/msg_error**
### ❌ DON'T:
1. **Hardcode versions**
2. **Use custom color codes** (use built-in variables)
3. **Forget error handling**
4. **Leave temporary files**
---
**Last Updated**: December 2025
**Compatibility**: ProxmoxVE with build.func v3+

72
docs/ct/README.md Normal file
View File

@ -0,0 +1,72 @@
# Container Scripts Documentation (/ct)
This directory contains comprehensive documentation for container creation scripts in the `/ct` directory.
## Overview
Container scripts (`ct/*.sh`) are the entry points for creating LXC containers in Proxmox VE. They run on the host and orchestrate the entire container creation process.
## Documentation Structure
Each script has standardized documentation following the project pattern.
## Key Resources
- **[DETAILED_GUIDE.md](DETAILED_GUIDE.md)** - Complete reference for creating ct scripts
- **[../contribution/README.md](../contribution/README.md)** - How to contribute
- **[../misc/build.func/](../misc/build.func/)** - Core orchestrator documentation
## Container Creation Flow
```
ct/AppName.sh (host-side)
├─ Calls: build.func (orchestrator)
├─ Variables: var_cpu, var_ram, var_disk, var_os
└─ Creates: LXC Container
└─ Runs: install/appname-install.sh (inside)
```
## Available Scripts
See `/ct` directory for all container creation scripts. Common examples:
- `pihole.sh` - Pi-hole DNS/DHCP server
- `docker.sh` - Docker container runtime
- `wallabag.sh` - Article reading & archiving
- `nextcloud.sh` - Private cloud storage
- `debian.sh` - Basic Debian container
- And 30+ more...
## Quick Start
To understand how to create a container script:
1. Read: [UPDATED_APP-ct.md](../UPDATED_APP-ct.md)
2. Study: A similar existing script in `/ct`
3. Copy template and customize
4. Test locally
5. Submit PR
## Contributing a New Container
1. Create `ct/myapp.sh`
2. Create `install/myapp-install.sh`
3. Follow template in [UPDATED_APP-ct.md](../UPDATED_APP-ct.md)
4. Test thoroughly
5. Submit PR with both files
## Common Tasks
- **Add new container application** → [CONTRIBUTION_GUIDE.md](../CONTRIBUTION_GUIDE.md)
- **Debug container creation** → [EXIT_CODES.md](../EXIT_CODES.md)
- **Understand build.func** → [misc/build.func/](../misc/build.func/)
- **Development mode debugging** → [DEV_MODE.md](../DEV_MODE.md)
---
**Last Updated**: December 2025
**Maintainers**: community-scripts team

View File

@ -0,0 +1,840 @@
# Configuration Reference
**Complete reference for all configuration variables and options in community-scripts for Proxmox VE.**
---
## Table of Contents
1. [Variable Naming Convention](#variable-naming-convention)
2. [Complete Variable Reference](#complete-variable-reference)
3. [Resource Configuration](#resource-configuration)
4. [Network Configuration](#network-configuration)
5. [IPv6 Configuration](#ipv6-configuration)
6. [SSH Configuration](#ssh-configuration)
7. [Container Features](#container-features)
8. [Storage Configuration](#storage-configuration)
9. [Security Settings](#security-settings)
10. [Advanced Options](#advanced-options)
11. [Quick Reference Table](#quick-reference-table)
---
## Variable Naming Convention
All configuration variables follow a consistent pattern:
```
var_<setting>=<value>
```
**Rules:**
- ✅ Always starts with `var_`
- ✅ Lowercase letters only
- ✅ Underscores for word separation
- ✅ No spaces around `=`
- ✅ Values can be quoted if needed
**Examples:**
```bash
# ✓ Correct
var_cpu=4
var_hostname=myserver
var_ssh_authorized_key=ssh-rsa AAAA...
# ✗ Wrong
CPU=4 # Missing var_ prefix
var_CPU=4 # Uppercase not allowed
var_cpu = 4 # Spaces around =
var-cpu=4 # Hyphens not allowed
```
---
## Complete Variable Reference
### var_unprivileged
**Type:** Boolean (0 or 1)
**Default:** `1` (unprivileged)
**Description:** Determines if container runs unprivileged (recommended) or privileged.
```bash
var_unprivileged=1 # Unprivileged (safer, recommended)
var_unprivileged=0 # Privileged (less secure, more features)
```
**When to use privileged (0):**
- Hardware access required
- Certain kernel modules needed
- Legacy applications
- Nested virtualization with full features
**Security Impact:**
- Unprivileged: Container root is mapped to unprivileged user on host
- Privileged: Container root = host root (security risk)
---
### var_cpu
**Type:** Integer
**Default:** Varies by app (usually 1-4)
**Range:** 1 to host CPU count
**Description:** Number of CPU cores allocated to container.
```bash
var_cpu=1 # Single core (minimal)
var_cpu=2 # Dual core (typical)
var_cpu=4 # Quad core (recommended for apps)
var_cpu=8 # High performance
```
**Best Practices:**
- Start with 2 cores for most applications
- Monitor usage with `pct exec <id> -- htop`
- Can be changed after creation
- Consider host CPU count (don't over-allocate)
---
### var_ram
**Type:** Integer (MB)
**Default:** Varies by app (usually 512-2048)
**Range:** 512 MB to host RAM
**Description:** Amount of RAM in megabytes.
```bash
var_ram=512 # 512 MB (minimal)
var_ram=1024 # 1 GB (typical)
var_ram=2048 # 2 GB (comfortable)
var_ram=4096 # 4 GB (recommended for databases)
var_ram=8192 # 8 GB (high memory apps)
```
**Conversion Guide:**
```
512 MB = 0.5 GB
1024 MB = 1 GB
2048 MB = 2 GB
4096 MB = 4 GB
8192 MB = 8 GB
16384 MB = 16 GB
```
**Best Practices:**
- Minimum 512 MB for basic Linux
- 1 GB for typical applications
- 2-4 GB for web servers, databases
- Monitor with `free -h` inside container
---
### var_disk
**Type:** Integer (GB)
**Default:** Varies by app (usually 2-8)
**Range:** 0.001 GB to storage capacity
**Description:** Root disk size in gigabytes.
```bash
var_disk=2 # 2 GB (minimal OS only)
var_disk=4 # 4 GB (typical)
var_disk=8 # 8 GB (comfortable)
var_disk=20 # 20 GB (recommended for apps)
var_disk=50 # 50 GB (large applications)
var_disk=100 # 100 GB (databases, media)
```
**Important Notes:**
- Can be expanded after creation (not reduced)
- Actual space depends on storage type
- Thin provisioning supported on most storage
- Plan for logs, data, updates
**Recommended Sizes by Use Case:**
```
Basic Linux container: 4 GB
Web server (Nginx/Apache): 8 GB
Application server: 10-20 GB
Database server: 20-50 GB
Docker host: 30-100 GB
Media server: 100+ GB
```
---
### var_hostname
**Type:** String
**Default:** Application name
**Max Length:** 63 characters
**Description:** Container hostname (FQDN format allowed).
```bash
var_hostname=myserver
var_hostname=pihole
var_hostname=docker-01
var_hostname=web.example.com
```
**Rules:**
- Lowercase letters, numbers, hyphens
- Cannot start or end with hyphen
- No underscores allowed
- No spaces
**Best Practices:**
```bash
# ✓ Good
var_hostname=web-server
var_hostname=db-primary
var_hostname=app.domain.com
# ✗ Avoid
var_hostname=Web_Server # Uppercase, underscore
var_hostname=-server # Starts with hyphen
var_hostname=my server # Contains space
```
---
### var_brg
**Type:** String
**Default:** `vmbr0`
**Description:** Network bridge interface.
```bash
var_brg=vmbr0 # Default Proxmox bridge
var_brg=vmbr1 # Custom bridge
var_brg=vmbr2 # Isolated network
```
**Common Setups:**
```
vmbr0 → Main network (LAN)
vmbr1 → Guest network
vmbr2 → DMZ
vmbr3 → Management
vmbr4 → Storage network
```
**Check available bridges:**
```bash
ip link show | grep vmbr
# or
brctl show
```
---
### var_net
**Type:** String
**Options:** `dhcp` or `static`
**Default:** `dhcp`
**Description:** IPv4 network configuration method.
```bash
var_net=dhcp # Automatic IP via DHCP
var_net=static # Manual IP configuration
```
**DHCP Mode:**
- Automatic IP assignment
- Easy setup
- Good for development
- Requires DHCP server on network
**Static Mode:**
- Fixed IP address
- Requires gateway configuration
- Better for servers
- Configure via advanced settings or after creation
---
### var_gateway
**Type:** IPv4 Address
**Default:** Auto-detected from host
**Description:** Network gateway IP address.
```bash
var_gateway=192.168.1.1
var_gateway=10.0.0.1
var_gateway=172.16.0.1
```
**Auto-detection:**
If not specified, system detects gateway from host:
```bash
ip route | grep default
```
**When to specify:**
- Multiple gateways available
- Custom routing setup
- Different network segment
---
### var_vlan
**Type:** Integer
**Range:** 1-4094
**Default:** None
**Description:** VLAN tag for network isolation.
```bash
var_vlan=10 # VLAN 10
var_vlan=100 # VLAN 100
var_vlan=200 # VLAN 200
```
**Common VLAN Schemes:**
```
VLAN 10 → Management
VLAN 20 → Servers
VLAN 30 → Desktops
VLAN 40 → Guest WiFi
VLAN 50 → IoT devices
VLAN 99 → DMZ
```
**Requirements:**
- Switch must support VLANs
- Proxmox bridge configured for VLAN aware
- Gateway on same VLAN
---
### var_mtu
**Type:** Integer
**Default:** `1500`
**Range:** 68-9000
**Description:** Maximum Transmission Unit size.
```bash
var_mtu=1500 # Standard Ethernet
var_mtu=1492 # PPPoE
var_mtu=9000 # Jumbo frames
```
**Common Values:**
```
1500 → Standard Ethernet (default)
1492 → PPPoE connections
1400 → Some VPN setups
9000 → Jumbo frames (10GbE networks)
```
**When to change:**
- Jumbo frames for performance on 10GbE
- PPPoE internet connections
- VPN tunnels with overhead
- Specific network requirements
---
### var_mac
**Type:** MAC Address
**Format:** `XX:XX:XX:XX:XX:XX`
**Default:** Auto-generated
**Description:** Container MAC address.
```bash
var_mac=02:00:00:00:00:01
var_mac=DE:AD:BE:EF:00:01
```
**When to specify:**
- MAC-based licensing
- Static DHCP reservations
- Network access control
- Cloning configurations
**Best Practices:**
- Use locally administered addresses (2nd bit set)
- Start with `02:`, `06:`, `0A:`, `0E:`
- Avoid vendor OUIs
- Document custom MACs
---
### var_ipv6_method
**Type:** String
**Options:** `auto`, `dhcp`, `static`, `none`, `disable`
**Default:** `none`
**Description:** IPv6 configuration method.
```bash
var_ipv6_method=auto # SLAAC (auto-configuration)
var_ipv6_method=dhcp # DHCPv6
var_ipv6_method=static # Manual configuration
var_ipv6_method=none # IPv6 enabled but not configured
var_ipv6_method=disable # IPv6 completely disabled
```
**Detailed Options:**
**auto (SLAAC)**
- Stateless Address Auto-Configuration
- Router advertisements
- No DHCPv6 server needed
- Recommended for most cases
**dhcp (DHCPv6)**
- Stateful configuration
- Requires DHCPv6 server
- More control over addressing
**static**
- Manual IPv6 address
- Manual gateway
- Full control
**none**
- IPv6 stack active
- No address configured
- Can configure later
**disable**
- IPv6 completely disabled at kernel level
- Use when IPv6 causes issues
- Sets `net.ipv6.conf.all.disable_ipv6=1`
---
### var_ns
**Type:** IP Address
**Default:** Auto (from host)
**Description:** DNS nameserver IP.
```bash
var_ns=8.8.8.8 # Google DNS
var_ns=1.1.1.1 # Cloudflare DNS
var_ns=9.9.9.9 # Quad9 DNS
var_ns=192.168.1.1 # Local DNS
```
**Common DNS Servers:**
```
8.8.8.8, 8.8.4.4 → Google Public DNS
1.1.1.1, 1.0.0.1 → Cloudflare DNS
9.9.9.9, 149.112.112.112 → Quad9 DNS
208.67.222.222 → OpenDNS
192.168.1.1 → Local router/Pi-hole
```
---
### var_ssh
**Type:** Boolean
**Options:** `yes` or `no`
**Default:** `no`
**Description:** Enable SSH server in container.
```bash
var_ssh=yes # SSH server enabled
var_ssh=no # SSH server disabled (console only)
```
**When enabled:**
- OpenSSH server installed
- Started on boot
- Port 22 open
- Root login allowed
**Security Considerations:**
- Disable if not needed
- Use SSH keys instead of passwords
- Consider non-standard port
- Firewall rules recommended
---
### var_ssh_authorized_key
**Type:** String (SSH public key)
**Default:** None
**Description:** SSH public key for root user.
```bash
var_ssh_authorized_key=ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC... user@host
var_ssh_authorized_key=ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA... user@host
```
**Supported Key Types:**
- RSA (2048-4096 bits)
- Ed25519 (recommended)
- ECDSA
- DSA (deprecated)
**How to get your public key:**
```bash
cat ~/.ssh/id_rsa.pub
# or
cat ~/.ssh/id_ed25519.pub
```
**Multiple keys:**
Separate with newlines (in file) or use multiple deployments.
---
### var_pw
**Type:** String
**Default:** Empty (auto-login)
**Description:** Root password.
```bash
var_pw=SecurePassword123! # Set password
var_pw= # Auto-login (empty)
```
**Auto-login behavior:**
- No password required for console
- Automatic login on console access
- SSH still requires key if enabled
- Suitable for development
**Password best practices:**
- Minimum 12 characters
- Mix upper/lower/numbers/symbols
- Use password manager
- Rotate regularly
---
### var_nesting
**Type:** Boolean (0 or 1)
**Default:** `1`
**Description:** Allow nested containers (required for Docker).
```bash
var_nesting=1 # Nested containers allowed
var_nesting=0 # Nested containers disabled
```
**Required for:**
- Docker
- LXC inside LXC
- Systemd features
- Container orchestration
**Security Impact:**
- Slightly reduced isolation
- Required for container platforms
- Generally safe when unprivileged
---
### var_keyctl
**Type:** Boolean (0 or 1)
**Default:** `0`
**Description:** Enable keyctl system call.
```bash
var_keyctl=1 # Keyctl enabled
var_keyctl=0 # Keyctl disabled
```
**Required for:**
- Docker in some configurations
- Systemd keyring features
- Encryption key management
- Some authentication systems
---
### var_fuse
**Type:** Boolean (0 or 1)
**Default:** `0`
**Description:** Enable FUSE filesystem support.
```bash
var_fuse=1 # FUSE enabled
var_fuse=0 # FUSE disabled
```
**Required for:**
- sshfs
- AppImage
- Some backup tools
- User-space filesystems
---
### var_mknod
**Type:** Boolean (0 or 1)
**Default:** `0`
**Description:** Allow device node creation.
```bash
var_mknod=1 # Device nodes allowed
var_mknod=0 # Device nodes disabled
```
**Requires:**
- Kernel 5.3+
- Experimental feature
- Use with caution
---
### var_mount_fs
**Type:** String (comma-separated)
**Default:** Empty
**Description:** Allowed mountable filesystems.
```bash
var_mount_fs=nfs
var_mount_fs=nfs,cifs
var_mount_fs=ext4,xfs,nfs
```
**Common Options:**
```
nfs → NFS network shares
cifs → SMB/CIFS shares
ext4 → Ext4 filesystems
xfs → XFS filesystems
btrfs → Btrfs filesystems
```
---
### var_protection
**Type:** Boolean
**Options:** `yes` or `no`
**Default:** `no`
**Description:** Prevent accidental deletion.
```bash
var_protection=yes # Protected from deletion
var_protection=no # Can be deleted normally
```
**When protected:**
- Cannot delete via GUI
- Cannot delete via `pct destroy`
- Must disable protection first
- Good for production containers
---
### var_tags
**Type:** String (comma-separated)
**Default:** `community-script`
**Description:** Container tags for organization.
```bash
var_tags=production
var_tags=production,webserver
var_tags=dev,testing,temporary
```
**Best Practices:**
```bash
# Environment tags
var_tags=production
var_tags=development
var_tags=staging
# Function tags
var_tags=webserver,nginx
var_tags=database,postgresql
var_tags=cache,redis
# Project tags
var_tags=project-alpha,frontend
var_tags=customer-xyz,billing
# Combined
var_tags=production,webserver,project-alpha
```
---
### var_timezone
**Type:** String (TZ database format)
**Default:** Host timezone
**Description:** Container timezone.
```bash
var_timezone=Europe/Berlin
var_timezone=America/New_York
var_timezone=Asia/Tokyo
```
**Common Timezones:**
```
Europe/London
Europe/Berlin
Europe/Paris
America/New_York
America/Chicago
America/Los_Angeles
Asia/Tokyo
Asia/Singapore
Australia/Sydney
UTC
```
**List all timezones:**
```bash
timedatectl list-timezones
```
---
### var_verbose
**Type:** Boolean
**Options:** `yes` or `no`
**Default:** `no`
**Description:** Enable verbose output.
```bash
var_verbose=yes # Show all commands
var_verbose=no # Silent mode
```
**When enabled:**
- Shows all executed commands
- Displays detailed progress
- Useful for debugging
- More log output
---
### var_apt_cacher
**Type:** Boolean
**Options:** `yes` or `no`
**Default:** `no`
**Description:** Use APT caching proxy.
```bash
var_apt_cacher=yes
var_apt_cacher=no
```
**Benefits:**
- Faster package installs
- Reduced bandwidth
- Offline package cache
- Speeds up multiple containers
---
### var_apt_cacher_ip
**Type:** IP Address
**Default:** None
**Description:** APT cacher proxy IP.
```bash
var_apt_cacher=yes
var_apt_cacher_ip=192.168.1.100
```
**Setup apt-cacher-ng:**
```bash
apt install apt-cacher-ng
# Runs on port 3142
```
---
### var_container_storage
**Type:** String
**Default:** Auto-detected
**Description:** Storage for container.
```bash
var_container_storage=local
var_container_storage=local-zfs
var_container_storage=pve-storage
```
**List available storage:**
```bash
pvesm status
```
---
### var_template_storage
**Type:** String
**Default:** Auto-detected
**Description:** Storage for templates.
```bash
var_template_storage=local
var_template_storage=nfs-templates
```
---
## Quick Reference Table
| Variable | Type | Default | Example |
|----------|------|---------|---------|
| `var_unprivileged` | 0/1 | 1 | `var_unprivileged=1` |
| `var_cpu` | int | varies | `var_cpu=4` |
| `var_ram` | int (MB) | varies | `var_ram=4096` |
| `var_disk` | int (GB) | varies | `var_disk=20` |
| `var_hostname` | string | app name | `var_hostname=server` |
| `var_brg` | string | vmbr0 | `var_brg=vmbr1` |
| `var_net` | dhcp/static | dhcp | `var_net=dhcp` |
| `var_gateway` | IP | auto | `var_gateway=192.168.1.1` |
| `var_ipv6_method` | string | none | `var_ipv6_method=disable` |
| `var_vlan` | int | - | `var_vlan=100` |
| `var_mtu` | int | 1500 | `var_mtu=9000` |
| `var_mac` | MAC | auto | `var_mac=02:00:00:00:00:01` |
| `var_ns` | IP | auto | `var_ns=8.8.8.8` |
| `var_ssh` | yes/no | no | `var_ssh=yes` |
| `var_ssh_authorized_key` | string | - | `var_ssh_authorized_key=ssh-rsa...` |
| `var_pw` | string | empty | `var_pw=password` |
| `var_nesting` | 0/1 | 1 | `var_nesting=1` |
| `var_keyctl` | 0/1 | 0 | `var_keyctl=1` |
| `var_fuse` | 0/1 | 0 | `var_fuse=1` |
| `var_mknod` | 0/1 | 0 | `var_mknod=1` |
| `var_mount_fs` | string | - | `var_mount_fs=nfs,cifs` |
| `var_protection` | yes/no | no | `var_protection=yes` |
| `var_tags` | string | community-script | `var_tags=prod,web` |
| `var_timezone` | string | host TZ | `var_timezone=Europe/Berlin` |
| `var_verbose` | yes/no | no | `var_verbose=yes` |
| `var_apt_cacher` | yes/no | no | `var_apt_cacher=yes` |
| `var_apt_cacher_ip` | IP | - | `var_apt_cacher_ip=192.168.1.10` |
| `var_container_storage` | string | auto | `var_container_storage=local-zfs` |
| `var_template_storage` | string | auto | `var_template_storage=local` |
---
## See Also
- [Defaults System Guide](DEFAULTS_GUIDE.md)
- [Unattended Deployments](UNATTENDED_DEPLOYMENTS.md)
- [Security Best Practices](SECURITY_GUIDE.md)
- [Network Configuration](NETWORK_GUIDE.md)

View File

@ -0,0 +1,748 @@
# Configuration & Defaults System - User Guide
> **Complete Guide to App Defaults and User Defaults**
>
> *Learn how to configure, save, and reuse your installation settings*
---
## Table of Contents
1. [Quick Start](#quick-start)
2. [Understanding the Defaults System](#understanding-the-defaults-system)
3. [Installation Modes](#installation-modes)
4. [How to Save Defaults](#how-to-save-defaults)
5. [How to Use Saved Defaults](#how-to-use-saved-defaults)
6. [Managing Your Defaults](#managing-your-defaults)
7. [Advanced Configuration](#advanced-configuration)
8. [Troubleshooting](#troubleshooting)
---
## Quick Start
### 30-Second Setup
```bash
# 1. Run any container installation script
bash pihole-install.sh
# 2. When prompted, select: "Advanced Settings"
# (This allows you to customize everything)
# 3. Answer all configuration questions
# 4. At the end, when asked "Save as App Defaults?"
# Select: YES
# 5. Done! Your settings are now saved
```
**Next Time**: Run the same script again, select **"App Defaults"** and your settings will be applied automatically!
---
## Understanding the Defaults System
### The Three-Tier System
Your installation settings are managed through three layers:
#### 🔷 **Tier 1: Built-in Defaults** (Fallback)
```
These are hardcoded in the scripts
Provide sensible defaults for each application
Example: PiHole uses 2 CPU cores by default
```
#### 🔶 **Tier 2: User Defaults** (Global)
```
Your personal global defaults
Applied to ALL container installations
Location: /usr/local/community-scripts/default.vars
Example: "I always want 4 CPU cores and 2GB RAM"
```
#### 🔴 **Tier 3: App Defaults** (Specific)
```
Application-specific saved settings
Only applied when installing that specific app
Location: /usr/local/community-scripts/defaults/<appname>.vars
Example: "Whenever I install PiHole, use these exact settings"
```
### Priority System
When installing a container, settings are applied in this order:
```
┌─────────────────────────────────────┐
│ 1. Environment Variables (HIGHEST) │ Set in shell: export var_cpu=8
│ (these override everything) │
├─────────────────────────────────────┤
│ 2. App Defaults │ From: defaults/pihole.vars
│ (app-specific saved settings) │
├─────────────────────────────────────┤
│ 3. User Defaults │ From: default.vars
│ (your global defaults) │
├─────────────────────────────────────┤
│ 4. Built-in Defaults (LOWEST) │ Hardcoded in script
│ (failsafe, always available) │
└─────────────────────────────────────┘
```
**In Plain English**:
- If you set an environment variable → it wins
- Otherwise, if you have app-specific defaults → use those
- Otherwise, if you have user defaults → use those
- Otherwise, use the hardcoded defaults
---
## Installation Modes
When you run any installation script, you'll be presented with a menu:
### Option 1⃣ : **Default Settings**
```
Quick installation with standard settings
├─ Best for: First-time users, quick deployments
├─ What happens:
│ 1. Script uses built-in defaults
│ 2. Container created immediately
│ 3. No questions asked
└─ Time: ~2 minutes
```
**When to use**: You want a standard installation, don't need customization
---
### Option 2⃣ : **Advanced Settings**
```
Full customization with 19 configuration steps
├─ Best for: Power users, custom requirements
├─ What happens:
│ 1. Script asks for EVERY setting
│ 2. You control: CPU, RAM, Disk, Network, SSH, etc.
│ 3. Shows summary before creating
│ 4. Offers to save as App Defaults
└─ Time: ~5-10 minutes
```
**When to use**: You want full control over the configuration
**Available Settings**:
- CPU cores, RAM amount, Disk size
- Container name, network settings
- SSH access, API access, Features
- Password, SSH keys, Tags
---
### Option 3⃣ : **User Defaults**
```
Use your saved global defaults
├─ Best for: Consistent deployments across many containers
├─ Requires: You've previously saved User Defaults
├─ What happens:
│ 1. Loads settings from: /usr/local/community-scripts/default.vars
│ 2. Shows you the loaded settings
│ 3. Creates container immediately
└─ Time: ~2 minutes
```
**When to use**: You have preferred defaults you want to use for every app
---
### Option 4⃣ : **App Defaults** (if available)
```
Use previously saved app-specific defaults
├─ Best for: Repeating the same configuration multiple times
├─ Requires: You've previously saved App Defaults for this app
├─ What happens:
│ 1. Loads settings from: /usr/local/community-scripts/defaults/<app>.vars
│ 2. Shows you the loaded settings
│ 3. Creates container immediately
└─ Time: ~2 minutes
```
**When to use**: You've installed this app before and want identical settings
---
### Option 5⃣ : **Settings Menu**
```
Manage your saved configurations
├─ Functions:
│ • View current settings
│ • Edit storage selections
│ • Manage defaults location
│ • See what's currently configured
└─ Time: ~1 minute
```
**When to use**: You want to review or modify saved settings
---
## How to Save Defaults
### Method 1: Save While Installing
This is the easiest way:
#### Step-by-Step: Create App Defaults
```bash
# 1. Run the installation script
bash pihole-install.sh
# 2. Choose installation mode
# ┌─────────────────────────┐
# │ Select installation mode:│
# │ 1) Default Settings │
# │ 2) Advanced Settings │
# │ 3) User Defaults │
# │ 4) App Defaults │
# │ 5) Settings Menu │
# └─────────────────────────┘
#
# Enter: 2 (Advanced Settings)
# 3. Answer all configuration questions
# • Container name? → my-pihole
# • CPU cores? → 4
# • RAM amount? → 2048
# • Disk size? → 20
# • SSH access? → yes
# ... (more options)
# 4. Review summary (shown before creation)
# ✓ Confirm to proceed
# 5. After creation completes, you'll see:
# ┌──────────────────────────────────┐
# │ Save as App Defaults for PiHole? │
# │ (Yes/No) │
# └──────────────────────────────────┘
#
# Select: Yes
# 6. Done! Settings saved to:
# /usr/local/community-scripts/defaults/pihole.vars
```
#### Step-by-Step: Create User Defaults
```bash
# Same as App Defaults, but:
# When you select "Advanced Settings"
# FIRST app you run with this selection will offer
# to save as "User Defaults" additionally
# This saves to: /usr/local/community-scripts/default.vars
```
---
### Method 2: Manual File Creation
For advanced users who want to create defaults without running installation:
```bash
# Create User Defaults manually
sudo tee /usr/local/community-scripts/default.vars > /dev/null << 'EOF'
# Global User Defaults
var_cpu=4
var_ram=2048
var_disk=20
var_unprivileged=1
var_brg=vmbr0
var_gateway=192.168.1.1
var_timezone=Europe/Berlin
var_ssh=yes
var_container_storage=local
var_template_storage=local
EOF
# Create App Defaults manually
sudo tee /usr/local/community-scripts/defaults/pihole.vars > /dev/null << 'EOF'
# App-specific defaults for PiHole
var_unprivileged=1
var_cpu=2
var_ram=1024
var_disk=10
var_brg=vmbr0
var_gateway=192.168.1.1
var_hostname=pihole
var_container_storage=local
var_template_storage=local
EOF
```
---
### Method 3: Using Environment Variables
Set defaults via environment before running:
```bash
# Set as environment variables
export var_cpu=4
export var_ram=2048
export var_disk=20
export var_hostname=my-container
# Run installation
bash pihole-install.sh
# These settings will be used
# (Can still be overridden by saved defaults)
```
---
## How to Use Saved Defaults
### Using User Defaults
```bash
# 1. Run any installation script
bash pihole-install.sh
# 2. When asked for mode, select:
# Option: 3 (User Defaults)
# 3. Your settings from default.vars are applied
# 4. Container created with your saved settings
```
### Using App Defaults
```bash
# 1. Run the app you configured before
bash pihole-install.sh
# 2. When asked for mode, select:
# Option: 4 (App Defaults)
# 3. Your settings from defaults/pihole.vars are applied
# 4. Container created with exact same settings
```
### Overriding Saved Defaults
```bash
# Even if you have defaults saved,
# you can override them with environment variables
export var_cpu=8 # Override saved defaults
export var_hostname=custom-name
bash pihole-install.sh
# Installation will use these values instead of saved defaults
```
---
## Managing Your Defaults
### View Your Settings
#### View User Defaults
```bash
cat /usr/local/community-scripts/default.vars
```
#### View App Defaults
```bash
cat /usr/local/community-scripts/defaults/pihole.vars
```
#### List All Saved App Defaults
```bash
ls -la /usr/local/community-scripts/defaults/
```
### Edit Your Settings
#### Edit User Defaults
```bash
sudo nano /usr/local/community-scripts/default.vars
```
#### Edit App Defaults
```bash
sudo nano /usr/local/community-scripts/defaults/pihole.vars
```
### Update Existing Defaults
```bash
# Run installation again with your app
bash pihole-install.sh
# Select: Advanced Settings
# Make desired changes
# At end, when asked to save:
# "Defaults already exist, Update?"
# Select: Yes
# Your saved defaults are updated
```
### Delete Defaults
#### Delete User Defaults
```bash
sudo rm /usr/local/community-scripts/default.vars
```
#### Delete App Defaults
```bash
sudo rm /usr/local/community-scripts/defaults/pihole.vars
```
#### Delete All App Defaults
```bash
sudo rm /usr/local/community-scripts/defaults/*
```
---
## Advanced Configuration
### Available Variables
All configurable variables start with `var_`:
#### Resource Allocation
```bash
var_cpu=4 # CPU cores
var_ram=2048 # RAM in MB
var_disk=20 # Disk in GB
var_unprivileged=1 # 0=privileged, 1=unprivileged
```
#### Network
```bash
var_brg=vmbr0 # Bridge interface
var_net=veth # Network driver
var_gateway=192.168.1.1 # Default gateway
var_mtu=1500 # MTU size
var_vlan=100 # VLAN ID
```
#### System
```bash
var_hostname=pihole # Container name
var_timezone=Europe/Berlin # Timezone
var_pw=SecurePass123 # Root password
var_tags=dns,pihole # Tags for organization
var_verbose=yes # Enable verbose output
```
#### Security & Access
```bash
var_ssh=yes # Enable SSH
var_ssh_authorized_key="ssh-rsa AA..." # SSH public key
var_protection=1 # Enable protection flag
```
#### Features
```bash
var_fuse=1 # FUSE filesystem support
var_tun=1 # TUN device support
var_nesting=1 # Nesting (Docker in LXC)
var_keyctl=1 # Keyctl syscall
var_mknod=1 # Device node creation
```
#### Storage
```bash
var_container_storage=local # Where to store container
var_template_storage=local # Where to store templates
```
### Example Configuration Files
#### Gaming Server Defaults
```bash
# High performance for gaming containers
var_cpu=8
var_ram=4096
var_disk=50
var_unprivileged=0
var_fuse=1
var_nesting=1
var_tags=gaming
```
#### Development Server
```bash
# Development with Docker support
var_cpu=4
var_ram=2048
var_disk=30
var_unprivileged=1
var_nesting=1
var_ssh=yes
var_tags=development
```
#### IoT/Monitoring
```bash
# Low-resource, always-on containers
var_cpu=2
var_ram=512
var_disk=10
var_unprivileged=1
var_nesting=0
var_fuse=0
var_tun=0
var_tags=iot,monitoring
```
---
## Troubleshooting
### "App Defaults not available" Message
**Problem**: You want to use App Defaults, but option says they're not available
**Solution**:
1. You haven't created App Defaults yet for this app
2. Run the app with "Advanced Settings"
3. When finished, save as App Defaults
4. Next time, App Defaults will be available
---
### "Settings not being applied"
**Problem**: You saved defaults, but they're not being used
**Checklist**:
```bash
# 1. Verify files exist
ls -la /usr/local/community-scripts/default.vars
ls -la /usr/local/community-scripts/defaults/<app>.vars
# 2. Check file permissions (should be readable)
stat /usr/local/community-scripts/default.vars
# 3. Verify correct mode selected
# (Make sure you selected "User Defaults" or "App Defaults")
# 4. Check for environment variable override
env | grep var_
# If you have var_* set in environment,
# those override your saved defaults
```
---
### "Cannot write to defaults location"
**Problem**: Permission denied when saving defaults
**Solution**:
```bash
# Create the defaults directory if missing
sudo mkdir -p /usr/local/community-scripts/defaults
# Fix permissions
sudo chmod 755 /usr/local/community-scripts
sudo chmod 755 /usr/local/community-scripts/defaults
# Make sure you're running as root
sudo bash pihole-install.sh
```
---
### "Defaults directory doesn't exist"
**Problem**: Script can't find where to save defaults
**Solution**:
```bash
# Create the directory
sudo mkdir -p /usr/local/community-scripts/defaults
# Verify
ls -la /usr/local/community-scripts/
```
---
### Settings seem random or wrong
**Problem**: Container gets different settings than expected
**Possible Causes & Solutions**:
```bash
# 1. Check if environment variables are set
env | grep var_
# If you see var_* entries, those override your defaults
# Clear them: unset var_cpu var_ram (etc)
# 2. Verify correct defaults are in files
cat /usr/local/community-scripts/default.vars
cat /usr/local/community-scripts/defaults/pihole.vars
# 3. Check which mode you actually selected
# (Script output shows which defaults were applied)
# 4. Check Proxmox logs for errors
sudo journalctl -u pve-daemon -n 50
```
---
### "Variable not recognized"
**Problem**: You set a variable that doesn't work
**Solution**:
Only certain variables are allowed (security whitelist):
```
Allowed variables (starting with var_):
✓ var_cpu, var_ram, var_disk, var_unprivileged
✓ var_brg, var_gateway, var_mtu, var_vlan, var_net
✓ var_hostname, var_pw, var_timezone
✓ var_ssh, var_ssh_authorized_key
✓ var_fuse, var_tun, var_nesting, var_keyctl
✓ var_container_storage, var_template_storage
✓ var_tags, var_verbose
✓ var_apt_cacher, var_apt_cacher_ip
✓ var_protection, var_mount_fs
✗ Other variables are NOT supported
```
---
## Best Practices
### ✅ Do's
✓ Use **App Defaults** when you want app-specific settings
✓ Use **User Defaults** for your global preferences
✓ Edit defaults files directly with `nano` (safe)
✓ Keep separate App Defaults for each app
✓ Back up your defaults regularly
✓ Use environment variables for temporary overrides
### ❌ Don'ts
✗ Don't use `source` on defaults files (security risk)
✗ Don't put sensitive passwords in defaults (use SSH keys)
✗ Don't modify defaults while installation is running
✗ Don't delete defaults.d while containers are being created
✗ Don't use special characters without escaping
---
## Quick Reference
### Defaults Locations
| Type | Location | Example |
|------|----------|---------|
| User Defaults | `/usr/local/community-scripts/default.vars` | Global settings |
| App Defaults | `/usr/local/community-scripts/defaults/<app>.vars` | PiHole-specific |
| Backup Dir | `/usr/local/community-scripts/defaults/` | All app defaults |
### File Format
```bash
# Comments start with #
var_name=value
# No spaces around =
var_cpu=4
var_cpu = 4
# String values don't need quotes
var_hostname=mycontainer
var_hostname='mycontainer'
# Values with spaces need quotes
var_tags="docker,production,testing"
var_tags=docker,production,testing
```
### Command Reference
```bash
# View defaults
cat /usr/local/community-scripts/default.vars
# Edit defaults
sudo nano /usr/local/community-scripts/default.vars
# List all app defaults
ls /usr/local/community-scripts/defaults/
# Backup your defaults
cp -r /usr/local/community-scripts/defaults/ ~/defaults-backup/
# Set temporary override
export var_cpu=8
bash pihole-install.sh
# Create custom defaults
sudo tee /usr/local/community-scripts/defaults/custom.vars << 'EOF'
var_cpu=4
var_ram=2048
EOF
```
---
## Getting Help
### Need More Information?
- 📖 [Main Documentation](../../docs/)
- 🐛 [Report Issues](https://github.com/community-scripts/ProxmoxVE/issues)
- 💬 [Discussions](https://github.com/community-scripts/ProxmoxVE/discussions)
### Useful Commands
```bash
# Check what variables are available
grep "var_" /path/to/app-install.sh | head -20
# Verify defaults syntax
cat /usr/local/community-scripts/default.vars
# Monitor installation with defaults
bash pihole-install.sh 2>&1 | tee installation.log
```
---
## Document Information
| Field | Value |
|-------|-------|
| Version | 1.0 |
| Last Updated | November 28, 2025 |
| Status | Current |
| License | MIT |
---
**Happy configuring! 🚀**

58
docs/guides/README.md Normal file
View File

@ -0,0 +1,58 @@
# Configuration & Deployment Guides
This directory contains comprehensive guides for configuring and deploying Proxmox VE containers using community-scripts.
## 📚 Available Guides
### [Configuration Reference](CONFIGURATION_REFERENCE.md)
Complete reference for all configuration options, environment variables, and advanced settings available in the build system.
**Topics covered:**
- Container specifications (CPU, RAM, Disk)
- Network configuration (IPv4/IPv6, VLAN, MTU)
- Storage selection and management
- Privilege modes and features
- OS selection and versions
### [Defaults System Guide](DEFAULTS_SYSTEM_GUIDE.md)
Understanding and customizing default settings for container deployments.
**Topics covered:**
- Default system settings
- Per-script overrides
- Custom defaults configuration
- Environment variable precedence
### [Unattended Deployments](UNATTENDED_DEPLOYMENTS.md)
Automating container deployments without user interaction.
**Topics covered:**
- Environment variable configuration
- Batch deployments
- CI/CD integration
- Scripted installations
- Pre-configured templates
## 🔗 Related Documentation
- **[CT Scripts Guide](../ct/)** - Container script structure and usage
- **[Install Scripts Guide](../install/)** - Installation script internals
- **[API Documentation](../api/)** - API integration and endpoints
- **[Build Functions](../misc/build.func/)** - Build system functions reference
- **[Tools Functions](../misc/tools.func/)** - Utility functions reference
## 💡 Quick Start
For most users, start with the **Unattended Deployments** guide to learn how to automate your container setups.
For advanced configuration options, refer to the **Configuration Reference**.
## 🤝 Contributing
If you'd like to improve these guides or add new ones, please see our [Contribution Guide](../contribution/).

View File

@ -0,0 +1,963 @@
# Unattended Deployments Guide
Complete guide for automated, zero-interaction container deployments using community-scripts for Proxmox VE.
---
## 🎯 What You'll Learn
This comprehensive guide covers:
- ✅ Complete automation of container deployments
- ✅ Zero-interaction installations
- ✅ Batch deployments (multiple containers)
- ✅ Infrastructure as Code (Ansible, Terraform)
- ✅ CI/CD pipeline integration
- ✅ Error handling and rollback strategies
- ✅ Production-ready deployment scripts
- ✅ Security best practices
---
## Table of Contents
1. [Overview](#overview)
2. [Prerequisites](#prerequisites)
3. [Deployment Methods](#deployment-methods)
4. [Single Container Deployment](#single-container-deployment)
5. [Batch Deployments](#batch-deployments)
6. [Infrastructure as Code](#infrastructure-as-code)
7. [CI/CD Integration](#cicd-integration)
8. [Error Handling](#error-handling)
9. [Security Considerations](#security-considerations)
---
## Overview
Unattended deployments allow you to:
- ✅ Deploy containers without manual interaction
- ✅ Automate infrastructure provisioning
- ✅ Integrate with CI/CD pipelines
- ✅ Maintain consistent configurations
- ✅ Scale deployments across multiple nodes
---
## Prerequisites
### 1. Proxmox VE Access
```bash
# Verify you have root access
whoami # Should return: root
# Check Proxmox version (8.0+ or 9.0-9.1 required)
pveversion
```
### 2. Network Connectivity
```bash
# Test GitHub access
curl -I https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main/ct/debian.sh
# Test internet connectivity
ping -c 1 1.1.1.1
```
### 3. Storage Available
```bash
# List available storage
pvesm status
# Check free space
df -h
```
---
## Deployment Methods
### Method Comparison
| Method | Use Case | Complexity | Flexibility |
|--------|----------|------------|-------------|
| **Environment Variables** | Quick one-offs | Low | High |
| **App Defaults** | Repeat deployments | Low | Medium |
| **Shell Scripts** | Batch operations | Medium | High |
| **Ansible** | Infrastructure as Code | High | Very High |
| **Terraform** | Cloud-native IaC | High | Very High |
---
## Single Container Deployment
### Basic Unattended Deployment
**Simplest form:**
```bash
var_hostname=myserver bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/ct/debian.sh)"
```
### Complete Configuration Example
```bash
#!/bin/bash
# deploy-single.sh - Deploy a single container with full configuration
var_unprivileged=1 \
var_cpu=4 \
var_ram=4096 \
var_disk=30 \
var_hostname=production-app \
var_brg=vmbr0 \
var_net=dhcp \
var_ipv6_method=none \
var_ssh=yes \
var_ssh_authorized_key="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ... admin@workstation" \
var_nesting=1 \
var_tags=production,automated \
var_protection=yes \
var_verbose=no \
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main/ct/debian.sh)"
echo "✓ Container deployed successfully"
```
### Using App Defaults
**Step 1: Create defaults once (interactive)**
```bash
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main/ct/pihole.sh)"
# Select "Advanced Settings" → Configure → Save as "App Defaults"
```
**Step 2: Deploy unattended (uses saved defaults)**
```bash
#!/bin/bash
# deploy-with-defaults.sh
# App defaults are loaded automatically
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main/ct/pihole.sh)"
# Script will use /usr/local/community-scripts/defaults/pihole.vars
```
---
## Batch Deployments
### Deploy Multiple Containers
#### Simple Loop
```bash
#!/bin/bash
# batch-deploy-simple.sh
apps=("debian" "ubuntu" "alpine")
for app in "${apps[@]}"; do
echo "Deploying $app..."
var_hostname="$app-container" \
var_cpu=2 \
var_ram=2048 \
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main/ct/${app}.sh)"
echo "✓ $app deployed"
sleep 5 # Wait between deployments
done
```
#### Advanced with Configuration Array
```bash
#!/bin/bash
# batch-deploy-advanced.sh - Deploy multiple containers with individual configs
declare -A CONTAINERS=(
["pihole"]="2:1024:8:vmbr0:dns,network"
["homeassistant"]="4:4096:20:vmbr0:automation,ha"
["docker"]="6:8192:50:vmbr1:containers,docker"
["nginx"]="2:2048:10:vmbr0:webserver,proxy"
)
for app in "${!CONTAINERS[@]}"; do
# Parse configuration
IFS=':' read -r cpu ram disk bridge tags <<< "${CONTAINERS[$app]}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Deploying: $app"
echo " CPU: $cpu cores"
echo " RAM: $ram MB"
echo " Disk: $disk GB"
echo " Bridge: $bridge"
echo " Tags: $tags"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# Deploy container
var_unprivileged=1 \
var_cpu="$cpu" \
var_ram="$ram" \
var_disk="$disk" \
var_hostname="$app" \
var_brg="$bridge" \
var_net=dhcp \
var_ipv6_method=none \
var_ssh=yes \
var_tags="$tags,automated" \
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main/ct/${app}.sh)" 2>&1 | tee "deploy-${app}.log"
if [ $? -eq 0 ]; then
echo "✓ $app deployed successfully"
else
echo "✗ $app deployment failed - check deploy-${app}.log"
fi
sleep 5
done
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Batch deployment complete!"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
```
#### Parallel Deployment
```bash
#!/bin/bash
# parallel-deploy.sh - Deploy multiple containers in parallel
deploy_container() {
local app="$1"
local cpu="$2"
local ram="$3"
local disk="$4"
echo "[$app] Starting deployment..."
var_cpu="$cpu" \
var_ram="$ram" \
var_disk="$disk" \
var_hostname="$app" \
var_net=dhcp \
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main/ct/${app}.sh)" \
&> "deploy-${app}.log"
echo "[$app] ✓ Completed"
}
# Export function for parallel execution
export -f deploy_container
# Deploy in parallel (max 3 at a time)
parallel -j 3 deploy_container ::: \
"debian 2 2048 10" \
"ubuntu 2 2048 10" \
"alpine 1 1024 5" \
"pihole 2 1024 8" \
"docker 4 4096 30"
echo "All deployments complete!"
```
---
## Infrastructure as Code
### Ansible Playbook
#### Basic Playbook
```yaml
---
# playbook-proxmox.yml
- name: Deploy ProxmoxVED Containers
hosts: proxmox_hosts
become: yes
tasks:
- name: Deploy Debian Container
shell: |
var_unprivileged=1 \
var_cpu=2 \
var_ram=2048 \
var_disk=10 \
var_hostname=debian-{{ inventory_hostname }} \
var_net=dhcp \
var_ssh=yes \
var_tags=ansible,automated \
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main/ct/debian.sh)"
args:
executable: /bin/bash
register: deploy_result
- name: Display deployment result
debug:
var: deploy_result.stdout_lines
```
#### Advanced Playbook with Variables
```yaml
---
# advanced-playbook.yml
- name: Deploy Multiple Container Types
hosts: proxmox
vars:
containers:
- name: pihole
cpu: 2
ram: 1024
disk: 8
tags: "dns,network"
- name: homeassistant
cpu: 4
ram: 4096
disk: 20
tags: "automation,ha"
- name: docker
cpu: 6
ram: 8192
disk: 50
tags: "containers,docker"
ssh_key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"
tasks:
- name: Ensure community-scripts directory exists
file:
path: /usr/local/community-scripts/defaults
state: directory
mode: '0755'
- name: Deploy containers
shell: |
var_unprivileged=1 \
var_cpu={{ item.cpu }} \
var_ram={{ item.ram }} \
var_disk={{ item.disk }} \
var_hostname={{ item.name }} \
var_brg=vmbr0 \
var_net=dhcp \
var_ipv6_method=none \
var_ssh=yes \
var_ssh_authorized_key="{{ ssh_key }}" \
var_tags="{{ item.tags }},ansible" \
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main/ct/{{ item.name }}.sh)"
args:
executable: /bin/bash
loop: "{{ containers }}"
register: deployment_results
- name: Wait for containers to be ready
wait_for:
timeout: 60
- name: Report deployment status
debug:
msg: "Deployed {{ item.item.name }} - Status: {{ 'Success' if item.rc == 0 else 'Failed' }}"
loop: "{{ deployment_results.results }}"
```
Run with:
```bash
ansible-playbook -i inventory.ini advanced-playbook.yml
```
### Terraform Integration
```hcl
# main.tf - Deploy containers via Terraform
terraform {
required_providers {
proxmox = {
source = "telmate/proxmox"
version = "2.9.14"
}
}
}
provider "proxmox" {
pm_api_url = "https://proxmox.example.com:8006/api2/json"
pm_api_token_id = "terraform@pam!terraform"
pm_api_token_secret = var.proxmox_token
}
resource "null_resource" "deploy_container" {
for_each = var.containers
provisioner "remote-exec" {
inline = [
"var_unprivileged=1",
"var_cpu=${each.value.cpu}",
"var_ram=${each.value.ram}",
"var_disk=${each.value.disk}",
"var_hostname=${each.key}",
"var_net=dhcp",
"bash -c \"$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main/ct/${each.value.template}.sh)\""
]
connection {
type = "ssh"
host = var.proxmox_host
user = "root"
private_key = file("~/.ssh/id_rsa")
}
}
}
variable "containers" {
type = map(object({
template = string
cpu = number
ram = number
disk = number
}))
default = {
"pihole" = {
template = "pihole"
cpu = 2
ram = 1024
disk = 8
}
"homeassistant" = {
template = "homeassistant"
cpu = 4
ram = 4096
disk = 20
}
}
}
```
---
## CI/CD Integration
### GitHub Actions
```yaml
# .github/workflows/deploy-container.yml
name: Deploy Container to Proxmox
on:
push:
branches: [main]
workflow_dispatch:
inputs:
container_type:
description: 'Container type to deploy'
required: true
type: choice
options:
- debian
- ubuntu
- docker
- pihole
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Deploy to Proxmox
uses: appleboy/ssh-action@v0.1.10
with:
host: ${{ secrets.PROXMOX_HOST }}
username: root
key: ${{ secrets.SSH_PRIVATE_KEY }}
script: |
var_unprivileged=1 \
var_cpu=4 \
var_ram=4096 \
var_disk=30 \
var_hostname=${{ github.event.inputs.container_type }}-ci \
var_net=dhcp \
var_ssh=yes \
var_tags=ci-cd,automated \
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main/ct/${{ github.event.inputs.container_type }}.sh)"
- name: Notify deployment status
if: success()
run: echo "✓ Container deployed successfully"
```
### GitLab CI
```yaml
# .gitlab-ci.yml
stages:
- deploy
deploy_container:
stage: deploy
image: alpine:latest
before_script:
- apk add --no-cache openssh-client curl bash
- eval $(ssh-agent -s)
- echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
- ssh-keyscan $PROXMOX_HOST >> ~/.ssh/known_hosts
script:
- |
ssh root@$PROXMOX_HOST << 'EOF'
var_unprivileged=1 \
var_cpu=4 \
var_ram=4096 \
var_disk=30 \
var_hostname=gitlab-ci-container \
var_net=dhcp \
var_tags=gitlab-ci,automated \
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main/ct/debian.sh)"
EOF
only:
- main
when: manual
```
---
## Error Handling
### Deployment Verification Script
```bash
#!/bin/bash
# deploy-with-verification.sh
APP="debian"
HOSTNAME="production-server"
MAX_RETRIES=3
RETRY_COUNT=0
deploy_container() {
echo "Attempting deployment (Try $((RETRY_COUNT + 1))/$MAX_RETRIES)..."
var_unprivileged=1 \
var_cpu=4 \
var_ram=4096 \
var_disk=30 \
var_hostname="$HOSTNAME" \
var_net=dhcp \
var_ssh=yes \
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main/ct/${APP}.sh)" 2>&1 | tee deploy.log
return ${PIPESTATUS[0]}
}
verify_deployment() {
echo "Verifying deployment..."
# Check if container exists
if ! pct list | grep -q "$HOSTNAME"; then
echo "✗ Container not found in pct list"
return 1
fi
# Check if container is running
CTID=$(pct list | grep "$HOSTNAME" | awk '{print $1}')
STATUS=$(pct status "$CTID" | awk '{print $2}')
if [ "$STATUS" != "running" ]; then
echo "✗ Container not running (Status: $STATUS)"
return 1
fi
# Check network connectivity
if ! pct exec "$CTID" -- ping -c 1 1.1.1.1 &>/dev/null; then
echo "⚠ Warning: No internet connectivity"
fi
echo "✓ Deployment verified successfully"
echo " Container ID: $CTID"
echo " Status: $STATUS"
echo " IP: $(pct exec "$CTID" -- hostname -I)"
return 0
}
# Main deployment loop with retry
while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
if deploy_container; then
if verify_deployment; then
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✓ Deployment successful!"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
exit 0
else
echo "✗ Deployment verification failed"
fi
else
echo "✗ Deployment failed"
fi
RETRY_COUNT=$((RETRY_COUNT + 1))
if [ $RETRY_COUNT -lt $MAX_RETRIES ]; then
echo "Retrying in 10 seconds..."
sleep 10
fi
done
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✗ Deployment failed after $MAX_RETRIES attempts"
echo "Check deploy.log for details"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
exit 1
```
### Rollback on Failure
```bash
#!/bin/bash
# deploy-with-rollback.sh
APP="debian"
HOSTNAME="test-server"
SNAPSHOT_NAME="pre-deployment"
# Take snapshot of existing container (if exists)
backup_existing() {
EXISTING_CTID=$(pct list | grep "$HOSTNAME" | awk '{print $1}')
if [ -n "$EXISTING_CTID" ]; then
echo "Creating snapshot of existing container..."
pct snapshot "$EXISTING_CTID" "$SNAPSHOT_NAME" --description "Pre-deployment backup"
return 0
fi
return 1
}
# Deploy new container
deploy() {
var_hostname="$HOSTNAME" \
var_cpu=4 \
var_ram=4096 \
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main/ct/${APP}.sh)"
return $?
}
# Rollback to snapshot
rollback() {
local ctid="$1"
echo "Rolling back to snapshot..."
pct rollback "$ctid" "$SNAPSHOT_NAME"
pct delsnapshot "$ctid" "$SNAPSHOT_NAME"
}
# Main execution
backup_existing
HAD_BACKUP=$?
if deploy; then
echo "✓ Deployment successful"
[ $HAD_BACKUP -eq 0 ] && echo "You can remove the snapshot with: pct delsnapshot <CTID> $SNAPSHOT_NAME"
else
echo "✗ Deployment failed"
if [ $HAD_BACKUP -eq 0 ]; then
read -p "Rollback to previous version? (y/N) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
rollback "$EXISTING_CTID"
echo "✓ Rolled back successfully"
fi
fi
exit 1
fi
```
---
## Security Considerations
### Secure Deployment Script
```bash
#!/bin/bash
# secure-deploy.sh - Production-ready secure deployment
set -euo pipefail # Exit on error, undefined vars, pipe failures
# Configuration
readonly APP="debian"
readonly HOSTNAME="secure-server"
readonly SSH_KEY_PATH="/root/.ssh/id_rsa.pub"
readonly LOG_FILE="/var/log/container-deployments.log"
# Logging function
log() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_FILE"
}
# Validate prerequisites
validate_environment() {
log "Validating environment..."
# Check if running as root
if [ "$EUID" -ne 0 ]; then
log "ERROR: Must run as root"
exit 1
fi
# Check SSH key exists
if [ ! -f "$SSH_KEY_PATH" ]; then
log "ERROR: SSH key not found at $SSH_KEY_PATH"
exit 1
fi
# Check internet connectivity
if ! curl -s --max-time 5 https://github.com &>/dev/null; then
log "ERROR: No internet connectivity"
exit 1
fi
log "✓ Environment validated"
}
# Secure deployment
deploy_secure() {
log "Starting secure deployment for $HOSTNAME..."
SSH_KEY=$(cat "$SSH_KEY_PATH")
var_unprivileged=1 \
var_cpu=4 \
var_ram=4096 \
var_disk=30 \
var_hostname="$HOSTNAME" \
var_brg=vmbr0 \
var_net=dhcp \
var_ipv6_method=disable \
var_ssh=yes \
var_ssh_authorized_key="$SSH_KEY" \
var_nesting=0 \
var_keyctl=0 \
var_fuse=0 \
var_protection=yes \
var_tags=production,secure,automated \
var_verbose=no \
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main/ct/${APP}.sh)" 2>&1 | tee -a "$LOG_FILE"
if [ ${PIPESTATUS[0]} -eq 0 ]; then
log "✓ Deployment successful"
return 0
else
log "✗ Deployment failed"
return 1
fi
}
# Main execution
main() {
validate_environment
if deploy_secure; then
log "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log "Secure deployment completed successfully"
log "Container: $HOSTNAME"
log "Features: Unprivileged, SSH-only, Protected"
log "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
exit 0
else
log "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log "Deployment failed - check logs at $LOG_FILE"
log "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
exit 1
fi
}
main "$@"
```
### SSH Key Management
```bash
#!/bin/bash
# deploy-with-ssh-keys.sh - Secure SSH key deployment
# Load SSH keys from multiple sources
load_ssh_keys() {
local keys=()
# Personal key
if [ -f ~/.ssh/id_rsa.pub ]; then
keys+=("$(cat ~/.ssh/id_rsa.pub)")
fi
# Team keys
if [ -f /etc/ssh/authorized_keys.d/team ]; then
while IFS= read -r key; do
[ -n "$key" ] && keys+=("$key")
done < /etc/ssh/authorized_keys.d/team
fi
# Join keys with newline
printf "%s\n" "${keys[@]}"
}
# Deploy with multiple SSH keys
SSH_KEYS=$(load_ssh_keys)
var_ssh=yes \
var_ssh_authorized_key="$SSH_KEYS" \
var_hostname=multi-key-server \
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main/ct/debian.sh)"
```
---
## Complete Production Example
```bash
#!/bin/bash
# production-deploy.sh - Complete production deployment system
set -euo pipefail
#━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Configuration
#━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly LOG_DIR="/var/log/proxmox-deployments"
readonly CONFIG_FILE="$SCRIPT_DIR/deployment-config.json"
#━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Functions
#━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
setup_logging() {
mkdir -p "$LOG_DIR"
exec 1> >(tee -a "$LOG_DIR/deployment-$(date +%Y%m%d-%H%M%S).log")
exec 2>&1
}
log_info() { echo "[INFO] $(date +'%H:%M:%S') - $*"; }
log_error() { echo "[ERROR] $(date +'%H:%M:%S') - $*" >&2; }
log_success() { echo "[SUCCESS] $(date +'%H:%M:%S') - $*"; }
validate_prerequisites() {
log_info "Validating prerequisites..."
[ "$EUID" -eq 0 ] || { log_error "Must run as root"; exit 1; }
command -v jq >/dev/null 2>&1 || { log_error "jq not installed"; exit 1; }
command -v curl >/dev/null 2>&1 || { log_error "curl not installed"; exit 1; }
log_success "Prerequisites validated"
}
deploy_from_config() {
local config_file="$1"
if [ ! -f "$config_file" ]; then
log_error "Config file not found: $config_file"
return 1
fi
local container_count
container_count=$(jq '.containers | length' "$config_file")
log_info "Deploying $container_count containers from config..."
for i in $(seq 0 $((container_count - 1))); do
local name cpu ram disk app tags
name=$(jq -r ".containers[$i].name" "$config_file")
cpu=$(jq -r ".containers[$i].cpu" "$config_file")
ram=$(jq -r ".containers[$i].ram" "$config_file")
disk=$(jq -r ".containers[$i].disk" "$config_file")
app=$(jq -r ".containers[$i].app" "$config_file")
tags=$(jq -r ".containers[$i].tags" "$config_file")
log_info "Deploying container: $name ($app)"
var_unprivileged=1 \
var_cpu="$cpu" \
var_ram="$ram" \
var_disk="$disk" \
var_hostname="$name" \
var_net=dhcp \
var_ssh=yes \
var_tags="$tags,automated" \
var_protection=yes \
bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main/ct/${app}.sh)"
if [ $? -eq 0 ]; then
log_success "Deployed: $name"
else
log_error "Failed to deploy: $name"
fi
sleep 5
done
}
generate_report() {
log_info "Generating deployment report..."
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "DEPLOYMENT REPORT"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Time: $(date)"
echo ""
pct list
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
}
#━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Main
#━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
main() {
setup_logging
log_info "Starting production deployment system"
validate_prerequisites
deploy_from_config "$CONFIG_FILE"
generate_report
log_success "Production deployment complete"
}
main "$@"
```
**Example config file (deployment-config.json):**
```json
{
"containers": [
{
"name": "pihole",
"app": "pihole",
"cpu": 2,
"ram": 1024,
"disk": 8,
"tags": "dns,network,production"
},
{
"name": "homeassistant",
"app": "homeassistant",
"cpu": 4,
"ram": 4096,
"disk": 20,
"tags": "automation,ha,production"
},
{
"name": "docker-host",
"app": "docker",
"cpu": 8,
"ram": 16384,
"disk": 100,
"tags": "containers,docker,production"
}
]
}
```
---
## See Also
- [Defaults System Guide](DEFAULTS_GUIDE.md)
- [Configuration Reference](CONFIGURATION_REFERENCE.md)
- [Security Best Practices](SECURITY_GUIDE.md)
- [Network Configuration](NETWORK_GUIDE.md)

View File

@ -0,0 +1,646 @@
# 🛠️ **Application Installation Scripts (install/AppName-install.sh)**
**Modern Guide to Writing In-Container Installation Scripts**
> **Updated**: December 2025
> **Context**: Integrated with tools.func, error_handler.func, and install.func
> **Examples Used**: `/install/pihole-install.sh`, `/install/mealie-install.sh`
---
## 📋 Table of Contents
- [Overview](#overview)
- [Execution Context](#execution-context)
- [File Structure](#file-structure)
- [Complete Script Template](#complete-script-template)
- [Installation Phases](#installation-phases)
- [Function Reference](#function-reference)
- [Best Practices](#best-practices)
- [Real Examples](#real-examples)
- [Troubleshooting](#troubleshooting)
- [Contribution Checklist](#contribution-checklist)
---
## Overview
### Purpose
Installation scripts (`install/AppName-install.sh`) **run inside the LXC container** and are responsible for:
1. Setting up the container OS (updates, packages)
2. Installing application dependencies
3. Downloading and configuring the application
4. Setting up services and systemd units
5. Creating version tracking files for updates
6. Generating credentials/configurations
7. Final cleanup and validation
### Execution Flow
```
ct/AppName.sh (Proxmox Host)
build_container()
pct exec CTID bash -c "$(cat install/AppName-install.sh)"
install/AppName-install.sh (Inside Container)
Container Ready with App Installed
```
---
## Execution Context
### Environment Variables Available
```bash
# From Proxmox/Container
CTID # Container ID (100, 101, etc.)
PCT_OSTYPE # OS type (alpine, debian, ubuntu)
HOSTNAME # Container hostname
# From build.func
FUNCTIONS_FILE_PATH # Bash functions library (core.func + tools.func)
VERBOSE # Verbose mode (yes/no)
STD # Standard redirection variable (silent/empty)
# From install.func
APP # Application name
NSAPP # Normalized app name (lowercase, no spaces)
METHOD # Installation method (ct/install)
RANDOM_UUID # Session UUID for telemetry
```
---
## File Structure
### Minimal install/AppName-install.sh Template
```bash
#!/usr/bin/env bash # [1] Shebang
# [2] Copyright/Metadata
# Copyright (c) 2021-2025 community-scripts ORG
# Author: YourUsername
# License: MIT
# Source: https://example.com
# [3] Load functions
source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
color
verb_ip6
catch_errors
setting_up_container
network_check
update_os
# [4] Installation steps
msg_info "Installing Dependencies"
$STD apt-get install -y package1 package2
msg_ok "Installed Dependencies"
# [5] Final setup
motd_ssh
customize
cleanup_lxc
```
---
## Complete Script Template
### Phase 1: Header & Initialization
```bash
#!/usr/bin/env bash
# Copyright (c) 2021-2025 community-scripts ORG
# Author: YourUsername
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE
# Source: https://github.com/application/repo
# Load all available functions (from core.func + tools.func)
source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
# Initialize environment
color # Setup ANSI colors and icons
verb_ip6 # Configure IPv6 (if needed)
catch_errors # Setup error traps
setting_up_container # Verify OS is ready
network_check # Verify internet connectivity
update_os # Update packages (apk/apt)
```
### Phase 2: Dependency Installation
```bash
msg_info "Installing Dependencies"
$STD apt-get install -y \
curl \
wget \
git \
nano \
build-essential \
libssl-dev \
python3-dev
msg_ok "Installed Dependencies"
```
### Phase 3: Tool Setup (Using tools.func)
```bash
# Setup specific tool versions
NODE_VERSION="22" setup_nodejs
PHP_VERSION="8.4" setup_php
PYTHON_VERSION="3.12" setup_uv
```
### Phase 4: Application Download & Setup
```bash
# Download from GitHub
RELEASE=$(curl -fsSL https://api.github.com/repos/user/repo/releases/latest | \
grep "tag_name" | awk '{print substr($2, 2, length($2)-3)}')
wget -q "https://github.com/user/repo/releases/download/v${RELEASE}/app-${RELEASE}.tar.gz"
cd /opt
tar -xzf app-${RELEASE}.tar.gz
rm -f app-${RELEASE}.tar.gz
```
### Phase 5: Configuration Files
```bash
# Using cat << EOF (multiline)
cat <<'EOF' >/etc/nginx/sites-available/appname
server {
listen 80;
server_name _;
root /opt/appname/public;
index index.php index.html;
}
EOF
# Using sed for replacements
sed -i -e "s|^DB_HOST=.*|DB_HOST=localhost|" \
-e "s|^DB_USER=.*|DB_USER=appuser|" \
/opt/appname/.env
```
### Phase 6: Database Setup (If Needed)
```bash
msg_info "Setting up Database"
DB_NAME="appname_db"
DB_USER="appuser"
DB_PASS=$(openssl rand -base64 18 | tr -dc 'a-zA-Z0-9' | head -c13)
# For MySQL/MariaDB
mysql -u root <<EOF
CREATE DATABASE ${DB_NAME};
CREATE USER '${DB_USER}'@'localhost' IDENTIFIED BY '${DB_PASS}';
GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'localhost';
FLUSH PRIVILEGES;
EOF
msg_ok "Database setup complete"
```
### Phase 7: Permission & Ownership
```bash
msg_info "Setting permissions"
# Web applications typically run as www-data
chown -R www-data:www-data /opt/appname
chmod -R 755 /opt/appname
chmod -R 644 /opt/appname/*
chmod 755 /opt/appname/*/.*
msg_ok "Permissions set"
```
### Phase 8: Service Configuration
```bash
# Enable systemd service
systemctl enable -q --now appname
# Or for OpenRC (Alpine)
rc-service appname start
rc-update add appname default
# Verify service is running
if systemctl is-active --quiet appname; then
msg_ok "Service running successfully"
else
msg_error "Service failed to start"
journalctl -u appname -n 20
exit 1
fi
```
### Phase 9: Version Tracking
```bash
# Essential for update detection
echo "${RELEASE}" > /opt/${APP}_version.txt
# Or with additional metadata
cat > /opt/${APP}_version.txt <<EOF
Version: ${RELEASE}
InstallDate: $(date)
InstallMethod: ${METHOD}
EOF
```
### Phase 10: Final Setup & Cleanup
```bash
# Display MOTD and enable autologin
motd_ssh
# Final customization
customize
# Clean up package manager cache
msg_info "Cleaning up"
apt-get -y autoremove
apt-get -y autoclean
msg_ok "Cleaned"
# Or for Alpine
apk cache clean
rm -rf /var/cache/apk/*
# System cleanup
cleanup_lxc
```
---
## Installation Phases
### Phase 1: Container OS Setup
- Network interface brought up and configured
- Internet connectivity verified
- Package lists updated
- All OS packages upgraded to latest versions
### Phase 2: Base Dependencies
```bash
msg_info "Installing Base Dependencies"
$STD apt-get install -y \
curl wget git nano build-essential
msg_ok "Installed Base Dependencies"
```
### Phase 3: Tool Installation
```bash
NODE_VERSION="22" setup_nodejs
PHP_VERSION="8.4" setup_php
```
### Phase 4: Application Setup
```bash
RELEASE=$(curl -fsSL https://api.github.com/repos/user/repo/releases/latest | \
grep "tag_name" | awk '{print substr($2, 2, length($2)-3)}')
wget -q "https://github.com/user/repo/releases/download/v${RELEASE}/app.tar.gz"
```
### Phase 5: Configuration
Application-specific configuration files and environment setup
### Phase 6: Service Registration
Enable and verify systemd services are running
---
## Function Reference
### Core Messaging Functions
#### `msg_info(message)`
Displays an info message with spinner animation
```bash
msg_info "Installing application"
# Output: ⏳ Installing application (with spinning animation)
```
#### `msg_ok(message)`
Displays success message with checkmark
```bash
msg_ok "Installation completed"
# Output: ✔️ Installation completed
```
#### `msg_error(message)`
Displays error message and exits
```bash
msg_error "Installation failed"
# Output: ✖️ Installation failed
```
### Package Management
#### `$STD` Variable
Controls output verbosity
```bash
# Silent mode (respects VERBOSE setting)
$STD apt-get install -y nginx
```
#### `update_os()`
Updates OS packages
```bash
update_os
# Runs: apt update && apt upgrade
```
### Tool Installation Functions
#### `setup_nodejs()`
Installs Node.js with optional global modules
```bash
NODE_VERSION="22" setup_nodejs
NODE_VERSION="22" NODE_MODULE="yarn,@vue/cli" setup_nodejs
```
#### `setup_php()`
Installs PHP with optional extensions
```bash
PHP_VERSION="8.4" PHP_MODULE="bcmath,curl,gd,intl,redis" setup_php
```
#### Other Tools
```bash
setup_mariadb # MariaDB database
setup_mysql # MySQL database
setup_postgresql # PostgreSQL
setup_docker # Docker Engine
setup_composer # PHP Composer
setup_python # Python 3
setup_ruby # Ruby
setup_rust # Rust
```
### Cleanup Functions
#### `cleanup_lxc()`
Comprehensive container cleanup
- Removes package manager caches
- Cleans temporary files
- Clears language package caches
- Removes systemd journal logs
```bash
cleanup_lxc
# Output: ⏳ Cleaning up
# ✔️ Cleaned
```
---
## Best Practices
### ✅ DO:
1. **Always Use $STD for Commands**
```bash
# ✅ Good: Respects VERBOSE setting
$STD apt-get install -y nginx
```
2. **Generate Random Passwords Safely**
```bash
# ✅ Good: Alphanumeric only
DB_PASS=$(openssl rand -base64 18 | tr -dc 'a-zA-Z0-9' | head -c13)
```
3. **Check Command Success**
```bash
# ✅ Good: Verify success
if ! wget -q "https://example.com/file.tar.gz"; then
msg_error "Download failed"
exit 1
fi
```
4. **Set Proper Permissions**
```bash
# ✅ Good: Explicit permissions
chown -R www-data:www-data /opt/appname
chmod -R 755 /opt/appname
```
5. **Save Version for Update Checks**
```bash
# ✅ Good: Version tracked
echo "${RELEASE}" > /opt/${APP}_version.txt
```
6. **Handle Alpine vs Debian Differences**
```bash
# ✅ Good: Detect OS
if grep -qi 'alpine' /etc/os-release; then
apk add package
else
apt-get install -y package
fi
```
### ❌ DON'T:
1. **Hardcode Versions**
```bash
# ❌ Bad: Won't auto-update
wget https://example.com/app-1.2.3.tar.gz
```
2. **Use Root Without Password**
```bash
# ❌ Bad: Security risk
mysql -u root
```
3. **Forget Error Handling**
```bash
# ❌ Bad: Silent failures
wget https://example.com/file
tar -xzf file
```
4. **Leave Temporary Files**
```bash
# ✅ Always cleanup
rm -rf /opt/app-${RELEASE}.tar.gz
```
---
## Real Examples
### Example 1: Node.js Application
```bash
#!/usr/bin/env bash
source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
color
catch_errors
setting_up_container
network_check
update_os
msg_info "Installing Node.js"
NODE_VERSION="22" setup_nodejs
msg_ok "Node.js installed"
msg_info "Installing Application"
cd /opt
RELEASE=$(curl -fsSL https://api.github.com/repos/user/repo/releases/latest | \
grep "tag_name" | awk '{print substr($2, 2, length($2)-3)}')
wget -q "https://github.com/user/repo/releases/download/v${RELEASE}/app.tar.gz"
tar -xzf app.tar.gz
echo "${RELEASE}" > /opt/app_version.txt
msg_ok "Application installed"
systemctl enable --now app
cleanup_lxc
```
### Example 2: PHP Application with Database
```bash
#!/usr/bin/env bash
source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
color
catch_errors
setting_up_container
network_check
update_os
PHP_VERSION="8.4" PHP_MODULE="bcmath,curl,pdo_mysql" setup_php
MARIADB_VERSION="11.4" setup_mariadb
# Database setup
DB_PASS=$(openssl rand -base64 18 | tr -dc 'a-zA-Z0-9' | head -c13)
mysql -u root <<EOF
CREATE DATABASE appdb;
CREATE USER 'appuser'@'localhost' IDENTIFIED BY '${DB_PASS}';
GRANT ALL ON appdb.* TO 'appuser'@'localhost';
FLUSH PRIVILEGES;
EOF
# App installation
cd /opt
wget -q https://github.com/user/repo/releases/latest/download/app.tar.gz
tar -xzf app.tar.gz
# Configuration
cat > /opt/app/.env <<EOF
DB_HOST=localhost
DB_NAME=appdb
DB_USER=appuser
DB_PASS=${DB_PASS}
EOF
chown -R www-data:www-data /opt/app
systemctl enable --now php-fpm
cleanup_lxc
```
---
## Troubleshooting
### Installation Hangs
**Check internet connectivity**:
```bash
ping -c 1 8.8.8.8
```
**Enable verbose mode**:
```bash
# In ct/AppName.sh, before running
VERBOSE="yes" bash install/AppName-install.sh
```
### Package Not Found
**Update package lists**:
```bash
apt update
apt-cache search package_name
```
### Service Won't Start
**Check logs**:
```bash
journalctl -u appname -n 50
systemctl status appname
```
---
## Contribution Checklist
Before submitting a PR:
### Structure
- [ ] Shebang is `#!/usr/bin/env bash`
- [ ] Loads functions from `$FUNCTIONS_FILE_PATH`
- [ ] Copyright header with author
- [ ] Clear phase comments
### Installation
- [ ] `setting_up_container` called early
- [ ] `network_check` before downloads
- [ ] `update_os` before package installation
- [ ] All errors checked properly
### Functions
- [ ] Uses `msg_info/msg_ok/msg_error` for status
- [ ] Uses `$STD` for command output silencing
- [ ] Version saved to `/opt/${APP}_version.txt`
- [ ] Proper permissions set
### Cleanup
- [ ] `motd_ssh` called for final setup
- [ ] `customize` called for options
- [ ] `cleanup_lxc` called at end
### Testing
- [ ] Tested with default settings
- [ ] Tested with advanced (19-step) mode
- [ ] Service starts and runs correctly
---
**Last Updated**: December 2025
**Compatibility**: ProxmoxVE with install.func v3+

159
docs/install/README.md Normal file
View File

@ -0,0 +1,159 @@
# Installation Scripts Documentation (/install)
This directory contains comprehensive documentation for installation scripts in the `/install` directory.
## Overview
Installation scripts (`install/*.sh`) run inside LXC containers and handle application-specific setup, configuration, and deployment.
## Documentation Structure
Each installation script category has documentation following the project pattern.
## Key Resources
- **[DETAILED_GUIDE.md](DETAILED_GUIDE.md)** - Complete reference for creating install scripts
- **[../contribution/README.md](../contribution/README.md)** - How to contribute
- **[../misc/install.func/](../misc/install.func/)** - Installation workflow documentation
- **[../misc/tools.func/](../misc/tools.func/)** - Package installation documentation
## Installation Script Flow
```
install/appname-install.sh (container-side)
├─ Sources: $FUNCTIONS_FILE_PATH
│ ├─ core.func (messaging)
│ ├─ error_handler.func (error handling)
│ ├─ install.func (setup)
│ └─ tools.func (packages & tools)
├─ 10-Phase Installation:
│ 1. OS Setup
│ 2. Base Dependencies
│ 3. Tool Setup
│ 4. Application Download
│ 5. Configuration
│ 6. Database Setup
│ 7. Permissions
│ 8. Services
│ 9. Version Tracking
│ 10. Final Cleanup
└─ Result: Application ready
```
## Available Installation Scripts
See `/install` directory for all installation scripts. Examples:
- `pihole-install.sh` - Pi-hole installation
- `docker-install.sh` - Docker installation
- `wallabag-install.sh` - Wallabag setup
- `nextcloud-install.sh` - Nextcloud deployment
- `debian-install.sh` - Base Debian setup
- And 30+ more...
## Quick Start
To understand how to create an installation script:
1. Read: [UPDATED_APP-install.md](../UPDATED_APP-install.md)
2. Study: A similar existing script in `/install`
3. Copy template and customize
4. Test in container
5. Submit PR
## 10-Phase Installation Pattern
Every installation script follows this structure:
### Phase 1: OS Setup
```bash
setting_up_container
network_check
update_os
```
### Phase 2: Base Dependencies
```bash
pkg_update
pkg_install curl wget git
```
### Phase 3: Tool Setup
```bash
setup_nodejs "20"
setup_php "8.3"
setup_mariadb "11"
```
### Phase 4: Application Download
```bash
git clone https://github.com/user/app /opt/app
cd /opt/app
```
### Phase 5: Configuration
```bash
# Create .env files, config files, etc.
cat > .env <<EOF
SETTING=value
EOF
```
### Phase 6: Database Setup
```bash
# Create databases, users, etc.
mysql -e "CREATE DATABASE appdb"
```
### Phase 7: Permissions
```bash
chown -R appuser:appgroup /opt/app
chmod -R 755 /opt/app
```
### Phase 8: Services
```bash
systemctl enable app
systemctl start app
```
### Phase 9: Version Tracking
```bash
echo "1.0.0" > /opt/app_version.txt
```
### Phase 10: Final Cleanup
```bash
motd_ssh
customize
cleanup_lxc
```
## Contributing an Installation Script
1. Create `ct/myapp.sh` (host script)
2. Create `install/myapp-install.sh` (container script)
3. Follow 10-phase pattern in [UPDATED_APP-install.md](../UPDATED_APP-install.md)
4. Test in actual container
5. Submit PR with both files
## Common Tasks
- **Create new installation script** → [UPDATED_APP-install.md](../UPDATED_APP-install.md)
- **Install Node.js/PHP/Database** → [misc/tools.func/](../misc/tools.func/)
- **Setup Alpine container** → [misc/alpine-install.func/](../misc/alpine-install.func/)
- **Debug installation errors** → [EXIT_CODES.md](../EXIT_CODES.md)
- **Use dev mode** → [DEV_MODE.md](../DEV_MODE.md)
## Alpine vs Debian
- **Debian-based** → Use `tools.func`, `install.func`, `systemctl`
- **Alpine-based** → Use `alpine-tools.func`, `alpine-install.func`, `rc-service`
---
**Last Updated**: December 2025
**Maintainers**: community-scripts team

283
docs/misc/README.md Normal file
View File

@ -0,0 +1,283 @@
# Misc Documentation
This directory contains comprehensive documentation for all function libraries and components of the Proxmox Community Scripts project. Each section is organized as a dedicated subdirectory with detailed references, examples, and integration guides.
---
## 🏗️ **Core Function Libraries**
### 📁 [build.func/](./build.func/)
**Core LXC Container Orchestration** - Main orchestrator for Proxmox LXC container creation
**Contents:**
- BUILD_FUNC_FLOWCHART.md - Visual execution flows and decision trees
- BUILD_FUNC_ARCHITECTURE.md - System architecture and design
- BUILD_FUNC_ENVIRONMENT_VARIABLES.md - Complete environment variable reference
- BUILD_FUNC_FUNCTIONS_REFERENCE.md - Alphabetical function reference
- BUILD_FUNC_EXECUTION_FLOWS.md - Detailed execution flows
- BUILD_FUNC_USAGE_EXAMPLES.md - Practical usage examples
- README.md - Overview and quick reference
**Key Functions**: `variables()`, `start()`, `build_container()`, `build_defaults()`, `advanced_settings()`
---
### 📁 [core.func/](./core.func/)
**System Utilities & Foundation** - Essential utility functions and system checks
**Contents:**
- CORE_FLOWCHART.md - Visual execution flows
- CORE_FUNCTIONS_REFERENCE.md - Complete function reference
- CORE_INTEGRATION.md - Integration points
- CORE_USAGE_EXAMPLES.md - Practical examples
- README.md - Overview and quick reference
**Key Functions**: `color()`, `msg_info()`, `msg_ok()`, `msg_error()`, `root_check()`, `pve_check()`, `parse_dev_mode()`
---
### 📁 [error_handler.func/](./error_handler.func/)
**Error Handling & Signal Management** - Comprehensive error handling and signal trapping
**Contents:**
- ERROR_HANDLER_FLOWCHART.md - Visual error handling flows
- ERROR_HANDLER_FUNCTIONS_REFERENCE.md - Function reference
- ERROR_HANDLER_INTEGRATION.md - Integration with other components
- ERROR_HANDLER_USAGE_EXAMPLES.md - Practical examples
- README.md - Overview and quick reference
**Key Functions**: `catch_errors()`, `error_handler()`, `explain_exit_code()`, `signal_handler()`
---
### 📁 [api.func/](./api.func/)
**Proxmox API Integration** - API communication and diagnostic reporting
**Contents:**
- API_FLOWCHART.md - API communication flows
- API_FUNCTIONS_REFERENCE.md - Function reference
- API_INTEGRATION.md - Integration points
- API_USAGE_EXAMPLES.md - Practical examples
- README.md - Overview and quick reference
**Key Functions**: `post_to_api()`, `post_update_to_api()`, `get_error_description()`
---
## 📦 **Installation & Setup Function Libraries**
### 📁 [install.func/](./install.func/)
**Container Installation Workflow** - Installation orchestration for container-internal setup
**Contents:**
- INSTALL_FUNC_FLOWCHART.md - Installation workflow diagrams
- INSTALL_FUNC_FUNCTIONS_REFERENCE.md - Complete function reference
- INSTALL_FUNC_INTEGRATION.md - Integration with build and tools
- INSTALL_FUNC_USAGE_EXAMPLES.md - Practical examples
- README.md - Overview and quick reference
**Key Functions**: `setting_up_container()`, `network_check()`, `update_os()`, `motd_ssh()`, `cleanup_lxc()`
---
### 📁 [tools.func/](./tools.func/)
**Package & Tool Installation** - Robust package management and 30+ tool installation functions
**Contents:**
- TOOLS_FUNC_FLOWCHART.md - Package management flows
- TOOLS_FUNC_FUNCTIONS_REFERENCE.md - 30+ function reference
- TOOLS_FUNC_INTEGRATION.md - Integration with install workflows
- TOOLS_FUNC_USAGE_EXAMPLES.md - Practical examples
- TOOLS_FUNC_ENVIRONMENT_VARIABLES.md - Configuration reference
- README.md - Overview and quick reference
**Key Functions**: `setup_nodejs()`, `setup_php()`, `setup_mariadb()`, `setup_docker()`, `setup_deb822_repo()`, `pkg_install()`, `pkg_update()`
---
### 📁 [alpine-install.func/](./alpine-install.func/)
**Alpine Container Setup** - Alpine Linux-specific installation functions
**Contents:**
- ALPINE_INSTALL_FUNC_FLOWCHART.md - Alpine setup flows
- ALPINE_INSTALL_FUNC_FUNCTIONS_REFERENCE.md - Function reference
- ALPINE_INSTALL_FUNC_INTEGRATION.md - Integration points
- ALPINE_INSTALL_FUNC_USAGE_EXAMPLES.md - Practical examples
- README.md - Overview and quick reference
**Key Functions**: `update_os()` (apk version), `verb_ip6()`, `motd_ssh()` (Alpine), `customize()`
---
### 📁 [alpine-tools.func/](./alpine-tools.func/)
**Alpine Tool Installation** - Alpine-specific package and tool installation
**Contents:**
- ALPINE_TOOLS_FUNC_FLOWCHART.md - Alpine package flows
- ALPINE_TOOLS_FUNC_FUNCTIONS_REFERENCE.md - Function reference
- ALPINE_TOOLS_FUNC_INTEGRATION.md - Integration with Alpine workflows
- ALPINE_TOOLS_FUNC_USAGE_EXAMPLES.md - Practical examples
- README.md - Overview and quick reference
**Key Functions**: `apk_add()`, `apk_update()`, `apk_del()`, `add_community_repo()`, Alpine tool setup functions
---
### 📁 [cloud-init.func/](./cloud-init.func/)
**VM Cloud-Init Configuration** - Cloud-init and VM provisioning functions
**Contents:**
- CLOUD_INIT_FUNC_FLOWCHART.md - Cloud-init flows
- CLOUD_INIT_FUNC_FUNCTIONS_REFERENCE.md - Function reference
- CLOUD_INIT_FUNC_INTEGRATION.md - Integration points
- CLOUD_INIT_FUNC_USAGE_EXAMPLES.md - Practical examples
- README.md - Overview and quick reference
**Key Functions**: `generate_cloud_init()`, `generate_user_data()`, `setup_ssh_keys()`, `setup_static_ip()`
---
## 🔗 **Function Library Relationships**
```
┌─────────────────────────────────────────────┐
│ Container Creation Flow │
├─────────────────────────────────────────────┤
│ │
│ ct/AppName.sh │
│ ↓ (sources) │
│ build.func │
│ ├─ variables() │
│ ├─ build_container() │
│ └─ advanced_settings() │
│ ↓ (calls pct create with) │
│ install/appname-install.sh │
│ ↓ (sources) │
│ ├─ core.func (colors, messaging) │
│ ├─ error_handler.func (error trapping) │
│ ├─ install.func (setup/network) │
│ └─ tools.func (packages/tools) │
│ │
└─────────────────────────────────────────────┘
┌─────────────────────────────────────────────┐
│ Alpine Container Flow │
├─────────────────────────────────────────────┤
│ │
│ install/appname-install.sh (Alpine) │
│ ↓ (sources) │
│ ├─ core.func (colors) │
│ ├─ error_handler.func (errors) │
│ ├─ alpine-install.func (apk setup) │
│ └─ alpine-tools.func (apk tools) │
│ │
└─────────────────────────────────────────────┘
┌─────────────────────────────────────────────┐
│ VM Provisioning Flow │
├─────────────────────────────────────────────┤
│ │
│ vm/OsName-vm.sh │
│ ↓ (uses) │
│ cloud-init.func │
│ ├─ generate_cloud_init() │
│ ├─ setup_ssh_keys() │
│ └─ configure_network() │
│ │
└─────────────────────────────────────────────┘
```
---
## 📊 **Documentation Quick Stats**
| Library | Files | Functions | Status |
|---------|:---:|:---:|:---:|
| build.func | 7 | 50+ | ✅ Complete |
| core.func | 5 | 20+ | ✅ Complete |
| error_handler.func | 5 | 10+ | ✅ Complete |
| api.func | 5 | 5+ | ✅ Complete |
| install.func | 5 | 8+ | ✅ Complete |
| tools.func | 6 | 30+ | ✅ Complete |
| alpine-install.func | 5 | 6+ | ✅ Complete |
| alpine-tools.func | 5 | 15+ | ✅ Complete |
| cloud-init.func | 5 | 12+ | ✅ Complete |
**Total**: 9 function libraries, 48 documentation files, 150+ functions
---
## 🚀 **Getting Started**
### For Container Creation Scripts
Start with: **[build.func/](./build.func/)** → **[tools.func/](./tools.func/)** → **[install.func/](./install.func/)**
### For Alpine Containers
Start with: **[alpine-install.func/](./alpine-install.func/)** → **[alpine-tools.func/](./alpine-tools.func/)**
### For VM Provisioning
Start with: **[cloud-init.func/](./cloud-init.func/)**
### For Troubleshooting
Start with: **[error_handler.func/](./error_handler.func/)** → **[EXIT_CODES.md](../EXIT_CODES.md)**
---
## 📚 **Related Top-Level Documentation**
- **[CONTRIBUTION_GUIDE.md](../CONTRIBUTION_GUIDE.md)** - How to contribute to ProxmoxVE
- **[UPDATED_APP-ct.md](../UPDATED_APP-ct.md)** - Container script guide
- **[UPDATED_APP-install.md](../UPDATED_APP-install.md)** - Installation script guide
- **[DEFAULTS_SYSTEM_GUIDE.md](../DEFAULTS_SYSTEM_GUIDE.md)** - Configuration system
- **[TECHNICAL_REFERENCE.md](../TECHNICAL_REFERENCE.md)** - Architecture reference
- **[EXIT_CODES.md](../EXIT_CODES.md)** - Complete exit code reference
- **[DEV_MODE.md](../DEV_MODE.md)** - Development debugging modes
- **[CHANGELOG_MISC.md](../CHANGELOG_MISC.md)** - Change history
---
## 🔄 **Standardized Documentation Structure**
Each function library follows the same documentation pattern:
```
function-library/
├── README.md # Quick reference & overview
├── FUNCTION_LIBRARY_FLOWCHART.md # Visual execution flows
├── FUNCTION_LIBRARY_FUNCTIONS_REFERENCE.md # Alphabetical reference
├── FUNCTION_LIBRARY_INTEGRATION.md # Integration points
├── FUNCTION_LIBRARY_USAGE_EXAMPLES.md # Practical examples
└── [FUNCTION_LIBRARY_ENVIRONMENT_VARIABLES.md] # (if applicable)
```
**Advantages**:
- ✅ Consistent navigation across all libraries
- ✅ Quick reference sections in each README
- ✅ Visual flowcharts for understanding
- ✅ Complete function references
- ✅ Real-world usage examples
- ✅ Integration guides for connecting libraries
---
## 📝 **Documentation Standards**
All documentation follows these standards:
1. **README.md** - Quick overview, key features, quick reference
2. **FLOWCHART.md** - ASCII flowcharts and visual diagrams
3. **FUNCTIONS_REFERENCE.md** - Every function with full details
4. **INTEGRATION.md** - How this library connects to others
5. **USAGE_EXAMPLES.md** - Copy-paste ready examples
6. **ENVIRONMENT_VARIABLES.md** - (if applicable) Configuration reference
---
## ✅ **Last Updated**: December 2025
**Maintainers**: community-scripts team
**License**: MIT
**Status**: All 9 libraries fully documented and standardized
---
*This directory contains specialized documentation for specific components of the Proxmox Community Scripts project.*

View File

@ -0,0 +1,29 @@
# alpine-install.func Flowchart
Alpine container initialization flow (apk-based, OpenRC init system).
## Alpine Container Setup Flow
```
Alpine Container Started
setting_up_container()
verb_ip6() [optional - IPv6]
update_os() [apk update/upgrade]
network_check()
Application Installation
motd_ssh()
customize()
cleanup_lxc()
Complete ✓
```
**Last Updated**: December 2025

View File

@ -0,0 +1,30 @@
# alpine-install.func Functions Reference
Alpine Linux-specific installation functions (apk-based, OpenRC).
## Core Functions
### setting_up_container()
Initialize Alpine container setup.
### update_os()
Update Alpine packages via `apk update && apk upgrade`.
### verb_ip6()
Enable IPv6 on Alpine with persistent configuration.
### network_check()
Verify network connectivity in Alpine.
### motd_ssh()
Configure SSH daemon and MOTD on Alpine.
### customize()
Apply Alpine-specific customizations.
### cleanup_lxc()
Final cleanup (Alpine-specific).
---
**Last Updated**: December 2025

View File

@ -0,0 +1,14 @@
# alpine-install.func Integration Guide
Integration of alpine-install.func with Alpine container workflows.
## Alpine-Specific Integration
Alpine containers use:
- `apk` instead of `apt-get`
- `OpenRC` instead of `systemd`
- Alpine-specific package names
---
**Last Updated**: December 2025

View File

@ -0,0 +1,24 @@
# alpine-install.func Usage Examples
Basic examples for Alpine container installation.
### Example: Basic Alpine Setup
```bash
#!/usr/bin/env bash
source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
setting_up_container
update_os
# Install Alpine packages
apk add --no-cache curl wget git
motd_ssh
customize
cleanup_lxc
```
---
**Last Updated**: December 2025

View File

@ -0,0 +1,273 @@
# alpine-install.func Documentation
## Overview
The `alpine-install.func` file provides Alpine Linux-specific installation and configuration functions for LXC containers. It complements the standard `install.func` with Alpine-specific operations using the apk package manager instead of apt.
## Purpose and Use Cases
- **Alpine Container Setup**: Initialize Alpine Linux containers with proper configuration
- **IPv6 Management**: Enable or disable IPv6 in Alpine with persistent configuration
- **Network Verification**: Verify connectivity in Alpine environments
- **SSH Configuration**: Setup SSH daemon on Alpine
- **Auto-Login Setup**: Configure passwordless root login for Alpine containers
- **Package Management**: Safe apk operations with error handling
## Quick Reference
### Key Function Groups
- **Initialization**: `setting_up_container()` - Alpine setup message
- **Network**: `verb_ip6()`, `network_check()` - IPv6 and connectivity
- **OS Configuration**: `update_os()` - Alpine package updates
- **SSH/MOTD**: `motd_ssh()` - SSH and login message setup
- **Container Customization**: `customize()`, `cleanup_lxc()` - Final setup
### Dependencies
- **External**: `apk`, `curl`, `wget`, `ping`
- **Internal**: Uses functions from `core.func`, `error_handler.func`
### Integration Points
- Used by: Alpine-based install scripts (alpine.sh, alpine-ntfy.sh, etc.)
- Uses: Environment variables from build.func
- Provides: Alpine-specific installation and management services
## Documentation Files
### 📊 [ALPINE_INSTALL_FUNC_FLOWCHART.md](./ALPINE_INSTALL_FUNC_FLOWCHART.md)
Visual execution flows showing Alpine container initialization and setup workflows.
### 📚 [ALPINE_INSTALL_FUNC_FUNCTIONS_REFERENCE.md](./ALPINE_INSTALL_FUNC_FUNCTIONS_REFERENCE.md)
Complete alphabetical reference of all functions with parameters and usage details.
### 💡 [ALPINE_INSTALL_FUNC_USAGE_EXAMPLES.md](./ALPINE_INSTALL_FUNC_USAGE_EXAMPLES.md)
Practical examples showing how to use Alpine installation functions.
### 🔗 [ALPINE_INSTALL_FUNC_INTEGRATION.md](./ALPINE_INSTALL_FUNC_INTEGRATION.md)
How alpine-install.func integrates with standard install workflows.
## Key Features
### Alpine-Specific Functions
- **apk Package Manager**: Alpine package operations (instead of apt-get)
- **OpenRC Support**: Alpine uses OpenRC init instead of systemd
- **Lightweight Setup**: Minimal dependencies appropriate for Alpine
- **IPv6 Configuration**: Persistent IPv6 settings via `/etc/network/interfaces`
### Network & Connectivity
- **IPv6 Toggle**: Enable/disable with persistent configuration
- **Connectivity Check**: Verify internet access in Alpine
- **DNS Verification**: Resolve domain names correctly
- **Retry Logic**: Automatic recovery from transient failures
### SSH & Auto-Login
- **SSH Daemon**: Setup and start sshd on Alpine
- **Root Keys**: Configure root SSH access
- **Auto-Login**: Optional automatic login without password
- **MOTD**: Custom login message on Alpine
## Function Categories
### 🔹 Core Functions
- `setting_up_container()` - Alpine container setup message
- `update_os()` - Update Alpine packages via apk
- `verb_ip6()` - Enable/disable IPv6 persistently
- `network_check()` - Verify network connectivity
### 🔹 SSH & Configuration Functions
- `motd_ssh()` - Configure SSH daemon on Alpine
- `customize()` - Apply Alpine-specific customizations
- `cleanup_lxc()` - Final cleanup
### 🔹 Service Management (OpenRC)
- `rc-update` - Enable/disable services for Alpine
- `rc-service` - Start/stop services on Alpine
- Service configuration files in `/etc/init.d/`
## Differences from Debian Install
| Feature | Debian (install.func) | Alpine (alpine-install.func) |
|---------|:---:|:---:|
| Package Manager | apt-get | apk |
| Init System | systemd | OpenRC |
| SSH Service | systemctl | rc-service |
| Config Files | /etc/systemd/ | /etc/init.d/ |
| Network Config | /etc/network/ or Netplan | /etc/network/interfaces |
| IPv6 Setup | netplan files | /etc/network/interfaces |
| Auto-Login | getty override | `/etc/inittab` or shell config |
| Size | ~200MB | ~100MB |
## Execution Flow for Alpine
```
Alpine Container Started
source $FUNCTIONS_FILE_PATH
setting_up_container() ← Alpine setup message
update_os() ← apk update
verb_ip6() ← IPv6 configuration (optional)
network_check() ← Verify connectivity
[Application-Specific Installation]
motd_ssh() ← Configure SSH/MOTD
customize() ← Apply customizations
cleanup_lxc() ← Final cleanup
Alpine Installation Complete
```
## Common Usage Patterns
### Basic Alpine Setup
```bash
#!/usr/bin/env bash
source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
setting_up_container
update_os
# Install Alpine-specific packages
apk add --no-cache curl wget git
# ... application installation ...
motd_ssh
customize
cleanup_lxc
```
### With IPv6 Enabled
```bash
#!/usr/bin/env bash
source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
setting_up_container
verb_ip6
update_os
network_check
# ... application installation ...
motd_ssh
customize
cleanup_lxc
```
### Installing Services
```bash
#!/usr/bin/env bash
source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
setting_up_container
update_os
# Install via apk
apk add --no-cache nginx
# Enable and start service on Alpine
rc-update add nginx
rc-service nginx start
motd_ssh
customize
cleanup_lxc
```
## Best Practices
### ✅ DO
- Use `apk add --no-cache` to reduce image size
- Enable IPv6 if application needs it (`verb_ip6`)
- Use `rc-service` for service management on Alpine
- Check `/etc/network/interfaces` for IPv6 persistence
- Test network connectivity before critical operations
- Use `$STD` for output suppression in production
### ❌ DON'T
- Use `apt-get` commands (Alpine doesn't have apt)
- Use `systemctl` (Alpine uses OpenRC, not systemd)
- Use `service` command (it may not exist on Alpine)
- Assume systemd exists on Alpine
- Forget to add `--no-cache` flag to `apk add`
- Hardcode paths from Debian (different on Alpine)
## Alpine-Specific Considerations
### Package Names
Some packages have different names on Alpine:
```bash
# Debian → Alpine
# curl → curl (same)
# wget → wget (same)
# python3 → python3 (same)
# libpq5 → postgresql-client
# libmariadb3 → mariadb-client
```
### Service Management
```bash
# Debian (systemd) → Alpine (OpenRC)
systemctl start nginx → rc-service nginx start
systemctl enable nginx → rc-update add nginx
systemctl status nginx → rc-service nginx status
```
### Network Configuration
```bash
# Debian (Netplan) → Alpine (/etc/network/interfaces)
/etc/netplan/01-*.yaml → /etc/network/interfaces
netplan apply → Configure directly in interfaces
# Enable IPv6 persistently on Alpine:
# Add to /etc/network/interfaces:
# iface eth0 inet6 static
# address <IPv6_ADDRESS>
```
## Troubleshooting
### "apk command not found"
- This is Alpine Linux, not Debian
- Install packages with `apk add` instead of `apt-get install`
- Example: `apk add --no-cache curl wget`
### "IPv6 not persisting after reboot"
- IPv6 must be configured in `/etc/network/interfaces`
- The `verb_ip6()` function handles this automatically
- Verify: `cat /etc/network/interfaces`
### "Service won't start on Alpine"
- Alpine uses OpenRC, not systemd
- Use `rc-service nginx start` instead of `systemctl start nginx`
- Enable service: `rc-update add nginx`
- Check logs: `/var/log/` or `rc-service nginx status`
### "Container too large"
- Alpine should be much smaller than Debian
- Verify using `apk add --no-cache` (removes package cache)
- Example: `apk add --no-cache nginx` (not `apk add nginx`)
## Related Documentation
- **[alpine-tools.func/](../alpine-tools.func/)** - Alpine tool installation
- **[install.func/](../install.func/)** - Standard installation functions
- **[core.func/](../core.func/)** - Utility functions
- **[error_handler.func/](../error_handler.func/)** - Error handling
- **[UPDATED_APP-install.md](../../UPDATED_APP-install.md)** - Application script guide
## Recent Updates
### Version 2.0 (Dec 2025)
- ✅ Enhanced IPv6 persistence configuration
- ✅ Improved OpenRC service management
- ✅ Better apk error handling
- ✅ Added Alpine-specific best practices documentation
- ✅ Streamlined SSH setup for Alpine
---
**Last Updated**: December 2025
**Maintainers**: community-scripts team
**License**: MIT

View File

@ -0,0 +1,25 @@
# alpine-tools.func Flowchart
Alpine tool installation and package management flow.
## Tool Installation on Alpine
```
apk_update()
add_community_repo() [optional]
apk_add PACKAGES
Tool Installation
rc-service start
rc-update add [enable at boot]
Complete ✓
```
---
**Last Updated**: December 2025

View File

@ -0,0 +1,31 @@
# alpine-tools.func Functions Reference
Alpine-specific tool installation functions.
## Core Functions
### apk_update()
Update Alpine package lists.
### apk_add(PACKAGES)
Install Alpine packages.
### apk_del(PACKAGES)
Remove Alpine packages.
### add_community_repo()
Enable Alpine community repository.
### add_testing_repo()
Enable Alpine testing repository.
### Alpine Tool Functions
- `setup_nodejs()` - Alpine Node.js
- `setup_php()` - Alpine PHP
- `setup_mariadb()` - Alpine MariaDB
- `setup_postgresql()` - Alpine PostgreSQL
- (+ more Alpine-specific setups)
---
**Last Updated**: December 2025

View File

@ -0,0 +1,7 @@
# alpine-tools.func Integration Guide
Alpine tool installation integration with container workflows.
---
**Last Updated**: December 2025

View File

@ -0,0 +1,19 @@
# alpine-tools.func Usage Examples
Examples for Alpine tool installation.
### Example: Alpine Setup with Tools
```bash
#!/usr/bin/env bash
source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
apk_update
setup_nodejs "20"
setup_php "8.3"
setup_mariadb "11"
```
---
**Last Updated**: December 2025

View File

@ -0,0 +1,297 @@
# alpine-tools.func Documentation
## Overview
The `alpine-tools.func` file provides Alpine Linux-specific tool installation functions for package and service management within Alpine LXC containers. It complements `tools.func` with Alpine-specific implementations using the apk package manager.
## Purpose and Use Cases
- **Alpine Tool Installation**: Install services and tools using apk on Alpine
- **Package Management**: Safe apk operations with error handling
- **Service Setup**: Install and configure common services on Alpine
- **Dependency Management**: Handle Alpine-specific package dependencies
- **Repository Management**: Setup and manage Alpine package repositories
## Quick Reference
### Key Function Groups
- **Package Operations**: Alpine-specific apk commands with error handling
- **Service Installation**: Install databases, web servers, tools on Alpine
- **Repository Setup**: Configure Alpine community and testing repositories
- **Tool Setup**: Install development tools and utilities
### Dependencies
- **External**: `apk`, `curl`, `wget`
- **Internal**: Uses functions from `core.func`, `error_handler.func`
### Integration Points
- Used by: Alpine-based application install scripts
- Uses: Environment variables from build.func
- Provides: Alpine package and tool installation services
## Documentation Files
### 📊 [ALPINE_TOOLS_FUNC_FLOWCHART.md](./ALPINE_TOOLS_FUNC_FLOWCHART.md)
Visual execution flows for package operations and tool installation on Alpine.
### 📚 [ALPINE_TOOLS_FUNC_FUNCTIONS_REFERENCE.md](./ALPINE_TOOLS_FUNC_FUNCTIONS_REFERENCE.md)
Complete alphabetical reference of all Alpine tool functions.
### 💡 [ALPINE_TOOLS_FUNC_USAGE_EXAMPLES.md](./ALPINE_TOOLS_FUNC_USAGE_EXAMPLES.md)
Practical examples for common Alpine installation patterns.
### 🔗 [ALPINE_TOOLS_FUNC_INTEGRATION.md](./ALPINE_TOOLS_FUNC_INTEGRATION.md)
How alpine-tools.func integrates with Alpine installation workflows.
## Key Features
### Alpine Package Management
- **apk Add**: Safe package installation with error handling
- **apk Update**: Update package lists with retry logic
- **apk Del**: Remove packages and dependencies
- **Repository Configuration**: Add community and testing repos
### Alpine Tool Coverage
- **Web Servers**: nginx, lighttpd
- **Databases**: mariadb, postgresql, sqlite
- **Development**: gcc, make, git, node.js (via apk)
- **Services**: sshd, docker, podman
- **Utilities**: curl, wget, htop, vim
### Error Handling
- **Retry Logic**: Automatic recovery from transient failures
- **Dependency Resolution**: Handle missing dependencies
- **Lock Management**: Wait for apk locks to release
- **Error Reporting**: Clear error messages
## Function Categories
### 🔹 Package Management
- `apk_update()` - Update Alpine packages with retry
- `apk_add()` - Install packages safely
- `apk_del()` - Remove packages completely
### 🔹 Repository Functions
- `add_community_repo()` - Enable community repositories
- `add_testing_repo()` - Enable testing repositories
- `setup_apk_repo()` - Configure custom apk repositories
### 🔹 Service Installation Functions
- `setup_nginx()` - Install and configure nginx
- `setup_mariadb()` - Install MariaDB on Alpine
- `setup_postgresql()` - Install PostgreSQL
- `setup_docker()` - Install Docker on Alpine
- `setup_nodejs()` - Install Node.js from Alpine repos
### 🔹 Development Tools
- `setup_build_tools()` - Install gcc, make, build-essential
- `setup_git()` - Install git version control
- `setup_python()` - Install Python 3 and pip
## Alpine vs Debian Package Differences
| Package | Debian | Alpine |
|---------|:---:|:---:|
| nginx | `apt-get install nginx` | `apk add nginx` |
| mariadb | `apt-get install mariadb-server` | `apk add mariadb` |
| PostgreSQL | `apt-get install postgresql` | `apk add postgresql` |
| Node.js | `apt-get install nodejs npm` | `apk add nodejs npm` |
| Docker | Special setup | `apk add docker` |
| Python | `apt-get install python3 python3-pip` | `apk add python3 py3-pip` |
## Common Usage Patterns
### Basic Alpine Tool Installation
```bash
#!/usr/bin/env bash
source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
# Update package lists
apk_update
# Install nginx
apk_add nginx
# Start service
rc-service nginx start
rc-update add nginx
```
### With Community Repository
```bash
#!/usr/bin/env bash
source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
# Enable community repo for more packages
add_community_repo
# Update and install
apk_update
apk_add postgresql postgresql-client
# Start service
rc-service postgresql start
```
### Development Environment
```bash
#!/usr/bin/env bash
source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
# Install build tools
setup_build_tools
setup_git
setup_nodejs "20"
# Install application
git clone https://example.com/app
cd app
npm install
```
## Best Practices
### ✅ DO
- Always use `apk add --no-cache` to keep images small
- Call `apk_update()` before installing packages
- Use community repository for more packages (`add_community_repo`)
- Handle apk locks gracefully with retry logic
- Use `$STD` variable for output control
- Check if tool already installed before reinstalling
### ❌ DON'T
- Use `apt-get` commands (Alpine doesn't have apt)
- Install packages without `--no-cache` flag
- Hardcode Alpine-specific paths
- Mix Alpine and Debian commands
- Forget to enable services with `rc-update`
- Use `systemctl` (Alpine has OpenRC, not systemd)
## Alpine Repository Configuration
### Default Repositories
Alpine comes with main repository enabled by default. Additional repos:
```bash
# Community repository (apk add php, go, rust, etc.)
add_community_repo
# Testing repository (bleeding edge packages)
add_testing_repo
```
### Repository Locations
```bash
/etc/apk/repositories # Main repo list
/etc/apk/keys/ # GPG keys for repos
/var/cache/apk/ # Package cache
```
## Package Size Optimization
Alpine is designed for small container images:
```bash
# DON'T: Leaves package cache (increases image size)
apk add nginx
# DO: Remove cache to reduce size
apk add --no-cache nginx
# Expected sizes:
# Alpine base: ~5MB
# Alpine + nginx: ~10-15MB
# Debian base: ~75MB
# Debian + nginx: ~90-95MB
```
## Service Management on Alpine
### Using OpenRC
```bash
# Start service immediately
rc-service nginx start
# Stop service
rc-service nginx stop
# Restart service
rc-service nginx restart
# Enable at boot
rc-update add nginx
# Disable at boot
rc-update del nginx
# List enabled services
rc-update show
```
## Troubleshooting
### "apk: lock is held by PID"
```bash
# Alpine apk database is locked (another process using apk)
# Wait a moment
sleep 5
apk_update
# Or manually:
rm /var/lib/apk/lock 2>/dev/null || true
apk update
```
### "Package not found"
```bash
# May be in community or testing repository
add_community_repo
apk_update
apk_add package-name
```
### "Repository not responding"
```bash
# Alpine repo may be slow or unreachable
# Try updating again with retry logic
apk_update # Built-in retry logic
# Or manually retry
sleep 10
apk update
```
### "Service fails to start"
```bash
# Check service status on Alpine
rc-service nginx status
# View logs
tail /var/log/nginx/error.log
# Verify configuration
nginx -t
```
## Related Documentation
- **[alpine-install.func/](../alpine-install.func/)** - Alpine installation functions
- **[tools.func/](../tools.func/)** - Debian/standard tool installation
- **[core.func/](../core.func/)** - Utility functions
- **[error_handler.func/](../error_handler.func/)** - Error handling
- **[UPDATED_APP-install.md](../../UPDATED_APP-install.md)** - Application script guide
## Recent Updates
### Version 2.0 (Dec 2025)
- ✅ Enhanced apk error handling and retry logic
- ✅ Improved repository management
- ✅ Better service management with OpenRC
- ✅ Added Alpine-specific optimization guidance
- ✅ Enhanced package cache management
---
**Last Updated**: December 2025
**Maintainers**: community-scripts team
**License**: MIT

View File

@ -0,0 +1,342 @@
# api.func Execution Flowchart
## Main API Communication Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ API Communication Initialization │
│ Entry point when api.func functions are called by installation scripts │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Prerequisites Check │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Prerequisites Validation │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Check curl │ │ Check │ │ Check │ │ │
│ │ │ Availability │ │ Diagnostics │ │ Random UUID │ │ │
│ │ │ │ │ Setting │ │ │ │
│ │ │ • command -v │ │ • DIAGNOSTICS │ │ • RANDOM_UUID │ │
│ │ │ curl │ │ = "yes" │ │ not empty │ │
│ │ │ • Return if │ │ • Return if │ │ • Return if │ │
│ │ │ not found │ │ disabled │ │ not set │ │
│ │ │ │ │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Data Collection │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ System Information Gathering │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Get PVE │ │ Collect │ │ Prepare JSON │ │ │
│ │ │ Version │ │ Environment │ │ Payload │ │
│ │ │ │ │ Variables │ │ │ │
│ │ │ • pveversion │ │ • CT_TYPE │ │ • Create JSON │ │
│ │ │ command │ │ • DISK_SIZE │ │ structure │ │
│ │ │ • Parse version │ │ • CORE_COUNT │ │ • Include all │ │
│ │ │ • Extract │ │ • RAM_SIZE │ │ variables │ │
│ │ │ major.minor │ │ • var_os │ │ • Format for API │ │
│ │ │ │ │ • var_version │ │ │ │
│ │ │ │ │ • NSAPP │ │ │ │
│ │ │ │ │ • METHOD │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ API Request Execution │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ HTTP Request Processing │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Prepare │ │ Execute │ │ Handle │ │ │
│ │ │ Request │ │ HTTP Request │ │ Response │ │
│ │ │ │ │ │ │ │ │
│ │ │ • Set API URL │ │ • curl -s -w │ │ • Capture HTTP │ │
│ │ │ • Set headers │ │ "%{http_code}" │ │ status code │ │
│ │ │ • Set payload │ │ • POST request │ │ • Store response │ │
│ │ │ • Content-Type │ │ • JSON data │ │ • Handle errors │ │
│ │ │ application/ │ │ • Follow │ │ gracefully │ │
│ │ │ json │ │ redirects │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## LXC API Reporting Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ POST_TO_API() Flow │
│ Send LXC container installation data to API │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ LXC Data Preparation │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ LXC-Specific Data Collection │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Set LXC │ │ Include LXC │ │ Set Status │ │ │
│ │ │ Type │ │ Variables │ │ Information │ │
│ │ │ │ │ │ │ │ │
│ │ │ • ct_type: 1 │ │ • DISK_SIZE │ │ • status: │ │
│ │ │ • type: "lxc" │ │ • CORE_COUNT │ │ "installing" │ │
│ │ │ • Include all │ │ • RAM_SIZE │ │ • Include all │ │
│ │ │ LXC data │ │ • var_os │ │ tracking data │ │
│ │ │ │ │ • var_version │ │ │ │
│ │ │ │ │ • DISABLEIP6 │ │ │ │
│ │ │ │ │ • NSAPP │ │ │ │
│ │ │ │ │ • METHOD │ │ │ │
│ │ │ │ │ • pve_version │ │ │ │
│ │ │ │ │ • random_id │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ JSON Payload Creation │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ JSON Structure Generation │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Create JSON │ │ Validate │ │ Format for │ │ │
│ │ │ Structure │ │ Data │ │ API Request │ │
│ │ │ │ │ │ │ │ │
│ │ │ • Use heredoc │ │ • Check all │ │ • Ensure proper │ │
│ │ │ syntax │ │ variables │ │ JSON format │ │
│ │ │ • Include all │ │ are set │ │ • Escape special │ │
│ │ │ required │ │ • Validate │ │ characters │ │
│ │ │ fields │ │ data types │ │ • Set content │ │
│ │ │ • Format │ │ • Handle │ │ type │ │
│ │ │ properly │ │ missing │ │ │ │
│ │ │ │ │ values │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## VM API Reporting Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ POST_TO_API_VM() Flow │
│ Send VM installation data to API │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ VM Data Preparation │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ VM-Specific Data Collection │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Check │ │ Set VM │ │ Process Disk │ │ │
│ │ │ Diagnostics │ │ Type │ │ Size │ │
│ │ │ File │ │ │ │ │ │
│ │ │ │ │ • ct_type: 2 │ │ • Remove 'G' │ │
│ │ │ • Check file │ │ • type: "vm" │ │ suffix │ │
│ │ │ existence │ │ • Include all │ │ • Convert to │ │
│ │ │ • Read │ │ VM data │ │ numeric value │ │
│ │ │ DIAGNOSTICS │ │ │ │ • Store in │ │
│ │ │ setting │ │ │ │ DISK_SIZE_API │ │
│ │ │ • Parse value │ │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ VM JSON Payload Creation │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ VM-Specific JSON Structure │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Include VM │ │ Set VM │ │ Format VM │ │ │
│ │ │ Variables │ │ Status │ │ Data for API │ │
│ │ │ │ │ │ │ │ │
│ │ │ • DISK_SIZE_API │ │ • status: │ │ • Ensure proper │ │
│ │ │ • CORE_COUNT │ │ "installing" │ │ JSON format │ │
│ │ │ • RAM_SIZE │ │ • Include all │ │ • Handle VM- │ │
│ │ │ • var_os │ │ tracking │ │ specific data │ │
│ │ │ • var_version │ │ information │ │ • Set appropriate │ │
│ │ │ • NSAPP │ │ │ │ content type │ │
│ │ │ • METHOD │ │ │ │ │ │
│ │ │ • pve_version │ │ │ │ │ │
│ │ │ • random_id │ │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## Status Update Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ POST_UPDATE_TO_API() Flow │
│ Send installation completion status to API │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Update Prevention Check │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Duplicate Update Prevention │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Check │ │ Set Flag │ │ Return Early │ │ │
│ │ │ POST_UPDATE_ │ │ if First │ │ if Already │ │
│ │ │ DONE │ │ Update │ │ Updated │ │
│ │ │ │ │ │ │ │ │
│ │ │ • Check if │ │ • Set │ │ • Return 0 │ │
│ │ │ already │ │ POST_UPDATE_ │ │ • Skip API call │ │
│ │ │ updated │ │ DONE=true │ │ • Prevent │ │
│ │ │ • Prevent │ │ • Continue │ │ duplicate │ │
│ │ │ duplicate │ │ with update │ │ requests │ │
│ │ │ requests │ │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Status and Error Processing │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Status Determination │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Determine │ │ Get Error │ │ Prepare Status │ │ │
│ │ │ Status │ │ Description │ │ Data │ │
│ │ │ │ │ │ │ │ │
│ │ │ • status: │ │ • Call │ │ • Include status │ │
│ │ │ "success" or │ │ get_error_ │ │ • Include error │ │
│ │ │ "failed" │ │ description() │ │ description │ │
│ │ │ • Set exit │ │ • Get human- │ │ • Include random │ │
│ │ │ code based │ │ readable │ │ ID for tracking │ │
│ │ │ on status │ │ error message │ │ │ │
│ │ │ • Default to │ │ • Handle │ │ │ │
│ │ │ error if │ │ unknown │ │ │ │
│ │ │ not set │ │ errors │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Status Update API Request │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Status Update Payload Creation │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Create │ │ Send Status │ │ Mark Update │ │ │
│ │ │ Status JSON │ │ Update │ │ Complete │ │
│ │ │ │ │ │ │ │ │
│ │ │ • Include │ │ • POST to │ │ • Set │ │
│ │ │ status │ │ updatestatus │ │ POST_UPDATE_ │ │
│ │ │ • Include │ │ endpoint │ │ DONE=true │ │
│ │ │ error │ │ • Include JSON │ │ • Prevent further │ │
│ │ │ description │ │ payload │ │ updates │ │
│ │ │ • Include │ │ • Handle │ │ • Complete │ │
│ │ │ random_id │ │ response │ │ process │ │
│ │ │ │ │ gracefully │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## Error Description Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ GET_ERROR_DESCRIPTION() Flow │
│ Convert numeric exit codes to human-readable explanations │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Error Code Classification │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Error Code Categories │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ General │ │ Network │ │ LXC-Specific │ │ │
│ │ │ System │ │ Errors │ │ Errors │ │
│ │ │ Errors │ │ │ │ │ │
│ │ │ │ │ • 18: Connection│ │ • 100-101: LXC │ │
│ │ │ • 0-9: Basic │ │ failed │ │ install errors │ │
│ │ │ errors │ │ • 22: Invalid │ │ • 200-209: LXC │ │
│ │ │ • 126-128: │ │ argument │ │ creation errors │ │
│ │ │ Command │ │ • 28: No space │ │ │ │
│ │ │ errors │ │ • 35: Timeout │ │ │ │
│ │ │ • 129-143: │ │ • 56: TLS error │ │ │ │
│ │ │ Signal │ │ • 60: SSL cert │ │ │ │
│ │ │ errors │ │ error │ │ │ │
│ │ │ • 152: Resource │ │ │ │ │ │
│ │ │ limit │ │ │ │ │ │
│ │ │ • 255: Unknown │ │ │ │ │ │
│ │ │ critical │ │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Error Message Return │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Error Message Formatting │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Match Error │ │ Return │ │ Default Case │ │ │
│ │ │ Code │ │ Description │ │ │ │
│ │ │ │ │ │ │ │ │
│ │ │ • Use case │ │ • Return │ │ • Return "Unknown │ │
│ │ │ statement │ │ human- │ │ error code │ │
│ │ │ • Match │ │ readable │ │ (exit_code)" │ │
│ │ │ specific │ │ message │ │ • Handle │ │
│ │ │ codes │ │ • Include │ │ unrecognized │ │
│ │ │ • Handle │ │ context │ │ codes │ │
│ │ │ ranges │ │ information │ │ • Provide fallback │ │
│ │ │ │ │ │ │ message │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## Integration Points
### With Installation Scripts
- **build.func**: Sends LXC installation data
- **vm-core.func**: Sends VM installation data
- **install.func**: Reports installation status
- **alpine-install.func**: Reports Alpine installation data
### With Error Handling
- **error_handler.func**: Provides error explanations
- **core.func**: Uses error descriptions in silent execution
- **Diagnostic reporting**: Tracks error patterns
### External Dependencies
- **curl**: HTTP client for API communication
- **Community Scripts API**: External API endpoint
- **Network connectivity**: Required for API communication

View File

@ -0,0 +1,433 @@
# api.func Functions Reference
## Overview
This document provides a comprehensive alphabetical reference of all functions in `api.func`, including parameters, dependencies, usage examples, and error handling.
## Function Categories
### Error Description Functions
#### `get_error_description()`
**Purpose**: Convert numeric exit codes to human-readable explanations
**Parameters**:
- `$1` - Exit code to explain
**Returns**: Human-readable error explanation string
**Side Effects**: None
**Dependencies**: None
**Environment Variables Used**: None
**Supported Exit Codes**:
- **General System**: 0-9, 18, 22, 28, 35, 56, 60, 125-128, 129-143, 152, 255
- **LXC-Specific**: 100-101, 200-209
- **Docker**: 125
**Usage Example**:
```bash
error_msg=$(get_error_description 127)
echo "Error 127: $error_msg"
# Output: Error 127: Command not found: Incorrect path or missing dependency.
```
**Error Code Examples**:
```bash
get_error_description 0 # " " (space)
get_error_description 1 # "General error: An unspecified error occurred."
get_error_description 127 # "Command not found: Incorrect path or missing dependency."
get_error_description 200 # "LXC creation failed."
get_error_description 255 # "Unknown critical error, often due to missing permissions or broken scripts."
```
### API Communication Functions
#### `post_to_api()`
**Purpose**: Send LXC container installation data to community-scripts.org API
**Parameters**: None (uses environment variables)
**Returns**: None
**Side Effects**:
- Sends HTTP POST request to API
- Stores response in RESPONSE variable
- Requires curl command and network connectivity
**Dependencies**: `curl` command
**Environment Variables Used**: `DIAGNOSTICS`, `RANDOM_UUID`, `CT_TYPE`, `DISK_SIZE`, `CORE_COUNT`, `RAM_SIZE`, `var_os`, `var_version`, `DISABLEIP6`, `NSAPP`, `METHOD`
**Prerequisites**:
- `curl` command must be available
- `DIAGNOSTICS` must be set to "yes"
- `RANDOM_UUID` must be set and not empty
**API Endpoint**: `http://api.community-scripts.org/dev/upload`
**JSON Payload Structure**:
```json
{
"ct_type": 1,
"type": "lxc",
"disk_size": 8,
"core_count": 2,
"ram_size": 2048,
"os_type": "debian",
"os_version": "12",
"disableip6": "true",
"nsapp": "plex",
"method": "install",
"pve_version": "8.0",
"status": "installing",
"random_id": "uuid-string"
}
```
**Usage Example**:
```bash
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export CT_TYPE=1
export DISK_SIZE=8
export CORE_COUNT=2
export RAM_SIZE=2048
export var_os="debian"
export var_version="12"
export NSAPP="plex"
export METHOD="install"
post_to_api
```
#### `post_to_api_vm()`
**Purpose**: Send VM installation data to community-scripts.org API
**Parameters**: None (uses environment variables)
**Returns**: None
**Side Effects**:
- Sends HTTP POST request to API
- Stores response in RESPONSE variable
- Requires curl command and network connectivity
**Dependencies**: `curl` command, diagnostics file
**Environment Variables Used**: `DIAGNOSTICS`, `RANDOM_UUID`, `DISK_SIZE`, `CORE_COUNT`, `RAM_SIZE`, `var_os`, `var_version`, `NSAPP`, `METHOD`
**Prerequisites**:
- `/usr/local/community-scripts/diagnostics` file must exist
- `DIAGNOSTICS` must be set to "yes" in diagnostics file
- `curl` command must be available
- `RANDOM_UUID` must be set and not empty
**API Endpoint**: `http://api.community-scripts.org/dev/upload`
**JSON Payload Structure**:
```json
{
"ct_type": 2,
"type": "vm",
"disk_size": 8,
"core_count": 2,
"ram_size": 2048,
"os_type": "debian",
"os_version": "12",
"disableip6": "",
"nsapp": "plex",
"method": "install",
"pve_version": "8.0",
"status": "installing",
"random_id": "uuid-string"
}
```
**Usage Example**:
```bash
# Create diagnostics file
echo "DIAGNOSTICS=yes" > /usr/local/community-scripts/diagnostics
export RANDOM_UUID="$(uuidgen)"
export DISK_SIZE="8G"
export CORE_COUNT=2
export RAM_SIZE=2048
export var_os="debian"
export var_version="12"
export NSAPP="plex"
export METHOD="install"
post_to_api_vm
```
#### `post_update_to_api()`
**Purpose**: Send installation completion status to community-scripts.org API
**Parameters**:
- `$1` - Status ("success" or "failed", default: "failed")
- `$2` - Exit code (default: 1)
**Returns**: None
**Side Effects**:
- Sends HTTP POST request to API
- Sets POST_UPDATE_DONE=true to prevent duplicates
- Stores response in RESPONSE variable
**Dependencies**: `curl` command, `get_error_description()`
**Environment Variables Used**: `DIAGNOSTICS`, `RANDOM_UUID`
**Prerequisites**:
- `curl` command must be available
- `DIAGNOSTICS` must be set to "yes"
- `RANDOM_UUID` must be set and not empty
- POST_UPDATE_DONE must be false (prevents duplicates)
**API Endpoint**: `http://api.community-scripts.org/dev/upload/updatestatus`
**JSON Payload Structure**:
```json
{
"status": "success",
"error": "Error description from get_error_description()",
"random_id": "uuid-string"
}
```
**Usage Example**:
```bash
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# Report successful installation
post_update_to_api "success" 0
# Report failed installation
post_update_to_api "failed" 127
```
## Function Call Hierarchy
### API Communication Flow
```
post_to_api()
├── Check curl availability
├── Check DIAGNOSTICS setting
├── Check RANDOM_UUID
├── Get PVE version
├── Create JSON payload
└── Send HTTP POST request
post_to_api_vm()
├── Check diagnostics file
├── Check curl availability
├── Check DIAGNOSTICS setting
├── Check RANDOM_UUID
├── Process disk size
├── Get PVE version
├── Create JSON payload
└── Send HTTP POST request
post_update_to_api()
├── Check POST_UPDATE_DONE flag
├── Check curl availability
├── Check DIAGNOSTICS setting
├── Check RANDOM_UUID
├── Determine status and exit code
├── Get error description
├── Create JSON payload
├── Send HTTP POST request
└── Set POST_UPDATE_DONE=true
```
### Error Description Flow
```
get_error_description()
├── Match exit code
├── Return appropriate description
└── Handle unknown codes
```
## Error Code Reference
### General System Errors
| Code | Description |
|------|-------------|
| 0 | (space) |
| 1 | General error: An unspecified error occurred. |
| 2 | Incorrect shell usage or invalid command arguments. |
| 3 | Unexecuted function or invalid shell condition. |
| 4 | Error opening a file or invalid path. |
| 5 | I/O error: An input/output failure occurred. |
| 6 | No such device or address. |
| 7 | Insufficient memory or resource exhaustion. |
| 8 | Non-executable file or invalid file format. |
| 9 | Failed child process execution. |
| 18 | Connection to a remote server failed. |
| 22 | Invalid argument or faulty network connection. |
| 28 | No space left on device. |
| 35 | Timeout while establishing a connection. |
| 56 | Faulty TLS connection. |
| 60 | SSL certificate error. |
### Command Execution Errors
| Code | Description |
|------|-------------|
| 125 | Docker error: Container could not start. |
| 126 | Command not executable: Incorrect permissions or missing dependencies. |
| 127 | Command not found: Incorrect path or missing dependency. |
| 128 | Invalid exit signal, e.g., incorrect Git command. |
### Signal Errors
| Code | Description |
|------|-------------|
| 129 | Signal 1 (SIGHUP): Process terminated due to hangup. |
| 130 | Signal 2 (SIGINT): Manual termination via Ctrl+C. |
| 132 | Signal 4 (SIGILL): Illegal machine instruction. |
| 133 | Signal 5 (SIGTRAP): Debugging error or invalid breakpoint signal. |
| 134 | Signal 6 (SIGABRT): Program aborted itself. |
| 135 | Signal 7 (SIGBUS): Memory error, invalid memory address. |
| 137 | Signal 9 (SIGKILL): Process forcibly terminated (OOM-killer or 'kill -9'). |
| 139 | Signal 11 (SIGSEGV): Segmentation fault, possibly due to invalid pointer access. |
| 141 | Signal 13 (SIGPIPE): Pipe closed unexpectedly. |
| 143 | Signal 15 (SIGTERM): Process terminated normally. |
| 152 | Signal 24 (SIGXCPU): CPU time limit exceeded. |
### LXC-Specific Errors
| Code | Description |
|------|-------------|
| 100 | LXC install error: Unexpected error in create_lxc.sh. |
| 101 | LXC install error: No network connection detected. |
| 200 | LXC creation failed. |
| 201 | LXC error: Invalid Storage class. |
| 202 | User aborted menu in create_lxc.sh. |
| 203 | CTID not set in create_lxc.sh. |
| 204 | PCT_OSTYPE not set in create_lxc.sh. |
| 205 | CTID cannot be less than 100 in create_lxc.sh. |
| 206 | CTID already in use in create_lxc.sh. |
| 207 | Template not found in create_lxc.sh. |
| 208 | Error downloading template in create_lxc.sh. |
| 209 | Container creation failed, but template is intact in create_lxc.sh. |
### Other Errors
| Code | Description |
|------|-------------|
| 255 | Unknown critical error, often due to missing permissions or broken scripts. |
| * | Unknown error code (exit_code). |
## Environment Variable Dependencies
### Required Variables
- **`DIAGNOSTICS`**: Enable/disable diagnostic reporting ("yes"/"no")
- **`RANDOM_UUID`**: Unique identifier for tracking
### Optional Variables
- **`CT_TYPE`**: Container type (1 for LXC, 2 for VM)
- **`DISK_SIZE`**: Disk size in GB (or GB with 'G' suffix for VM)
- **`CORE_COUNT`**: Number of CPU cores
- **`RAM_SIZE`**: RAM size in MB
- **`var_os`**: Operating system type
- **`var_version`**: OS version
- **`DISABLEIP6`**: IPv6 disable setting
- **`NSAPP`**: Namespace application name
- **`METHOD`**: Installation method
### Internal Variables
- **`POST_UPDATE_DONE`**: Prevents duplicate status updates
- **`API_URL`**: Community scripts API endpoint
- **`JSON_PAYLOAD`**: API request payload
- **`RESPONSE`**: API response
- **`DISK_SIZE_API`**: Processed disk size for VM API
## Error Handling Patterns
### API Communication Errors
- All API functions handle curl failures gracefully
- Network errors don't block installation process
- Missing prerequisites cause early return
- Duplicate updates are prevented
### Error Description Errors
- Unknown error codes return generic message
- All error codes are handled with case statement
- Fallback message includes the actual error code
### Prerequisites Validation
- Check curl availability before API calls
- Validate DIAGNOSTICS setting
- Ensure RANDOM_UUID is set
- Check for duplicate updates
## Integration Examples
### With build.func
```bash
#!/usr/bin/env bash
source core.func
source api.func
source build.func
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# Report installation start
post_to_api
# Container creation...
# ... build.func code ...
# Report completion
if [[ $? -eq 0 ]]; then
post_update_to_api "success" 0
else
post_update_to_api "failed" $?
fi
```
### With vm-core.func
```bash
#!/usr/bin/env bash
source core.func
source api.func
source vm-core.func
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# Report VM installation start
post_to_api_vm
# VM creation...
# ... vm-core.func code ...
# Report completion
post_update_to_api "success" 0
```
### With error_handler.func
```bash
#!/usr/bin/env bash
source core.func
source error_handler.func
source api.func
# Use error descriptions
error_code=127
error_msg=$(get_error_description $error_code)
echo "Error $error_code: $error_msg"
# Report error to API
post_update_to_api "failed" $error_code
```
## Best Practices
### API Usage
1. Always check prerequisites before API calls
2. Use unique identifiers for tracking
3. Handle API failures gracefully
4. Don't block installation on API failures
### Error Reporting
1. Use appropriate error codes
2. Provide meaningful error descriptions
3. Report both success and failure cases
4. Prevent duplicate status updates
### Diagnostic Reporting
1. Respect user privacy settings
2. Only send data when diagnostics enabled
3. Use anonymous tracking identifiers
4. Include relevant system information
### Error Handling
1. Handle unknown error codes gracefully
2. Provide fallback error messages
3. Include error code in unknown error messages
4. Use consistent error message format

View File

@ -0,0 +1,643 @@
# api.func Integration Guide
## Overview
This document describes how `api.func` integrates with other components in the Proxmox Community Scripts project, including dependencies, data flow, and API surface.
## Dependencies
### External Dependencies
#### Required Commands
- **`curl`**: HTTP client for API communication
- **`uuidgen`**: Generate unique identifiers (optional, can use other methods)
#### Optional Commands
- **None**: No other external command dependencies
### Internal Dependencies
#### Environment Variables from Other Scripts
- **build.func**: Provides container creation variables
- **vm-core.func**: Provides VM creation variables
- **core.func**: Provides system information variables
- **Installation scripts**: Provide application-specific variables
## Integration Points
### With build.func
#### LXC Container Reporting
```bash
# build.func uses api.func for container reporting
source core.func
source api.func
source build.func
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# Container creation with API reporting
create_container() {
# Set container parameters
export CT_TYPE=1
export DISK_SIZE="$var_disk"
export CORE_COUNT="$var_cpu"
export RAM_SIZE="$var_ram"
export var_os="$var_os"
export var_version="$var_version"
export NSAPP="$APP"
export METHOD="install"
# Report installation start
post_to_api
# Container creation using build.func
# ... build.func container creation logic ...
# Report completion
if [[ $? -eq 0 ]]; then
post_update_to_api "success" 0
else
post_update_to_api "failed" $?
fi
}
```
#### Error Reporting Integration
```bash
# build.func uses api.func for error reporting
handle_container_error() {
local exit_code=$1
local error_msg=$(get_error_description $exit_code)
echo "Container creation failed: $error_msg"
post_update_to_api "failed" $exit_code
}
```
### With vm-core.func
#### VM Installation Reporting
```bash
# vm-core.func uses api.func for VM reporting
source core.func
source api.func
source vm-core.func
# Set up VM API reporting
mkdir -p /usr/local/community-scripts
echo "DIAGNOSTICS=yes" > /usr/local/community-scripts/diagnostics
export RANDOM_UUID="$(uuidgen)"
# VM creation with API reporting
create_vm() {
# Set VM parameters
export DISK_SIZE="${var_disk}G"
export CORE_COUNT="$var_cpu"
export RAM_SIZE="$var_ram"
export var_os="$var_os"
export var_version="$var_version"
export NSAPP="$APP"
export METHOD="install"
# Report VM installation start
post_to_api_vm
# VM creation using vm-core.func
# ... vm-core.func VM creation logic ...
# Report completion
post_update_to_api "success" 0
}
```
### With core.func
#### System Information Integration
```bash
# core.func provides system information for api.func
source core.func
source api.func
# Get system information for API reporting
get_system_info_for_api() {
# Get PVE version using core.func utilities
local pve_version=$(pveversion | awk -F'[/ ]' '{print $2}')
# Set API parameters
export var_os="$var_os"
export var_version="$var_version"
# Use core.func error handling with api.func reporting
if silent apt-get update; then
post_update_to_api "success" 0
else
post_update_to_api "failed" $?
fi
}
```
### With error_handler.func
#### Error Description Integration
```bash
# error_handler.func uses api.func for error descriptions
source core.func
source error_handler.func
source api.func
# Enhanced error handler with API reporting
enhanced_error_handler() {
local exit_code=${1:-$?}
local command=${2:-${BASH_COMMAND:-unknown}}
# Get error description from api.func
local error_msg=$(get_error_description $exit_code)
# Display error information
echo "Error $exit_code: $error_msg"
echo "Command: $command"
# Report error to API
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
post_update_to_api "failed" $exit_code
# Use standard error handler
error_handler $exit_code $command
}
```
### With install.func
#### Installation Process Reporting
```bash
# install.func uses api.func for installation reporting
source core.func
source api.func
source install.func
# Installation with API reporting
install_package_with_reporting() {
local package="$1"
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export NSAPP="$package"
export METHOD="install"
# Report installation start
post_to_api
# Package installation using install.func
if install_package "$package"; then
echo "$package installed successfully"
post_update_to_api "success" 0
return 0
else
local exit_code=$?
local error_msg=$(get_error_description $exit_code)
echo "$package installation failed: $error_msg"
post_update_to_api "failed" $exit_code
return $exit_code
fi
}
```
### With alpine-install.func
#### Alpine Installation Reporting
```bash
# alpine-install.func uses api.func for Alpine reporting
source core.func
source api.func
source alpine-install.func
# Alpine installation with API reporting
install_alpine_with_reporting() {
local app="$1"
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export NSAPP="$app"
export METHOD="install"
export var_os="alpine"
# Report Alpine installation start
post_to_api
# Alpine installation using alpine-install.func
if install_alpine_app "$app"; then
echo "Alpine $app installed successfully"
post_update_to_api "success" 0
return 0
else
local exit_code=$?
local error_msg=$(get_error_description $exit_code)
echo "Alpine $app installation failed: $error_msg"
post_update_to_api "failed" $exit_code
return $exit_code
fi
}
```
### With alpine-tools.func
#### Alpine Tools Reporting
```bash
# alpine-tools.func uses api.func for Alpine tools reporting
source core.func
source api.func
source alpine-tools.func
# Alpine tools with API reporting
run_alpine_tool_with_reporting() {
local tool="$1"
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export NSAPP="alpine-tools"
export METHOD="tool"
# Report tool execution start
post_to_api
# Run Alpine tool using alpine-tools.func
if run_alpine_tool "$tool"; then
echo "Alpine tool $tool executed successfully"
post_update_to_api "success" 0
return 0
else
local exit_code=$?
local error_msg=$(get_error_description $exit_code)
echo "Alpine tool $tool failed: $error_msg"
post_update_to_api "failed" $exit_code
return $exit_code
fi
}
```
### With passthrough.func
#### Hardware Passthrough Reporting
```bash
# passthrough.func uses api.func for hardware reporting
source core.func
source api.func
source passthrough.func
# Hardware passthrough with API reporting
configure_passthrough_with_reporting() {
local hardware_type="$1"
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export NSAPP="passthrough"
export METHOD="hardware"
# Report passthrough configuration start
post_to_api
# Configure passthrough using passthrough.func
if configure_passthrough "$hardware_type"; then
echo "Hardware passthrough configured successfully"
post_update_to_api "success" 0
return 0
else
local exit_code=$?
local error_msg=$(get_error_description $exit_code)
echo "Hardware passthrough failed: $error_msg"
post_update_to_api "failed" $exit_code
return $exit_code
fi
}
```
### With tools.func
#### Maintenance Operations Reporting
```bash
# tools.func uses api.func for maintenance reporting
source core.func
source api.func
source tools.func
# Maintenance operations with API reporting
run_maintenance_with_reporting() {
local operation="$1"
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export NSAPP="maintenance"
export METHOD="tool"
# Report maintenance start
post_to_api
# Run maintenance using tools.func
if run_maintenance_operation "$operation"; then
echo "Maintenance operation $operation completed successfully"
post_update_to_api "success" 0
return 0
else
local exit_code=$?
local error_msg=$(get_error_description $exit_code)
echo "Maintenance operation $operation failed: $error_msg"
post_update_to_api "failed" $exit_code
return $exit_code
fi
}
```
## Data Flow
### Input Data
#### Environment Variables from Other Scripts
- **`CT_TYPE`**: Container type (1 for LXC, 2 for VM)
- **`DISK_SIZE`**: Disk size in GB
- **`CORE_COUNT`**: Number of CPU cores
- **`RAM_SIZE`**: RAM size in MB
- **`var_os`**: Operating system type
- **`var_version`**: OS version
- **`DISABLEIP6`**: IPv6 disable setting
- **`NSAPP`**: Namespace application name
- **`METHOD`**: Installation method
- **`DIAGNOSTICS`**: Enable/disable diagnostic reporting
- **`RANDOM_UUID`**: Unique identifier for tracking
#### Function Parameters
- **Exit codes**: Passed to `get_error_description()` and `post_update_to_api()`
- **Status information**: Passed to `post_update_to_api()`
- **API endpoints**: Hardcoded in functions
#### System Information
- **PVE version**: Retrieved from `pveversion` command
- **Disk size processing**: Processed for VM API (removes 'G' suffix)
- **Error codes**: Retrieved from command exit codes
### Processing Data
#### API Request Preparation
- **JSON payload creation**: Format data for API consumption
- **Data validation**: Ensure required fields are present
- **Error handling**: Handle missing or invalid data
- **Content type setting**: Set appropriate HTTP headers
#### Error Processing
- **Error code mapping**: Map numeric codes to descriptions
- **Error message formatting**: Format error descriptions
- **Unknown error handling**: Handle unrecognized error codes
- **Fallback messages**: Provide default error messages
#### API Communication
- **HTTP request preparation**: Prepare curl commands
- **Response handling**: Capture HTTP response codes
- **Error handling**: Handle network and API errors
- **Duplicate prevention**: Prevent duplicate status updates
### Output Data
#### API Communication
- **HTTP requests**: Sent to community-scripts.org API
- **Response codes**: Captured from API responses
- **Error information**: Reported to API
- **Status updates**: Sent to API
#### Error Information
- **Error descriptions**: Human-readable error messages
- **Error codes**: Mapped to descriptions
- **Context information**: Error context and details
- **Fallback messages**: Default error messages
#### System State
- **POST_UPDATE_DONE**: Prevents duplicate updates
- **RESPONSE**: Stores API response
- **JSON_PAYLOAD**: Stores formatted API data
- **API_URL**: Stores API endpoint
## API Surface
### Public Functions
#### Error Description
- **`get_error_description()`**: Convert exit codes to explanations
- **Parameters**: Exit code to explain
- **Returns**: Human-readable explanation string
- **Usage**: Called by other functions and scripts
#### API Communication
- **`post_to_api()`**: Send LXC installation data
- **`post_to_api_vm()`**: Send VM installation data
- **`post_update_to_api()`**: Send status updates
- **Parameters**: Status and exit code (for updates)
- **Returns**: None
- **Usage**: Called by installation scripts
### Internal Functions
#### None
- All functions in api.func are public
- No internal helper functions
- Direct implementation of all functionality
### Global Variables
#### Configuration Variables
- **`DIAGNOSTICS`**: Diagnostic reporting setting
- **`RANDOM_UUID`**: Unique tracking identifier
- **`POST_UPDATE_DONE`**: Duplicate update prevention
#### Data Variables
- **`CT_TYPE`**: Container type
- **`DISK_SIZE`**: Disk size
- **`CORE_COUNT`**: CPU core count
- **`RAM_SIZE`**: RAM size
- **`var_os`**: Operating system
- **`var_version`**: OS version
- **`DISABLEIP6`**: IPv6 setting
- **`NSAPP`**: Application namespace
- **`METHOD`**: Installation method
#### Internal Variables
- **`API_URL`**: API endpoint URL
- **`JSON_PAYLOAD`**: API request payload
- **`RESPONSE`**: API response
- **`DISK_SIZE_API`**: Processed disk size for VM API
## Integration Patterns
### Standard Integration Pattern
```bash
#!/usr/bin/env bash
# Standard integration pattern
# 1. Source core.func first
source core.func
# 2. Source api.func
source api.func
# 3. Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# 4. Set application parameters
export NSAPP="$APP"
export METHOD="install"
# 5. Report installation start
post_to_api
# 6. Perform installation
# ... installation logic ...
# 7. Report completion
post_update_to_api "success" 0
```
### Minimal Integration Pattern
```bash
#!/usr/bin/env bash
# Minimal integration pattern
source api.func
# Basic error reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# Report failure
post_update_to_api "failed" 127
```
### Advanced Integration Pattern
```bash
#!/usr/bin/env bash
# Advanced integration pattern
source core.func
source api.func
source error_handler.func
# Set up comprehensive API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export CT_TYPE=1
export DISK_SIZE=8
export CORE_COUNT=2
export RAM_SIZE=2048
export var_os="debian"
export var_version="12"
export METHOD="install"
# Enhanced error handling with API reporting
enhanced_error_handler() {
local exit_code=${1:-$?}
local command=${2:-${BASH_COMMAND:-unknown}}
local error_msg=$(get_error_description $exit_code)
echo "Error $exit_code: $error_msg"
post_update_to_api "failed" $exit_code
error_handler $exit_code $command
}
trap 'enhanced_error_handler' ERR
# Advanced operations with API reporting
post_to_api
# ... operations ...
post_update_to_api "success" 0
```
## Error Handling Integration
### Automatic Error Reporting
- **Error Descriptions**: Provides human-readable error messages
- **API Integration**: Reports errors to community-scripts.org API
- **Error Tracking**: Tracks error patterns for project improvement
- **Diagnostic Data**: Contributes to anonymous usage analytics
### Manual Error Reporting
- **Custom Error Codes**: Use appropriate error codes for different scenarios
- **Error Context**: Provide context information for errors
- **Status Updates**: Report both success and failure cases
- **Error Analysis**: Analyze error patterns and trends
### API Communication Errors
- **Network Failures**: Handle API communication failures gracefully
- **Missing Prerequisites**: Check prerequisites before API calls
- **Duplicate Prevention**: Prevent duplicate status updates
- **Error Recovery**: Handle API errors without blocking installation
## Performance Considerations
### API Communication Overhead
- **Minimal Impact**: API calls add minimal overhead
- **Asynchronous**: API calls don't block installation process
- **Error Handling**: API failures don't affect installation
- **Optional**: API reporting is optional and can be disabled
### Memory Usage
- **Minimal Footprint**: API functions use minimal memory
- **Variable Reuse**: Global variables reused across functions
- **No Memory Leaks**: Proper cleanup prevents memory leaks
- **Efficient Processing**: Efficient JSON payload creation
### Execution Speed
- **Fast API Calls**: Quick API communication
- **Efficient Error Processing**: Fast error code processing
- **Minimal Delay**: Minimal delay in API operations
- **Non-blocking**: API calls don't block installation
## Security Considerations
### Data Privacy
- **Anonymous Reporting**: Only anonymous data is sent
- **No Sensitive Data**: No sensitive information is transmitted
- **User Control**: Users can disable diagnostic reporting
- **Data Minimization**: Only necessary data is sent
### API Security
- **HTTPS**: API communication uses secure protocols
- **Data Validation**: API data is validated before sending
- **Error Handling**: API errors are handled securely
- **No Credentials**: No authentication credentials are sent
### Network Security
- **Secure Communication**: Uses secure HTTP protocols
- **Error Handling**: Network errors are handled gracefully
- **No Data Leakage**: No sensitive data is leaked
- **Secure Endpoints**: Uses trusted API endpoints
## Future Integration Considerations
### Extensibility
- **New API Endpoints**: Easy to add new API endpoints
- **Additional Data**: Easy to add new data fields
- **Error Codes**: Easy to add new error code descriptions
- **API Versions**: Easy to support new API versions
### Compatibility
- **API Versioning**: Compatible with different API versions
- **Data Format**: Compatible with different data formats
- **Error Codes**: Compatible with different error code systems
- **Network Protocols**: Compatible with different network protocols
### Performance
- **Optimization**: API communication can be optimized
- **Caching**: API responses can be cached
- **Batch Operations**: Multiple operations can be batched
- **Async Processing**: API calls can be made asynchronous

View File

@ -0,0 +1,794 @@
# api.func Usage Examples
## Overview
This document provides practical usage examples for `api.func` functions, covering common scenarios, integration patterns, and best practices.
## Basic API Setup
### Standard API Initialization
```bash
#!/usr/bin/env bash
# Standard API setup for LXC containers
source api.func
# Set up diagnostic reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# Set container parameters
export CT_TYPE=1
export DISK_SIZE=8
export CORE_COUNT=2
export RAM_SIZE=2048
export var_os="debian"
export var_version="12"
export NSAPP="plex"
export METHOD="install"
# Report installation start
post_to_api
# Your installation code here
# ... installation logic ...
# Report completion
if [[ $? -eq 0 ]]; then
post_update_to_api "success" 0
else
post_update_to_api "failed" $?
fi
```
### VM API Setup
```bash
#!/usr/bin/env bash
# API setup for VMs
source api.func
# Create diagnostics file for VM
mkdir -p /usr/local/community-scripts
echo "DIAGNOSTICS=yes" > /usr/local/community-scripts/diagnostics
# Set up VM parameters
export RANDOM_UUID="$(uuidgen)"
export DISK_SIZE="20G"
export CORE_COUNT=4
export RAM_SIZE=4096
export var_os="ubuntu"
export var_version="22.04"
export NSAPP="nextcloud"
export METHOD="install"
# Report VM installation start
post_to_api_vm
# Your VM installation code here
# ... VM creation logic ...
# Report completion
post_update_to_api "success" 0
```
## Error Description Examples
### Basic Error Explanation
```bash
#!/usr/bin/env bash
source api.func
# Explain common error codes
echo "Error 0: '$(get_error_description 0)'"
echo "Error 1: $(get_error_description 1)"
echo "Error 127: $(get_error_description 127)"
echo "Error 200: $(get_error_description 200)"
echo "Error 255: $(get_error_description 255)"
```
### Error Code Testing
```bash
#!/usr/bin/env bash
source api.func
# Test all error codes
test_error_codes() {
local codes=(0 1 2 127 128 130 137 139 143 200 203 205 255)
for code in "${codes[@]}"; do
echo "Code $code: $(get_error_description $code)"
done
}
test_error_codes
```
### Error Handling with Descriptions
```bash
#!/usr/bin/env bash
source api.func
# Function with error handling
run_command_with_error_handling() {
local command="$1"
local description="$2"
echo "Running: $description"
if $command; then
echo "Success: $description"
return 0
else
local exit_code=$?
local error_msg=$(get_error_description $exit_code)
echo "Error $exit_code: $error_msg"
return $exit_code
fi
}
# Usage
run_command_with_error_handling "apt-get update" "Package list update"
run_command_with_error_handling "nonexistent_command" "Test command"
```
## API Communication Examples
### LXC Installation Reporting
```bash
#!/usr/bin/env bash
source api.func
# Complete LXC installation with API reporting
install_lxc_with_reporting() {
local app="$1"
local ctid="$2"
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export CT_TYPE=1
export DISK_SIZE=10
export CORE_COUNT=2
export RAM_SIZE=2048
export var_os="debian"
export var_version="12"
export NSAPP="$app"
export METHOD="install"
# Report installation start
post_to_api
# Installation process
echo "Installing $app container (ID: $ctid)..."
# Simulate installation
sleep 2
# Check if installation succeeded
if [[ $? -eq 0 ]]; then
echo "Installation completed successfully"
post_update_to_api "success" 0
return 0
else
echo "Installation failed"
post_update_to_api "failed" $?
return 1
fi
}
# Install multiple containers
install_lxc_with_reporting "plex" "100"
install_lxc_with_reporting "nextcloud" "101"
install_lxc_with_reporting "nginx" "102"
```
### VM Installation Reporting
```bash
#!/usr/bin/env bash
source api.func
# Complete VM installation with API reporting
install_vm_with_reporting() {
local app="$1"
local vmid="$2"
# Create diagnostics file
mkdir -p /usr/local/community-scripts
echo "DIAGNOSTICS=yes" > /usr/local/community-scripts/diagnostics
# Set up API reporting
export RANDOM_UUID="$(uuidgen)"
export DISK_SIZE="20G"
export CORE_COUNT=4
export RAM_SIZE=4096
export var_os="ubuntu"
export var_version="22.04"
export NSAPP="$app"
export METHOD="install"
# Report VM installation start
post_to_api_vm
# VM installation process
echo "Installing $app VM (ID: $vmid)..."
# Simulate VM creation
sleep 3
# Check if VM creation succeeded
if [[ $? -eq 0 ]]; then
echo "VM installation completed successfully"
post_update_to_api "success" 0
return 0
else
echo "VM installation failed"
post_update_to_api "failed" $?
return 1
fi
}
# Install multiple VMs
install_vm_with_reporting "nextcloud" "200"
install_vm_with_reporting "wordpress" "201"
```
## Status Update Examples
### Success Reporting
```bash
#!/usr/bin/env bash
source api.func
# Report successful installation
report_success() {
local operation="$1"
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
echo "Reporting successful $operation"
post_update_to_api "success" 0
}
# Usage
report_success "container installation"
report_success "package installation"
report_success "service configuration"
```
### Failure Reporting
```bash
#!/usr/bin/env bash
source api.func
# Report failed installation
report_failure() {
local operation="$1"
local exit_code="$2"
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
local error_msg=$(get_error_description $exit_code)
echo "Reporting failed $operation: $error_msg"
post_update_to_api "failed" $exit_code
}
# Usage
report_failure "container creation" 200
report_failure "package installation" 127
report_failure "service start" 1
```
### Conditional Status Reporting
```bash
#!/usr/bin/env bash
source api.func
# Conditional status reporting
report_installation_status() {
local operation="$1"
local exit_code="$2"
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
if [[ $exit_code -eq 0 ]]; then
echo "Reporting successful $operation"
post_update_to_api "success" 0
else
local error_msg=$(get_error_description $exit_code)
echo "Reporting failed $operation: $error_msg"
post_update_to_api "failed" $exit_code
fi
}
# Usage
report_installation_status "container creation" 0
report_installation_status "package installation" 127
```
## Advanced Usage Examples
### Batch Installation with API Reporting
```bash
#!/usr/bin/env bash
source api.func
# Batch installation with comprehensive API reporting
batch_install_with_reporting() {
local apps=("plex" "nextcloud" "nginx" "mysql")
local ctids=(100 101 102 103)
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export CT_TYPE=1
export DISK_SIZE=8
export CORE_COUNT=2
export RAM_SIZE=2048
export var_os="debian"
export var_version="12"
export METHOD="install"
local success_count=0
local failure_count=0
for i in "${!apps[@]}"; do
local app="${apps[$i]}"
local ctid="${ctids[$i]}"
echo "Installing $app (ID: $ctid)..."
# Set app-specific parameters
export NSAPP="$app"
# Report installation start
post_to_api
# Simulate installation
if install_app "$app" "$ctid"; then
echo "$app installed successfully"
post_update_to_api "success" 0
((success_count++))
else
echo "$app installation failed"
post_update_to_api "failed" $?
((failure_count++))
fi
echo "---"
done
echo "Batch installation completed: $success_count successful, $failure_count failed"
}
# Mock installation function
install_app() {
local app="$1"
local ctid="$2"
# Simulate installation
sleep 1
# Simulate occasional failures
if [[ $((RANDOM % 10)) -eq 0 ]]; then
return 1
fi
return 0
}
batch_install_with_reporting
```
### Error Analysis and Reporting
```bash
#!/usr/bin/env bash
source api.func
# Analyze and report errors
analyze_and_report_errors() {
local log_file="$1"
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
if [[ ! -f "$log_file" ]]; then
echo "Log file not found: $log_file"
return 1
fi
# Extract error codes from log
local error_codes=$(grep -o 'exit code [0-9]\+' "$log_file" | grep -o '[0-9]\+' | sort -u)
if [[ -z "$error_codes" ]]; then
echo "No errors found in log"
post_update_to_api "success" 0
return 0
fi
echo "Found error codes: $error_codes"
# Report each unique error
for code in $error_codes; do
local error_msg=$(get_error_description $code)
echo "Error $code: $error_msg"
post_update_to_api "failed" $code
done
}
# Usage
analyze_and_report_errors "/var/log/installation.log"
```
### API Health Check
```bash
#!/usr/bin/env bash
source api.func
# Check API connectivity and functionality
check_api_health() {
echo "Checking API health..."
# Test prerequisites
if ! command -v curl >/dev/null 2>&1; then
echo "ERROR: curl not available"
return 1
fi
# Test error description function
local test_error=$(get_error_description 127)
if [[ -z "$test_error" ]]; then
echo "ERROR: Error description function not working"
return 1
fi
echo "Error description test: $test_error"
# Test API connectivity (without sending data)
local api_url="http://api.community-scripts.org/dev/upload"
if curl -s --head "$api_url" >/dev/null 2>&1; then
echo "API endpoint is reachable"
else
echo "WARNING: API endpoint not reachable"
fi
echo "API health check completed"
}
check_api_health
```
## Integration Examples
### With build.func
```bash
#!/usr/bin/env bash
# Integration with build.func
source core.func
source api.func
source build.func
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# Container creation with API reporting
create_container_with_reporting() {
local app="$1"
local ctid="$2"
# Set container parameters
export APP="$app"
export CTID="$ctid"
export var_hostname="${app}-server"
export var_os="debian"
export var_version="12"
export var_cpu="2"
export var_ram="2048"
export var_disk="10"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.$ctid"
export var_template_storage="local"
export var_container_storage="local"
# Report installation start
post_to_api
# Create container using build.func
if source build.func; then
echo "Container $app created successfully"
post_update_to_api "success" 0
return 0
else
echo "Container $app creation failed"
post_update_to_api "failed" $?
return 1
fi
}
# Create containers
create_container_with_reporting "plex" "100"
create_container_with_reporting "nextcloud" "101"
```
### With vm-core.func
```bash
#!/usr/bin/env bash
# Integration with vm-core.func
source core.func
source api.func
source vm-core.func
# Set up VM API reporting
mkdir -p /usr/local/community-scripts
echo "DIAGNOSTICS=yes" > /usr/local/community-scripts/diagnostics
export RANDOM_UUID="$(uuidgen)"
# VM creation with API reporting
create_vm_with_reporting() {
local app="$1"
local vmid="$2"
# Set VM parameters
export APP="$app"
export VMID="$vmid"
export var_hostname="${app}-vm"
export var_os="ubuntu"
export var_version="22.04"
export var_cpu="4"
export var_ram="4096"
export var_disk="20"
# Report VM installation start
post_to_api_vm
# Create VM using vm-core.func
if source vm-core.func; then
echo "VM $app created successfully"
post_update_to_api "success" 0
return 0
else
echo "VM $app creation failed"
post_update_to_api "failed" $?
return 1
fi
}
# Create VMs
create_vm_with_reporting "nextcloud" "200"
create_vm_with_reporting "wordpress" "201"
```
### With error_handler.func
```bash
#!/usr/bin/env bash
# Integration with error_handler.func
source core.func
source error_handler.func
source api.func
# Enhanced error handling with API reporting
enhanced_error_handler() {
local exit_code=${1:-$?}
local command=${2:-${BASH_COMMAND:-unknown}}
# Get error description from api.func
local error_msg=$(get_error_description $exit_code)
# Display error information
echo "Error $exit_code: $error_msg"
echo "Command: $command"
# Report error to API
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
post_update_to_api "failed" $exit_code
# Use standard error handler
error_handler $exit_code $command
}
# Set up enhanced error handling
trap 'enhanced_error_handler' ERR
# Test enhanced error handling
nonexistent_command
```
## Best Practices Examples
### Comprehensive API Integration
```bash
#!/usr/bin/env bash
# Comprehensive API integration example
source core.func
source api.func
# Set up comprehensive API reporting
setup_api_reporting() {
# Enable diagnostics
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# Set common parameters
export CT_TYPE=1
export DISK_SIZE=8
export CORE_COUNT=2
export RAM_SIZE=2048
export var_os="debian"
export var_version="12"
export METHOD="install"
echo "API reporting configured"
}
# Installation with comprehensive reporting
install_with_comprehensive_reporting() {
local app="$1"
local ctid="$2"
# Set up API reporting
setup_api_reporting
export NSAPP="$app"
# Report installation start
post_to_api
# Installation process
echo "Installing $app..."
# Simulate installation steps
local steps=("Downloading" "Installing" "Configuring" "Starting")
for step in "${steps[@]}"; do
echo "$step $app..."
sleep 1
done
# Check installation result
if [[ $? -eq 0 ]]; then
echo "$app installation completed successfully"
post_update_to_api "success" 0
return 0
else
echo "$app installation failed"
post_update_to_api "failed" $?
return 1
fi
}
# Install multiple applications
apps=("plex" "nextcloud" "nginx" "mysql")
ctids=(100 101 102 103)
for i in "${!apps[@]}"; do
install_with_comprehensive_reporting "${apps[$i]}" "${ctids[$i]}"
echo "---"
done
```
### Error Recovery with API Reporting
```bash
#!/usr/bin/env bash
source api.func
# Error recovery with API reporting
retry_with_api_reporting() {
local operation="$1"
local max_attempts=3
local attempt=1
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
while [[ $attempt -le $max_attempts ]]; do
echo "Attempt $attempt of $max_attempts: $operation"
if $operation; then
echo "Operation succeeded on attempt $attempt"
post_update_to_api "success" 0
return 0
else
local exit_code=$?
local error_msg=$(get_error_description $exit_code)
echo "Attempt $attempt failed: $error_msg"
post_update_to_api "failed" $exit_code
((attempt++))
if [[ $attempt -le $max_attempts ]]; then
echo "Retrying in 5 seconds..."
sleep 5
fi
fi
done
echo "Operation failed after $max_attempts attempts"
return 1
}
# Usage
retry_with_api_reporting "apt-get update"
retry_with_api_reporting "apt-get install -y package"
```
### API Reporting with Logging
```bash
#!/usr/bin/env bash
source api.func
# API reporting with detailed logging
install_with_logging_and_api() {
local app="$1"
local log_file="/var/log/${app}_installation.log"
# Set up API reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
export NSAPP="$app"
# Start logging
exec > >(tee -a "$log_file")
exec 2>&1
echo "Starting $app installation at $(date)"
# Report installation start
post_to_api
# Installation process
echo "Installing $app..."
# Simulate installation
if install_app "$app"; then
echo "$app installation completed successfully at $(date)"
post_update_to_api "success" 0
return 0
else
local exit_code=$?
local error_msg=$(get_error_description $exit_code)
echo "$app installation failed at $(date): $error_msg"
post_update_to_api "failed" $exit_code
return $exit_code
fi
}
# Mock installation function
install_app() {
local app="$1"
echo "Installing $app..."
sleep 2
return 0
}
# Install with logging and API reporting
install_with_logging_and_api "plex"
```

View File

@ -0,0 +1,199 @@
# api.func Documentation
## Overview
The `api.func` file provides Proxmox API integration and diagnostic reporting functionality for the Community Scripts project. It handles API communication, error reporting, and status updates to the community-scripts.org API.
## Purpose and Use Cases
- **API Communication**: Send installation and status data to community-scripts.org API
- **Diagnostic Reporting**: Report installation progress and errors for analytics
- **Error Description**: Provide detailed error code explanations
- **Status Updates**: Track installation success/failure status
- **Analytics**: Contribute anonymous usage data for project improvement
## Quick Reference
### Key Function Groups
- **Error Handling**: `get_error_description()` - Convert exit codes to human-readable messages
- **API Communication**: `post_to_api()`, `post_to_api_vm()` - Send installation data
- **Status Updates**: `post_update_to_api()` - Report installation completion status
### Dependencies
- **External**: `curl` command for HTTP requests
- **Internal**: Uses environment variables from other scripts
### Integration Points
- Used by: All installation scripts for diagnostic reporting
- Uses: Environment variables from build.func and other scripts
- Provides: API communication and error reporting services
## Documentation Files
### 📊 [API_FLOWCHART.md](./API_FLOWCHART.md)
Visual execution flows showing API communication processes and error handling.
### 📚 [API_FUNCTIONS_REFERENCE.md](./API_FUNCTIONS_REFERENCE.md)
Complete alphabetical reference of all functions with parameters, dependencies, and usage details.
### 💡 [API_USAGE_EXAMPLES.md](./API_USAGE_EXAMPLES.md)
Practical examples showing how to use API functions and common patterns.
### 🔗 [API_INTEGRATION.md](./API_INTEGRATION.md)
How api.func integrates with other components and provides API services.
## Key Features
### Error Code Descriptions
- **Comprehensive Coverage**: 50+ error codes with detailed explanations
- **LXC-Specific Errors**: Container creation and management errors
- **System Errors**: General system and network errors
- **Signal Errors**: Process termination and signal errors
### API Communication
- **LXC Reporting**: Send LXC container installation data
- **VM Reporting**: Send VM installation data
- **Status Updates**: Report installation success/failure
- **Diagnostic Data**: Anonymous usage analytics
### Diagnostic Integration
- **Optional Reporting**: Only sends data when diagnostics enabled
- **Privacy Respect**: Respects user privacy settings
- **Error Tracking**: Tracks installation errors for improvement
- **Usage Analytics**: Contributes to project statistics
## Common Usage Patterns
### Basic API Setup
```bash
#!/usr/bin/env bash
# Basic API setup
source api.func
# Set up diagnostic reporting
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
# Report installation start
post_to_api
```
### Error Reporting
```bash
#!/usr/bin/env bash
source api.func
# Get error description
error_msg=$(get_error_description 127)
echo "Error 127: $error_msg"
# Output: Error 127: Command not found: Incorrect path or missing dependency.
```
### Status Updates
```bash
#!/usr/bin/env bash
source api.func
# Report successful installation
post_update_to_api "success" 0
# Report failed installation
post_update_to_api "failed" 127
```
## Environment Variables
### Required Variables
- `DIAGNOSTICS`: Enable/disable diagnostic reporting ("yes"/"no")
- `RANDOM_UUID`: Unique identifier for tracking
### Optional Variables
- `CT_TYPE`: Container type (1 for LXC, 2 for VM)
- `DISK_SIZE`: Disk size in GB
- `CORE_COUNT`: Number of CPU cores
- `RAM_SIZE`: RAM size in MB
- `var_os`: Operating system type
- `var_version`: OS version
- `DISABLEIP6`: IPv6 disable setting
- `NSAPP`: Namespace application name
- `METHOD`: Installation method
### Internal Variables
- `POST_UPDATE_DONE`: Prevents duplicate status updates
- `API_URL`: Community scripts API endpoint
- `JSON_PAYLOAD`: API request payload
- `RESPONSE`: API response
## Error Code Categories
### General System Errors
- **0-9**: Basic system errors
- **18, 22, 28, 35**: Network and I/O errors
- **56, 60**: TLS/SSL errors
- **125-128**: Command execution errors
- **129-143**: Signal errors
- **152**: Resource limit errors
- **255**: Unknown critical errors
### LXC-Specific Errors
- **100-101**: LXC installation errors
- **200-209**: LXC creation and management errors
### Docker Errors
- **125**: Docker container start errors
## Best Practices
### Diagnostic Reporting
1. Always check if diagnostics are enabled
2. Respect user privacy settings
3. Use unique identifiers for tracking
4. Report both success and failure cases
### Error Handling
1. Use appropriate error codes
2. Provide meaningful error descriptions
3. Handle API communication failures gracefully
4. Don't block installation on API failures
### API Usage
1. Check for curl availability
2. Handle network failures gracefully
3. Use appropriate HTTP methods
4. Include all required data
## Troubleshooting
### Common Issues
1. **API Communication Fails**: Check network connectivity and curl availability
2. **Diagnostics Not Working**: Verify DIAGNOSTICS setting and RANDOM_UUID
3. **Missing Error Descriptions**: Check error code coverage
4. **Duplicate Updates**: POST_UPDATE_DONE prevents duplicates
### Debug Mode
Enable diagnostic reporting for debugging:
```bash
export DIAGNOSTICS="yes"
export RANDOM_UUID="$(uuidgen)"
```
### API Testing
Test API communication:
```bash
source api.func
export DIAGNOSTICS="yes"
export RANDOM_UUID="test-$(date +%s)"
post_to_api
```
## Related Documentation
- [core.func](../core.func/) - Core utilities and error handling
- [error_handler.func](../error_handler.func/) - Error handling utilities
- [build.func](../build.func/) - Container creation with API integration
- [tools.func](../tools.func/) - Extended utilities with API integration
---
*This documentation covers the api.func file which provides API communication and diagnostic reporting for all Proxmox Community Scripts.*

View File

@ -0,0 +1,410 @@
# build.func Architecture Guide
## Overview
This document provides a high-level architectural overview of `build.func`, including module dependencies, data flow, integration points, and system architecture.
## High-Level Architecture
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Proxmox Host System │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ build.func │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────────────┐ │ │
│ │ │ Entry Point │ │ Configuration │ │ Container Creation │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ • start() │ │ • variables() │ │ • build_container() │ │ │
│ │ │ • install_ │ │ • base_ │ │ • create_lxc_container() │ │ │
│ │ │ script() │ │ settings() │ │ • configure_gpu_ │ │ │
│ │ │ • advanced_ │ │ • select_ │ │ passthrough() │ │ │
│ │ │ settings() │ │ storage() │ │ • fix_gpu_gids() │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Module Dependencies │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────────────┐ │ │
│ │ │ core.func │ │ error_handler. │ │ api.func │ │ │
│ │ │ │ │ func │ │ │ │ │
│ │ │ • Basic │ │ • Error │ │ • Proxmox API │ │ │
│ │ │ utilities │ │ handling │ │ interactions │ │ │
│ │ │ • Common │ │ • Error │ │ • Container │ │ │
│ │ │ functions │ │ recovery │ │ management │ │ │
│ │ │ • System │ │ • Cleanup │ │ • Status │ │ │
│ │ │ utilities │ │ functions │ │ monitoring │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────────────┘ │ │
│ │ │ │
│ │ ┌─────────────────────────────────────────────────────────────────────────┐ │ │
│ │ │ tools.func │ │ │
│ │ │ │ │ │
│ │ │ • Additional utilities │ │ │
│ │ │ • Helper functions │ │ │
│ │ │ • System tools │ │ │
│ │ └─────────────────────────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## Module Dependencies
### Core Dependencies
```
build.func Dependencies:
├── core.func
│ ├── Basic system utilities
│ ├── Common functions
│ ├── System information
│ └── File operations
├── error_handler.func
│ ├── Error handling
│ ├── Error recovery
│ ├── Cleanup functions
│ └── Error logging
├── api.func
│ ├── Proxmox API interactions
│ ├── Container management
│ ├── Status monitoring
│ └── Configuration updates
└── tools.func
├── Additional utilities
├── Helper functions
├── System tools
└── Custom functions
```
### Dependency Flow
```
Dependency Flow:
├── build.func
│ ├── Sources core.func
│ ├── Sources error_handler.func
│ ├── Sources api.func
│ └── Sources tools.func
├── core.func
│ ├── Basic utilities
│ └── System functions
├── error_handler.func
│ ├── Error management
│ └── Recovery functions
├── api.func
│ ├── Proxmox integration
│ └── Container operations
└── tools.func
├── Additional tools
└── Helper functions
```
## Data Flow Architecture
### Configuration Data Flow
```
Configuration Data Flow:
├── Environment Variables
│ ├── Hard environment variables
│ ├── App-specific .vars
│ ├── Global default.vars
│ └── Built-in defaults
├── Variable Resolution
│ ├── Apply precedence chain
│ ├── Validate settings
│ └── Resolve conflicts
├── Configuration Storage
│ ├── Memory variables
│ ├── Temporary files
│ └── Persistent storage
└── Configuration Usage
├── Container creation
├── Feature configuration
└── Settings persistence
```
### Container Data Flow
```
Container Data Flow:
├── Input Data
│ ├── Configuration variables
│ ├── Resource specifications
│ ├── Network settings
│ └── Storage requirements
├── Processing
│ ├── Validation
│ ├── Conflict resolution
│ ├── Resource allocation
│ └── Configuration generation
├── Container Creation
│ ├── LXC container creation
│ ├── Network configuration
│ ├── Storage setup
│ └── Feature configuration
└── Output
├── Container status
├── Access information
├── Configuration files
└── Log files
```
## Integration Architecture
### With Proxmox System
```
Proxmox Integration:
├── Proxmox Host
│ ├── LXC container management
│ ├── Storage management
│ ├── Network management
│ └── Resource management
├── Proxmox API
│ ├── Container operations
│ ├── Configuration updates
│ ├── Status monitoring
│ └── Error handling
├── Proxmox Configuration
│ ├── /etc/pve/lxc/<ctid>.conf
│ ├── Storage configuration
│ ├── Network configuration
│ └── Resource configuration
└── Proxmox Services
├── Container services
├── Network services
├── Storage services
└── Monitoring services
```
### With Install Scripts
```
Install Script Integration:
├── build.func
│ ├── Creates container
│ ├── Configures basic settings
│ ├── Starts container
│ └── Provides access
├── Install Scripts
│ ├── <app>-install.sh
│ ├── Downloads application
│ ├── Configures application
│ └── Sets up services
├── Container
│ ├── Running application
│ ├── Configured services
│ ├── Network access
│ └── Storage access
└── Integration Points
├── Container creation
├── Network configuration
├── Storage setup
└── Service configuration
```
## System Architecture Components
### Core Components
```
System Components:
├── Entry Point
│ ├── start() function
│ ├── Context detection
│ ├── Environment capture
│ └── Workflow routing
├── Configuration Management
│ ├── Variable resolution
│ ├── Settings persistence
│ ├── Default management
│ └── Validation
├── Container Creation
│ ├── LXC container creation
│ ├── Network configuration
│ ├── Storage setup
│ └── Feature configuration
├── Hardware Integration
│ ├── GPU passthrough
│ ├── USB passthrough
│ ├── Storage management
│ └── Network management
└── Error Handling
├── Error detection
├── Error recovery
├── Cleanup functions
└── User notification
```
### User Interface Components
```
UI Components:
├── Menu System
│ ├── Installation mode selection
│ ├── Configuration menus
│ ├── Storage selection
│ └── GPU configuration
├── Interactive Elements
│ ├── Whiptail menus
│ ├── User prompts
│ ├── Confirmation dialogs
│ └── Error messages
├── Non-Interactive Mode
│ ├── Environment variable driven
│ ├── Silent execution
│ ├── Automated configuration
│ └── Error handling
└── Output
├── Status messages
├── Progress indicators
├── Completion information
└── Access details
```
## Security Architecture
### Security Considerations
```
Security Architecture:
├── Container Security
│ ├── Unprivileged containers (default)
│ ├── Privileged containers (when needed)
│ ├── Resource limits
│ └── Access controls
├── Network Security
│ ├── Network isolation
│ ├── VLAN support
│ ├── Firewall integration
│ └── Access controls
├── Storage Security
│ ├── Storage isolation
│ ├── Access controls
│ ├── Encryption support
│ └── Backup integration
├── GPU Security
│ ├── Device isolation
│ ├── Permission management
│ ├── Access controls
│ └── Security validation
└── API Security
├── Authentication
├── Authorization
├── Input validation
└── Error handling
```
## Performance Architecture
### Performance Considerations
```
Performance Architecture:
├── Execution Optimization
│ ├── Parallel operations
│ ├── Efficient algorithms
│ ├── Minimal user interaction
│ └── Optimized validation
├── Resource Management
│ ├── Memory efficiency
│ ├── CPU optimization
│ ├── Disk usage optimization
│ └── Network efficiency
├── Caching
│ ├── Configuration caching
│ ├── Template caching
│ ├── Storage caching
│ └── GPU detection caching
└── Monitoring
├── Performance monitoring
├── Resource monitoring
├── Error monitoring
└── Status monitoring
```
## Deployment Architecture
### Deployment Scenarios
```
Deployment Scenarios:
├── Single Container
│ ├── Individual application
│ ├── Standard configuration
│ ├── Basic networking
│ └── Standard storage
├── Multiple Containers
│ ├── Application stack
│ ├── Shared networking
│ ├── Shared storage
│ └── Coordinated deployment
├── High Availability
│ ├── Redundant containers
│ ├── Load balancing
│ ├── Failover support
│ └── Monitoring integration
└── Development Environment
├── Development containers
├── Testing containers
├── Staging containers
└── Production containers
```
## Maintenance Architecture
### Maintenance Components
```
Maintenance Architecture:
├── Updates
│ ├── Container updates
│ ├── Application updates
│ ├── Configuration updates
│ └── Security updates
├── Monitoring
│ ├── Container monitoring
│ ├── Resource monitoring
│ ├── Performance monitoring
│ └── Error monitoring
├── Backup
│ ├── Configuration backup
│ ├── Container backup
│ ├── Storage backup
│ └── Recovery procedures
└── Troubleshooting
├── Error diagnosis
├── Log analysis
├── Performance analysis
└── Recovery procedures
```
## Future Architecture Considerations
### Scalability
```
Scalability Considerations:
├── Horizontal Scaling
│ ├── Multiple containers
│ ├── Load balancing
│ ├── Distributed deployment
│ └── Resource distribution
├── Vertical Scaling
│ ├── Resource scaling
│ ├── Performance optimization
│ ├── Capacity planning
│ └── Resource management
├── Automation
│ ├── Automated deployment
│ ├── Automated scaling
│ ├── Automated monitoring
│ └── Automated recovery
└── Integration
├── External systems
├── Cloud integration
├── Container orchestration
└── Service mesh
```

View File

@ -0,0 +1,248 @@
# build.func Environment Variables Reference
## Overview
This document provides a comprehensive reference of all environment variables used in `build.func`, organized by category and usage context.
## Variable Categories
### Core Container Variables
| Variable | Description | Default | Set In | Used In |
|----------|-------------|---------|---------|---------|
| `APP` | Application name (e.g., "plex", "nextcloud") | - | Environment | Throughout |
| `NSAPP` | Namespace application name | `$APP` | Environment | Throughout |
| `CTID` | Container ID | - | Environment | Container creation |
| `CT_TYPE` | Container type ("install" or "update") | "install" | Environment | Entry point |
| `CT_NAME` | Container name | `$APP` | Environment | Container creation |
### Operating System Variables
| Variable | Description | Default | Set In | Used In |
|----------|-------------|---------|---------|---------|
| `var_os` | Operating system selection | "debian" | base_settings() | OS selection |
| `var_version` | OS version | "12" | base_settings() | Template selection |
| `var_template` | Template name | Auto-generated | base_settings() | Template download |
### Resource Configuration Variables
| Variable | Description | Default | Set In | Used In |
|----------|-------------|---------|---------|---------|
| `var_cpu` | CPU cores | "2" | base_settings() | Container creation |
| `var_ram` | RAM in MB | "2048" | base_settings() | Container creation |
| `var_disk` | Disk size in GB | "8" | base_settings() | Container creation |
| `DISK_SIZE` | Disk size (alternative) | `$var_disk` | Environment | Container creation |
| `CORE_COUNT` | CPU cores (alternative) | `$var_cpu` | Environment | Container creation |
| `RAM_SIZE` | RAM size (alternative) | `$var_ram` | Environment | Container creation |
### Network Configuration Variables
| Variable | Description | Default | Set In | Used In |
|----------|-------------|---------|---------|---------|
| `var_net` | Network interface | "vmbr0" | base_settings() | Network config |
| `var_bridge` | Bridge interface | "vmbr0" | base_settings() | Network config |
| `var_gateway` | Gateway IP | "192.168.1.1" | base_settings() | Network config |
| `var_ip` | Container IP address | - | User input | Network config |
| `var_ipv6` | IPv6 address | - | User input | Network config |
| `var_vlan` | VLAN ID | - | User input | Network config |
| `var_mtu` | MTU size | "1500" | base_settings() | Network config |
| `var_mac` | MAC address | Auto-generated | base_settings() | Network config |
| `NET` | Network interface (alternative) | `$var_net` | Environment | Network config |
| `BRG` | Bridge interface (alternative) | `$var_bridge` | Environment | Network config |
| `GATE` | Gateway IP (alternative) | `$var_gateway` | Environment | Network config |
| `IPV6_METHOD` | IPv6 configuration method | "none" | Environment | Network config |
| `VLAN` | VLAN ID (alternative) | `$var_vlan` | Environment | Network config |
| `MTU` | MTU size (alternative) | `$var_mtu` | Environment | Network config |
| `MAC` | MAC address (alternative) | `$var_mac` | Environment | Network config |
### Storage Configuration Variables
| Variable | Description | Default | Set In | Used In |
|----------|-------------|---------|---------|---------|
| `var_template_storage` | Storage for templates | - | select_storage() | Template storage |
| `var_container_storage` | Storage for container disks | - | select_storage() | Container storage |
| `TEMPLATE_STORAGE` | Template storage (alternative) | `$var_template_storage` | Environment | Template storage |
| `CONTAINER_STORAGE` | Container storage (alternative) | `$var_container_storage` | Environment | Container storage |
### Feature Flags
| Variable | Description | Default | Set In | Used In |
|----------|-------------|---------|---------|---------|
| `ENABLE_FUSE` | Enable FUSE support | "true" | base_settings() | Container features |
| `ENABLE_TUN` | Enable TUN/TAP support | "true" | base_settings() | Container features |
| `ENABLE_KEYCTL` | Enable keyctl support | "true" | base_settings() | Container features |
| `ENABLE_MOUNT` | Enable mount support | "true" | base_settings() | Container features |
| `ENABLE_NESTING` | Enable nesting support | "false" | base_settings() | Container features |
| `ENABLE_PRIVILEGED` | Enable privileged mode | "false" | base_settings() | Container features |
| `ENABLE_UNPRIVILEGED` | Enable unprivileged mode | "true" | base_settings() | Container features |
| `VERBOSE` | Enable verbose output | "false" | Environment | Logging |
| `SSH` | Enable SSH key provisioning | "true" | base_settings() | SSH setup |
### GPU Passthrough Variables
| Variable | Description | Default | Set In | Used In |
|----------|-------------|---------|---------|---------|
| `GPU_APPS` | List of apps that support GPU | - | Environment | GPU detection |
| `var_gpu` | GPU selection | - | User input | GPU passthrough |
| `var_gpu_type` | GPU type (intel/amd/nvidia) | - | detect_gpu_devices() | GPU passthrough |
| `var_gpu_devices` | GPU device list | - | detect_gpu_devices() | GPU passthrough |
### API and Diagnostics Variables
| Variable | Description | Default | Set In | Used In |
|----------|-------------|---------|---------|---------|
| `DIAGNOSTICS` | Enable diagnostics mode | "false" | Environment | Diagnostics |
| `METHOD` | Installation method | "install" | Environment | Installation flow |
| `RANDOM_UUID` | Random UUID for tracking | - | Environment | Logging |
| `API_TOKEN` | Proxmox API token | - | Environment | API calls |
| `API_USER` | Proxmox API user | - | Environment | API calls |
### Settings Persistence Variables
| Variable | Description | Default | Set In | Used In |
|----------|-------------|---------|---------|---------|
| `SAVE_DEFAULTS` | Save settings as defaults | "false" | User input | Settings persistence |
| `SAVE_APP_DEFAULTS` | Save app-specific defaults | "false" | User input | Settings persistence |
| `DEFAULT_VARS_FILE` | Path to default.vars | "/usr/local/community-scripts/default.vars" | Environment | Settings persistence |
| `APP_DEFAULTS_FILE` | Path to app.vars | "/usr/local/community-scripts/defaults/$APP.vars" | Environment | Settings persistence |
## Variable Precedence Chain
Variables are resolved in the following order (highest to lowest priority):
1. **Hard Environment Variables**: Set before script execution
2. **App-specific .vars file**: `/usr/local/community-scripts/defaults/<app>.vars`
3. **Global default.vars file**: `/usr/local/community-scripts/default.vars`
4. **Built-in defaults**: Set in `base_settings()` function
## Critical Variables for Non-Interactive Use
For silent/non-interactive execution, these variables must be set:
```bash
# Core container settings
export APP="plex"
export CTID="100"
export var_hostname="plex-server"
# OS selection
export var_os="debian"
export var_version="12"
# Resource allocation
export var_cpu="4"
export var_ram="4096"
export var_disk="20"
# Network configuration
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.100"
# Storage selection
export var_template_storage="local"
export var_container_storage="local"
# Feature flags
export ENABLE_FUSE="true"
export ENABLE_TUN="true"
export SSH="true"
```
## Environment Variable Usage Patterns
### 1. Container Creation
```bash
# Basic container creation
export APP="nextcloud"
export CTID="101"
export var_hostname="nextcloud-server"
export var_os="debian"
export var_version="12"
export var_cpu="2"
export var_ram="2048"
export var_disk="10"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.101"
export var_template_storage="local"
export var_container_storage="local"
```
### 2. GPU Passthrough
```bash
# Enable GPU passthrough
export GPU_APPS="plex,jellyfin,emby"
export var_gpu="intel"
export ENABLE_PRIVILEGED="true"
```
### 3. Advanced Network Configuration
```bash
# VLAN and IPv6 configuration
export var_vlan="100"
export var_ipv6="2001:db8::100"
export IPV6_METHOD="static"
export var_mtu="9000"
```
### 4. Storage Configuration
```bash
# Custom storage locations
export var_template_storage="nfs-storage"
export var_container_storage="ssd-storage"
```
## Variable Validation
The script validates variables at several points:
1. **Container ID validation**: Must be unique and within valid range
2. **IP address validation**: Must be valid IPv4/IPv6 format
3. **Storage validation**: Must exist and support required content types
4. **Resource validation**: Must be within reasonable limits
5. **Network validation**: Must be valid network configuration
## Common Variable Combinations
### Development Container
```bash
export APP="dev-container"
export CTID="200"
export var_hostname="dev-server"
export var_os="ubuntu"
export var_version="22.04"
export var_cpu="4"
export var_ram="4096"
export var_disk="20"
export ENABLE_NESTING="true"
export ENABLE_PRIVILEGED="true"
```
### Media Server with GPU
```bash
export APP="plex"
export CTID="300"
export var_hostname="plex-server"
export var_os="debian"
export var_version="12"
export var_cpu="6"
export var_ram="8192"
export var_disk="50"
export GPU_APPS="plex"
export var_gpu="nvidia"
export ENABLE_PRIVILEGED="true"
```
### Lightweight Service
```bash
export APP="nginx"
export CTID="400"
export var_hostname="nginx-proxy"
export var_os="alpine"
export var_version="3.18"
export var_cpu="1"
export var_ram="512"
export var_disk="2"
export ENABLE_UNPRIVILEGED="true"
```

View File

@ -0,0 +1,413 @@
# build.func Execution Flows
## Overview
This document details the execution flows for different installation modes and scenarios in `build.func`, including variable precedence, decision trees, and workflow patterns.
## Installation Modes
### 1. Default Install Flow
**Purpose**: Uses built-in defaults with minimal user interaction
**Use Case**: Quick container creation with standard settings
```
Default Install Flow:
├── start()
│ ├── Detect execution context
│ ├── Capture hard environment variables
│ └── Set CT_TYPE="install"
├── install_script()
│ ├── Display installation mode menu
│ ├── User selects "Default Install"
│ └── Proceed with defaults
├── variables()
│ ├── base_settings() # Set built-in defaults
│ ├── Load app.vars (if exists)
│ ├── Load default.vars (if exists)
│ └── Apply variable precedence
├── build_container()
│ ├── validate_settings()
│ ├── check_conflicts()
│ └── create_lxc_container()
└── default_var_settings()
└── Offer to save as defaults
```
**Key Characteristics**:
- Minimal user prompts
- Uses built-in defaults
- Fast execution
- Suitable for standard deployments
### 2. Advanced Install Flow
**Purpose**: Full interactive configuration via whiptail menus
**Use Case**: Custom container configuration with full control
```
Advanced Install Flow:
├── start()
│ ├── Detect execution context
│ ├── Capture hard environment variables
│ └── Set CT_TYPE="install"
├── install_script()
│ ├── Display installation mode menu
│ ├── User selects "Advanced Install"
│ └── Proceed with advanced configuration
├── variables()
│ ├── base_settings() # Set built-in defaults
│ ├── Load app.vars (if exists)
│ ├── Load default.vars (if exists)
│ └── Apply variable precedence
├── advanced_settings()
│ ├── OS Selection Menu
│ ├── Resource Configuration Menu
│ ├── Network Configuration Menu
│ ├── select_storage()
│ │ ├── resolve_storage_preselect()
│ │ └── choose_and_set_storage_for_file()
│ ├── GPU Configuration Menu
│ │ └── detect_gpu_devices()
│ └── Feature Flags Menu
├── build_container()
│ ├── validate_settings()
│ ├── check_conflicts()
│ └── create_lxc_container()
└── default_var_settings()
└── Offer to save as defaults
```
**Key Characteristics**:
- Full interactive configuration
- Whiptail menus for all options
- Complete control over settings
- Suitable for custom deployments
### 3. My Defaults Flow
**Purpose**: Loads settings from global default.vars file
**Use Case**: Using previously saved global defaults
```
My Defaults Flow:
├── start()
│ ├── Detect execution context
│ ├── Capture hard environment variables
│ └── Set CT_TYPE="install"
├── install_script()
│ ├── Display installation mode menu
│ ├── User selects "My Defaults"
│ └── Proceed with loaded defaults
├── variables()
│ ├── base_settings() # Set built-in defaults
│ ├── Load app.vars (if exists)
│ ├── Load default.vars # Load global defaults
│ └── Apply variable precedence
├── build_container()
│ ├── validate_settings()
│ ├── check_conflicts()
│ └── create_lxc_container()
└── default_var_settings()
└── Offer to save as defaults
```
**Key Characteristics**:
- Uses global default.vars file
- Minimal user interaction
- Consistent with previous settings
- Suitable for repeated deployments
### 4. App Defaults Flow
**Purpose**: Loads settings from app-specific .vars file
**Use Case**: Using previously saved app-specific defaults
```
App Defaults Flow:
├── start()
│ ├── Detect execution context
│ ├── Capture hard environment variables
│ └── Set CT_TYPE="install"
├── install_script()
│ ├── Display installation mode menu
│ ├── User selects "App Defaults"
│ └── Proceed with app-specific defaults
├── variables()
│ ├── base_settings() # Set built-in defaults
│ ├── Load app.vars # Load app-specific defaults
│ ├── Load default.vars (if exists)
│ └── Apply variable precedence
├── build_container()
│ ├── validate_settings()
│ ├── check_conflicts()
│ └── create_lxc_container()
└── default_var_settings()
└── Offer to save as defaults
```
**Key Characteristics**:
- Uses app-specific .vars file
- Minimal user interaction
- App-optimized settings
- Suitable for app-specific deployments
## Variable Precedence Chain
### Precedence Order (Highest to Lowest)
1. **Hard Environment Variables**: Set before script execution
2. **App-specific .vars file**: `/usr/local/community-scripts/defaults/<app>.vars`
3. **Global default.vars file**: `/usr/local/community-scripts/default.vars`
4. **Built-in defaults**: Set in `base_settings()` function
### Variable Resolution Process
```
Variable Resolution:
├── Capture hard environment variables at start()
├── Load built-in defaults in base_settings()
├── Load global default.vars (if exists)
├── Load app-specific .vars (if exists)
└── Apply precedence chain
├── Hard env vars override all
├── App.vars override default.vars and built-ins
├── Default.vars override built-ins
└── Built-ins are fallback defaults
```
## Storage Selection Logic
### Storage Resolution Flow
```
Storage Selection:
├── Check if storage is preselected
│ ├── var_template_storage set? → Validate and use
│ └── var_container_storage set? → Validate and use
├── Count available storage options
│ ├── Only 1 option → Auto-select
│ └── Multiple options → Prompt user
├── User selection via whiptail
│ ├── Template storage selection
│ └── Container storage selection
└── Validate selected storage
├── Check availability
├── Check content type support
└── Proceed with selection
```
### Storage Validation
```
Storage Validation:
├── Check storage exists
├── Check storage is online
├── Check content type support
│ ├── Template storage: vztmpl support
│ └── Container storage: rootdir support
├── Check available space
└── Validate permissions
```
## GPU Passthrough Flow
### GPU Detection and Configuration
```
GPU Passthrough Flow:
├── detect_gpu_devices()
│ ├── Scan for Intel GPUs
│ │ ├── Check i915 driver
│ │ └── Detect devices
│ ├── Scan for AMD GPUs
│ │ ├── Check AMDGPU driver
│ │ └── Detect devices
│ └── Scan for NVIDIA GPUs
│ ├── Check NVIDIA driver
│ ├── Detect devices
│ └── Check CUDA support
├── Check GPU passthrough eligibility
│ ├── Is app in GPU_APPS list?
│ ├── Is container privileged?
│ └── Proceed if eligible
├── GPU selection logic
│ ├── Single GPU type → Auto-select
│ └── Multiple GPU types → Prompt user
├── configure_gpu_passthrough()
│ ├── Add GPU device entries
│ ├── Configure permissions
│ └── Update container config
└── fix_gpu_gids()
├── Update GPU group IDs
└── Configure access permissions
```
### GPU Eligibility Check
```
GPU Eligibility:
├── Check app support
│ ├── Is APP in GPU_APPS list?
│ └── Proceed if supported
├── Check container privileges
│ ├── Is ENABLE_PRIVILEGED="true"?
│ └── Proceed if privileged
└── Check hardware availability
├── Are GPUs detected?
└── Proceed if available
```
## Network Configuration Flow
### Network Setup Process
```
Network Configuration:
├── Basic network settings
│ ├── var_net (network interface)
│ ├── var_bridge (bridge interface)
│ └── var_gateway (gateway IP)
├── IP configuration
│ ├── var_ip (IPv4 address)
│ ├── var_ipv6 (IPv6 address)
│ └── IPV6_METHOD (IPv6 method)
├── Advanced network settings
│ ├── var_vlan (VLAN ID)
│ ├── var_mtu (MTU size)
│ └── var_mac (MAC address)
└── Network validation
├── Check IP format
├── Check gateway reachability
└── Validate network configuration
```
## Container Creation Flow
### LXC Container Creation Process
```
Container Creation:
├── create_lxc_container()
│ ├── Create basic container
│ ├── Configure network
│ ├── Set up storage
│ ├── Configure features
│ ├── Set resource limits
│ ├── Configure startup
│ └── Start container
├── Post-creation configuration
│ ├── Wait for network
│ ├── Configure GPU (if enabled)
│ ├── Set up SSH keys
│ └── Run post-install scripts
└── Finalization
├── Display container info
├── Show access details
└── Provide next steps
```
## Error Handling Flows
### Validation Error Flow
```
Validation Error Flow:
├── validate_settings()
│ ├── Check configuration validity
│ └── Return error if invalid
├── check_conflicts()
│ ├── Check for conflicts
│ └── Return error if conflicts found
├── Error handling
│ ├── Display error message
│ ├── cleanup_on_error()
│ └── Exit with error code
└── User notification
├── Show error details
└── Suggest fixes
```
### Storage Error Flow
```
Storage Error Flow:
├── Storage selection fails
├── Retry storage selection
│ ├── Show available options
│ └── Allow user to retry
├── Storage validation fails
│ ├── Show validation errors
│ └── Allow user to fix
└── Fallback to default storage
├── Use fallback storage
└── Continue with creation
```
### GPU Error Flow
```
GPU Error Flow:
├── GPU detection fails
├── Fall back to no GPU
│ ├── Disable GPU passthrough
│ └── Continue without GPU
├── GPU configuration fails
│ ├── Show configuration errors
│ └── Allow user to retry
└── GPU permission errors
├── Fix GPU permissions
└── Retry configuration
```
## Integration Flows
### With Install Scripts
```
Install Script Integration:
├── build.func creates container
├── Container starts successfully
├── Install script execution
│ ├── Download and install app
│ ├── Configure app settings
│ └── Set up services
└── Post-installation configuration
├── Verify installation
├── Configure access
└── Display completion info
```
### With Proxmox API
```
Proxmox API Integration:
├── API authentication
├── Container creation via API
├── Configuration updates via API
├── Status monitoring via API
└── Error handling via API
```
## Performance Considerations
### Execution Time Optimization
```
Performance Optimization:
├── Parallel operations where possible
├── Minimal user interaction in default mode
├── Efficient storage selection
├── Optimized GPU detection
└── Streamlined validation
```
### Resource Usage
```
Resource Usage:
├── Minimal memory footprint
├── Efficient disk usage
├── Optimized network usage
└── Minimal CPU overhead
```

View File

@ -0,0 +1,244 @@
# build.func Execution Flowchart
## Main Execution Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ START() │
│ Entry point when build.func is sourced or executed │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Check Environment │
│ • Detect if running on Proxmox host vs inside container │
│ • Capture hard environment variables │
│ • Set CT_TYPE based on context │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Determine Action │
│ • If CT_TYPE="update" → update_script() │
│ • If CT_TYPE="install" → install_script() │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ INSTALL_SCRIPT() │
│ Main container creation workflow │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Installation Mode Selection │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────┐ │
│ │ Default │ │ Advanced │ │ My Defaults │ │ App Defaults│ │
│ │ Install │ │ Install │ │ │ │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ • Use built-in │ │ • Full whiptail │ │ • Load from │ │ • Load from │ │
│ │ defaults │ │ menus │ │ default.vars │ │ app.vars │ │
│ │ • Minimal │ │ • Interactive │ │ • Override │ │ • App- │ │
│ │ prompts │ │ configuration │ │ built-ins │ │ specific │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ └─────────────┘ │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ VARIABLES() │
│ • Load variable precedence chain: │
│ 1. Hard environment variables │
│ 2. App-specific .vars file │
│ 3. Global default.vars file │
│ 4. Built-in defaults in base_settings() │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ BASE_SETTINGS() │
│ • Set core container parameters │
│ • Configure OS selection │
│ • Set resource defaults (CPU, RAM, Disk) │
│ • Configure network defaults │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Storage Selection Logic │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ SELECT_STORAGE() │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────────┐ │ │
│ │ │ Template │ │ Container │ │ Resolution │ │ │
│ │ │ Storage │ │ Storage │ │ Logic │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ • Check if │ │ • Check if │ │ 1. Only 1 storage │ │ │
│ │ │ preselected │ │ preselected │ │ → Auto-select │ │ │
│ │ │ • Validate │ │ • Validate │ │ 2. Preselected │ │ │
│ │ │ availability │ │ availability │ │ → Validate & use │ │ │
│ │ │ • Prompt if │ │ • Prompt if │ │ 3. Multiple options │ │ │
│ │ │ needed │ │ needed │ │ → Prompt user │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ BUILD_CONTAINER() │
│ • Validate all settings │
│ • Check for conflicts │
│ • Prepare container configuration │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ CREATE_LXC_CONTAINER() │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Container Creation Process │ │
│ │ │ │
│ │ 1. Create LXC container with basic configuration │ │
│ │ 2. Configure network settings │ │
│ │ 3. Set up storage and mount points │ │
│ │ 4. Configure features (FUSE, TUN, etc.) │ │
│ │ 5. Set resource limits │ │
│ │ 6. Configure startup options │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ GPU Passthrough Decision Tree │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ DETECT_GPU_DEVICES() │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────────┐ │ │
│ │ │ Intel GPU │ │ AMD GPU │ │ NVIDIA GPU │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ • Check i915 │ │ • Check AMDGPU │ │ • Check NVIDIA │ │ │
│ │ │ driver │ │ driver │ │ driver │ │ │
│ │ │ • Detect │ │ • Detect │ │ • Detect devices │ │ │
│ │ │ devices │ │ devices │ │ • Check CUDA support │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ GPU Selection Logic │ │
│ │ │ │
│ │ • Is app in GPU_APPS list? OR Is container privileged? │ │
│ │ └─ YES → Proceed with GPU configuration │ │
│ │ └─ NO → Skip GPU passthrough │ │
│ │ │ │
│ │ • Single GPU type detected? │ │
│ │ └─ YES → Auto-select and configure │ │
│ │ └─ NO → Prompt user for selection │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ CONFIGURE_GPU_PASSTHROUGH() │
│ • Add GPU device entries to /etc/pve/lxc/<ctid>.conf │
│ • Configure proper device permissions │
│ • Set up device mapping │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Container Finalization │
│ • Start container │
│ • Wait for network connectivity │
│ • Fix GPU GIDs (if GPU passthrough enabled) │
│ • Configure SSH keys (if enabled) │
│ • Run post-installation scripts │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Settings Persistence │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ DEFAULT_VAR_SETTINGS() │ │
│ │ │ │
│ │ • Offer to save current settings as defaults │ │
│ │ • Save to /usr/local/community-scripts/default.vars │ │
│ │ • Save to /usr/local/community-scripts/defaults/<app>.vars │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ COMPLETION │
│ • Display container information │
│ • Show access details │
│ • Provide next steps │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## Key Decision Points
### 1. Installation Mode Selection
- **Default**: Uses built-in defaults, minimal user interaction
- **Advanced**: Full interactive configuration via whiptail menus
- **My Defaults**: Loads settings from global default.vars file
- **App Defaults**: Loads settings from app-specific .vars file
### 2. Storage Selection Logic
```
Storage Selection Flow:
├── Check if storage is preselected via environment variables
│ ├── YES → Validate availability and use
│ └── NO → Continue to resolution logic
├── Count available storage options for content type
│ ├── Only 1 option → Auto-select
│ └── Multiple options → Prompt user via whiptail
└── Validate selected storage and proceed
```
### 3. GPU Passthrough Decision Tree
```
GPU Passthrough Flow:
├── Detect available GPU hardware
│ ├── Intel GPU detected
│ ├── AMD GPU detected
│ └── NVIDIA GPU detected
├── Check if GPU passthrough should be enabled
│ ├── App is in GPU_APPS list? → YES
│ ├── Container is privileged? → YES
│ └── Neither? → Skip GPU passthrough
├── Configure GPU passthrough
│ ├── Single GPU type → Auto-configure
│ └── Multiple GPU types → Prompt user
└── Fix GPU GIDs post-creation
```
### 4. Variable Precedence Chain
```
Variable Resolution Order:
1. Hard environment variables (captured at start)
2. App-specific .vars file (/usr/local/community-scripts/defaults/<app>.vars)
3. Global default.vars file (/usr/local/community-scripts/default.vars)
4. Built-in defaults in base_settings() function
```
## Error Handling Flow
```
Error Handling:
├── Validation errors → Display error message and exit
├── Storage errors → Retry storage selection
├── Network errors → Retry network configuration
├── GPU errors → Fall back to no GPU passthrough
└── Container creation errors → Cleanup and exit
```
## Integration Points
- **Core Functions**: Depends on core.func for basic utilities
- **Error Handling**: Uses error_handler.func for error management
- **API Functions**: Uses api.func for Proxmox API interactions
- **Tools**: Uses tools.func for additional utilities
- **Install Scripts**: Integrates with <app>-install.sh scripts

View File

@ -0,0 +1,361 @@
# build.func Functions Reference
## Overview
This document provides a comprehensive reference of all functions in `build.func`, organized alphabetically with detailed descriptions, parameters, and usage information.
## Function Categories
### Initialization Functions
#### `start()`
**Purpose**: Main entry point when build.func is sourced or executed
**Parameters**: None
**Returns**: None
**Side Effects**:
- Detects execution context (Proxmox host vs container)
- Captures hard environment variables
- Sets CT_TYPE based on context
- Routes to appropriate workflow (install_script or update_script)
**Dependencies**: None
**Environment Variables Used**: `CT_TYPE`, `APP`, `CTID`
#### `variables()`
**Purpose**: Load and resolve all configuration variables using precedence chain
**Parameters**: None
**Returns**: None
**Side Effects**:
- Loads app-specific .vars file
- Loads global default.vars file
- Applies variable precedence chain
- Sets all configuration variables
**Dependencies**: `base_settings()`
**Environment Variables Used**: All configuration variables
#### `base_settings()`
**Purpose**: Set built-in default values for all configuration variables
**Parameters**: None
**Returns**: None
**Side Effects**: Sets default values for all variables
**Dependencies**: None
**Environment Variables Used**: All configuration variables
### UI and Menu Functions
#### `install_script()`
**Purpose**: Main installation workflow coordinator
**Parameters**: None
**Returns**: None
**Side Effects**:
- Displays installation mode selection menu
- Coordinates the entire installation process
- Handles user interaction and validation
**Dependencies**: `variables()`, `build_container()`, `default_var_settings()`
**Environment Variables Used**: `APP`, `CTID`, `var_hostname`
#### `advanced_settings()`
**Purpose**: Provide advanced configuration options via whiptail menus
**Parameters**: None
**Returns**: None
**Side Effects**:
- Displays whiptail menus for configuration
- Updates configuration variables based on user input
- Validates user selections
**Dependencies**: `select_storage()`, `detect_gpu_devices()`
**Environment Variables Used**: All configuration variables
#### `settings_menu()`
**Purpose**: Display and handle settings configuration menu
**Parameters**: None
**Returns**: None
**Side Effects**: Updates configuration variables
**Dependencies**: `advanced_settings()`
**Environment Variables Used**: All configuration variables
### Storage Functions
#### `select_storage()`
**Purpose**: Handle storage selection for templates and containers
**Parameters**: None
**Returns**: None
**Side Effects**:
- Resolves storage preselection
- Prompts user for storage selection if needed
- Validates storage availability
- Sets var_template_storage and var_container_storage
**Dependencies**: `resolve_storage_preselect()`, `choose_and_set_storage_for_file()`
**Environment Variables Used**: `var_template_storage`, `var_container_storage`, `TEMPLATE_STORAGE`, `CONTAINER_STORAGE`
#### `resolve_storage_preselect()`
**Purpose**: Resolve preselected storage options
**Parameters**:
- `storage_type`: Type of storage (template or container)
**Returns**: Storage name if valid, empty if invalid
**Side Effects**: Validates storage availability
**Dependencies**: None
**Environment Variables Used**: `var_template_storage`, `var_container_storage`
#### `choose_and_set_storage_for_file()`
**Purpose**: Interactive storage selection via whiptail
**Parameters**:
- `storage_type`: Type of storage (template or container)
- `content_type`: Content type (vztmpl or rootdir)
**Returns**: None
**Side Effects**:
- Displays whiptail menu
- Updates storage variables
- Validates selection
**Dependencies**: None
**Environment Variables Used**: `var_template_storage`, `var_container_storage`
### Container Creation Functions
#### `build_container()`
**Purpose**: Validate settings and prepare container creation
**Parameters**: None
**Returns**: None
**Side Effects**:
- Validates all configuration
- Checks for conflicts
- Prepares container configuration
- Calls create_lxc_container()
**Dependencies**: `create_lxc_container()`
**Environment Variables Used**: All configuration variables
#### `create_lxc_container()`
**Purpose**: Create the actual LXC container
**Parameters**: None
**Returns**: None
**Side Effects**:
- Creates LXC container with basic configuration
- Configures network settings
- Sets up storage and mount points
- Configures features (FUSE, TUN, etc.)
- Sets resource limits
- Configures startup options
- Starts container
**Dependencies**: `configure_gpu_passthrough()`, `fix_gpu_gids()`
**Environment Variables Used**: All configuration variables
### GPU and Hardware Functions
#### `detect_gpu_devices()`
**Purpose**: Detect available GPU hardware on the system
**Parameters**: None
**Returns**: None
**Side Effects**:
- Scans for Intel, AMD, and NVIDIA GPUs
- Updates var_gpu_type and var_gpu_devices
- Determines GPU capabilities
**Dependencies**: None
**Environment Variables Used**: `var_gpu_type`, `var_gpu_devices`, `GPU_APPS`
#### `configure_gpu_passthrough()`
**Purpose**: Configure GPU passthrough for the container
**Parameters**: None
**Returns**: None
**Side Effects**:
- Adds GPU device entries to container config
- Configures proper device permissions
- Sets up device mapping
- Updates /etc/pve/lxc/<ctid>.conf
**Dependencies**: `detect_gpu_devices()`
**Environment Variables Used**: `var_gpu`, `var_gpu_type`, `var_gpu_devices`, `CTID`
#### `fix_gpu_gids()`
**Purpose**: Fix GPU group IDs after container creation
**Parameters**: None
**Returns**: None
**Side Effects**:
- Updates GPU group IDs in container
- Ensures proper GPU access permissions
- Configures video and render groups
**Dependencies**: `configure_gpu_passthrough()`
**Environment Variables Used**: `CTID`, `var_gpu_type`
### Settings Persistence Functions
#### `default_var_settings()`
**Purpose**: Offer to save current settings as defaults
**Parameters**: None
**Returns**: None
**Side Effects**:
- Prompts user to save settings
- Saves to default.vars file
- Saves to app-specific .vars file
**Dependencies**: `maybe_offer_save_app_defaults()`
**Environment Variables Used**: All configuration variables
#### `maybe_offer_save_app_defaults()`
**Purpose**: Offer to save app-specific defaults
**Parameters**: None
**Returns**: None
**Side Effects**:
- Prompts user to save app-specific settings
- Saves to app.vars file
- Updates app-specific configuration
**Dependencies**: None
**Environment Variables Used**: `APP`, `SAVE_APP_DEFAULTS`
### Utility Functions
#### `validate_settings()`
**Purpose**: Validate all configuration settings
**Parameters**: None
**Returns**: 0 if valid, 1 if invalid
**Side Effects**:
- Checks for configuration conflicts
- Validates resource limits
- Validates network configuration
- Validates storage configuration
**Dependencies**: None
**Environment Variables Used**: All configuration variables
#### `check_conflicts()`
**Purpose**: Check for configuration conflicts
**Parameters**: None
**Returns**: 0 if no conflicts, 1 if conflicts found
**Side Effects**:
- Checks for conflicting settings
- Validates resource allocation
- Checks network configuration
**Dependencies**: None
**Environment Variables Used**: All configuration variables
#### `cleanup_on_error()`
**Purpose**: Clean up resources on error
**Parameters**: None
**Returns**: None
**Side Effects**:
- Removes partially created containers
- Cleans up temporary files
- Resets configuration
**Dependencies**: None
**Environment Variables Used**: `CTID`
## Function Call Flow
### Main Installation Flow
```
start()
├── variables()
│ ├── base_settings()
│ ├── Load app.vars
│ └── Load default.vars
├── install_script()
│ ├── advanced_settings()
│ │ ├── select_storage()
│ │ │ ├── resolve_storage_preselect()
│ │ │ └── choose_and_set_storage_for_file()
│ │ └── detect_gpu_devices()
│ ├── build_container()
│ │ ├── validate_settings()
│ │ ├── check_conflicts()
│ │ └── create_lxc_container()
│ │ ├── configure_gpu_passthrough()
│ │ └── fix_gpu_gids()
│ └── default_var_settings()
│ └── maybe_offer_save_app_defaults()
```
### Error Handling Flow
```
Error Detection
├── validate_settings()
│ └── check_conflicts()
├── Error Handling
│ └── cleanup_on_error()
└── Exit with error code
```
## Function Dependencies
### Core Dependencies
- `start()``install_script()``build_container()``create_lxc_container()`
- `variables()``base_settings()`
- `advanced_settings()``select_storage()``detect_gpu_devices()`
### Storage Dependencies
- `select_storage()``resolve_storage_preselect()`
- `select_storage()``choose_and_set_storage_for_file()`
### GPU Dependencies
- `configure_gpu_passthrough()``detect_gpu_devices()`
- `fix_gpu_gids()``configure_gpu_passthrough()`
### Settings Dependencies
- `default_var_settings()``maybe_offer_save_app_defaults()`
## Function Usage Examples
### Basic Container Creation
```bash
# Set required variables
export APP="plex"
export CTID="100"
export var_hostname="plex-server"
# Call main functions
start() # Entry point
# → variables() # Load configuration
# → install_script() # Main workflow
# → build_container() # Create container
# → create_lxc_container() # Actual creation
```
### Advanced Configuration
```bash
# Set advanced variables
export var_os="debian"
export var_version="12"
export var_cpu="4"
export var_ram="4096"
export var_disk="20"
# Call advanced functions
advanced_settings() # Interactive configuration
# → select_storage() # Storage selection
# → detect_gpu_devices() # GPU detection
```
### GPU Passthrough
```bash
# Enable GPU passthrough
export GPU_APPS="plex"
export var_gpu="nvidia"
# Call GPU functions
detect_gpu_devices() # Detect hardware
configure_gpu_passthrough() # Configure passthrough
fix_gpu_gids() # Fix permissions
```
### Settings Persistence
```bash
# Save settings as defaults
export SAVE_DEFAULTS="true"
export SAVE_APP_DEFAULTS="true"
# Call persistence functions
default_var_settings() # Save global defaults
maybe_offer_save_app_defaults() # Save app defaults
```
## Function Error Handling
### Validation Functions
- `validate_settings()`: Returns 0 for valid, 1 for invalid
- `check_conflicts()`: Returns 0 for no conflicts, 1 for conflicts
### Error Recovery
- `cleanup_on_error()`: Cleans up on any error
- Error codes are propagated up the call stack
- Critical errors cause script termination
### Error Types
1. **Configuration Errors**: Invalid settings or conflicts
2. **Resource Errors**: Insufficient resources or conflicts
3. **Network Errors**: Invalid network configuration
4. **Storage Errors**: Storage not available or invalid
5. **GPU Errors**: GPU configuration failures
6. **Container Creation Errors**: LXC creation failures

View File

@ -0,0 +1,600 @@
# build.func Usage Examples
## Overview
This document provides practical usage examples for `build.func`, covering common scenarios, CLI examples, and environment variable combinations.
## Basic Usage Examples
### 1. Simple Container Creation
**Scenario**: Create a basic Plex media server container
```bash
# Set basic environment variables
export APP="plex"
export CTID="100"
export var_hostname="plex-server"
export var_os="debian"
export var_version="12"
export var_cpu="4"
export var_ram="4096"
export var_disk="20"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.100"
export var_template_storage="local"
export var_container_storage="local"
# Execute build.func
source build.func
```
**Expected Output**:
```
Creating Plex container...
Container ID: 100
Hostname: plex-server
OS: Debian 12
Resources: 4 CPU, 4GB RAM, 20GB Disk
Network: 192.168.1.100/24
Container created successfully!
```
### 2. Advanced Configuration
**Scenario**: Create a Nextcloud container with custom settings
```bash
# Set advanced environment variables
export APP="nextcloud"
export CTID="101"
export var_hostname="nextcloud-server"
export var_os="ubuntu"
export var_version="22.04"
export var_cpu="6"
export var_ram="8192"
export var_disk="50"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.101"
export var_vlan="100"
export var_mtu="9000"
export var_template_storage="nfs-storage"
export var_container_storage="ssd-storage"
export ENABLE_FUSE="true"
export ENABLE_TUN="true"
export SSH="true"
# Execute build.func
source build.func
```
### 3. GPU Passthrough Configuration
**Scenario**: Create a Jellyfin container with NVIDIA GPU passthrough
```bash
# Set GPU passthrough variables
export APP="jellyfin"
export CTID="102"
export var_hostname="jellyfin-server"
export var_os="debian"
export var_version="12"
export var_cpu="8"
export var_ram="16384"
export var_disk="30"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.102"
export var_template_storage="local"
export var_container_storage="local"
export GPU_APPS="jellyfin"
export var_gpu="nvidia"
export ENABLE_PRIVILEGED="true"
export ENABLE_FUSE="true"
export ENABLE_TUN="true"
# Execute build.func
source build.func
```
## Silent/Non-Interactive Examples
### 1. Automated Deployment
**Scenario**: Deploy multiple containers without user interaction
```bash
#!/bin/bash
# Automated deployment script
# Function to create container
create_container() {
local app=$1
local ctid=$2
local ip=$3
export APP="$app"
export CTID="$ctid"
export var_hostname="${app}-server"
export var_os="debian"
export var_version="12"
export var_cpu="2"
export var_ram="2048"
export var_disk="10"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="$ip"
export var_template_storage="local"
export var_container_storage="local"
export ENABLE_FUSE="true"
export ENABLE_TUN="true"
export SSH="true"
source build.func
}
# Create multiple containers
create_container "plex" "100" "192.168.1.100"
create_container "nextcloud" "101" "192.168.1.101"
create_container "nginx" "102" "192.168.1.102"
```
### 2. Development Environment Setup
**Scenario**: Create development containers with specific configurations
```bash
#!/bin/bash
# Development environment setup
# Development container configuration
export APP="dev-container"
export CTID="200"
export var_hostname="dev-server"
export var_os="ubuntu"
export var_version="22.04"
export var_cpu="4"
export var_ram="4096"
export var_disk="20"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.200"
export var_template_storage="local"
export var_container_storage="local"
export ENABLE_NESTING="true"
export ENABLE_PRIVILEGED="true"
export ENABLE_FUSE="true"
export ENABLE_TUN="true"
export SSH="true"
# Execute build.func
source build.func
```
## Network Configuration Examples
### 1. VLAN Configuration
**Scenario**: Create container with VLAN support
```bash
# VLAN configuration
export APP="web-server"
export CTID="300"
export var_hostname="web-server"
export var_os="debian"
export var_version="12"
export var_cpu="2"
export var_ram="2048"
export var_disk="10"
export var_net="vmbr0"
export var_gateway="192.168.100.1"
export var_ip="192.168.100.100"
export var_vlan="100"
export var_mtu="1500"
export var_template_storage="local"
export var_container_storage="local"
source build.func
```
### 2. IPv6 Configuration
**Scenario**: Create container with IPv6 support
```bash
# IPv6 configuration
export APP="ipv6-server"
export CTID="301"
export var_hostname="ipv6-server"
export var_os="debian"
export var_version="12"
export var_cpu="2"
export var_ram="2048"
export var_disk="10"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.101"
export var_ipv6="2001:db8::101"
export IPV6_METHOD="static"
export var_template_storage="local"
export var_container_storage="local"
source build.func
```
## Storage Configuration Examples
### 1. Custom Storage Locations
**Scenario**: Use different storage for templates and containers
```bash
# Custom storage configuration
export APP="storage-test"
export CTID="400"
export var_hostname="storage-test"
export var_os="debian"
export var_version="12"
export var_cpu="2"
export var_ram="2048"
export var_disk="10"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.140"
export var_template_storage="nfs-storage"
export var_container_storage="ssd-storage"
source build.func
```
### 2. High-Performance Storage
**Scenario**: Use high-performance storage for resource-intensive applications
```bash
# High-performance storage configuration
export APP="database-server"
export CTID="401"
export var_hostname="database-server"
export var_os="debian"
export var_version="12"
export var_cpu="8"
export var_ram="16384"
export var_disk="100"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.141"
export var_template_storage="nvme-storage"
export var_container_storage="nvme-storage"
source build.func
```
## Feature Configuration Examples
### 1. Privileged Container
**Scenario**: Create privileged container for system-level access
```bash
# Privileged container configuration
export APP="system-container"
export CTID="500"
export var_hostname="system-container"
export var_os="debian"
export var_version="12"
export var_cpu="4"
export var_ram="4096"
export var_disk="20"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.150"
export var_template_storage="local"
export var_container_storage="local"
export ENABLE_PRIVILEGED="true"
export ENABLE_FUSE="true"
export ENABLE_TUN="true"
export ENABLE_KEYCTL="true"
export ENABLE_MOUNT="true"
source build.func
```
### 2. Unprivileged Container
**Scenario**: Create secure unprivileged container
```bash
# Unprivileged container configuration
export APP="secure-container"
export CTID="501"
export var_hostname="secure-container"
export var_os="debian"
export var_version="12"
export var_cpu="2"
export var_ram="2048"
export var_disk="10"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.151"
export var_template_storage="local"
export var_container_storage="local"
export ENABLE_UNPRIVILEGED="true"
export ENABLE_FUSE="true"
export ENABLE_TUN="true"
source build.func
```
## Settings Persistence Examples
### 1. Save Global Defaults
**Scenario**: Save current settings as global defaults
```bash
# Save global defaults
export APP="default-test"
export CTID="600"
export var_hostname="default-test"
export var_os="debian"
export var_version="12"
export var_cpu="2"
export var_ram="2048"
export var_disk="10"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.160"
export var_template_storage="local"
export var_container_storage="local"
export SAVE_DEFAULTS="true"
source build.func
```
### 2. Save App-Specific Defaults
**Scenario**: Save settings as app-specific defaults
```bash
# Save app-specific defaults
export APP="plex"
export CTID="601"
export var_hostname="plex-server"
export var_os="debian"
export var_version="12"
export var_cpu="4"
export var_ram="4096"
export var_disk="20"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.161"
export var_template_storage="local"
export var_container_storage="local"
export SAVE_APP_DEFAULTS="true"
source build.func
```
## Error Handling Examples
### 1. Validation Error Handling
**Scenario**: Handle configuration validation errors
```bash
#!/bin/bash
# Error handling example
# Set invalid configuration
export APP="error-test"
export CTID="700"
export var_hostname="error-test"
export var_os="invalid-os"
export var_version="invalid-version"
export var_cpu="invalid-cpu"
export var_ram="invalid-ram"
export var_disk="invalid-disk"
export var_net="invalid-network"
export var_gateway="invalid-gateway"
export var_ip="invalid-ip"
# Execute with error handling
if source build.func; then
echo "Container created successfully!"
else
echo "Error: Container creation failed!"
echo "Please check your configuration and try again."
fi
```
### 2. Storage Error Handling
**Scenario**: Handle storage selection errors
```bash
#!/bin/bash
# Storage error handling
# Set invalid storage
export APP="storage-error-test"
export CTID="701"
export var_hostname="storage-error-test"
export var_os="debian"
export var_version="12"
export var_cpu="2"
export var_ram="2048"
export var_disk="10"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.170"
export var_template_storage="nonexistent-storage"
export var_container_storage="nonexistent-storage"
# Execute with error handling
if source build.func; then
echo "Container created successfully!"
else
echo "Error: Storage not available!"
echo "Please check available storage and try again."
fi
```
## Integration Examples
### 1. With Install Scripts
**Scenario**: Integrate with application install scripts
```bash
#!/bin/bash
# Integration with install scripts
# Create container
export APP="plex"
export CTID="800"
export var_hostname="plex-server"
export var_os="debian"
export var_version="12"
export var_cpu="4"
export var_ram="4096"
export var_disk="20"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.180"
export var_template_storage="local"
export var_container_storage="local"
# Create container
source build.func
# Run install script
if [ -f "plex-install.sh" ]; then
source plex-install.sh
else
echo "Install script not found!"
fi
```
### 2. With Monitoring
**Scenario**: Integrate with monitoring systems
```bash
#!/bin/bash
# Monitoring integration
# Create container with monitoring
export APP="monitored-app"
export CTID="801"
export var_hostname="monitored-app"
export var_os="debian"
export var_version="12"
export var_cpu="2"
export var_ram="2048"
export var_disk="10"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.181"
export var_template_storage="local"
export var_container_storage="local"
export DIAGNOSTICS="true"
# Create container
source build.func
# Set up monitoring
if [ -f "monitoring-setup.sh" ]; then
source monitoring-setup.sh
fi
```
## Best Practices
### 1. Environment Variable Management
```bash
#!/bin/bash
# Best practice: Environment variable management
# Set configuration file
CONFIG_FILE="/etc/build.func.conf"
# Load configuration if exists
if [ -f "$CONFIG_FILE" ]; then
source "$CONFIG_FILE"
fi
# Set required variables
export APP="${APP:-plex}"
export CTID="${CTID:-100}"
export var_hostname="${var_hostname:-plex-server}"
export var_os="${var_os:-debian}"
export var_version="${var_version:-12}"
export var_cpu="${var_cpu:-2}"
export var_ram="${var_ram:-2048}"
export var_disk="${var_disk:-10}"
export var_net="${var_net:-vmbr0}"
export var_gateway="${var_gateway:-192.168.1.1}"
export var_ip="${var_ip:-192.168.1.100}"
export var_template_storage="${var_template_storage:-local}"
export var_container_storage="${var_container_storage:-local}"
# Execute build.func
source build.func
```
### 2. Error Handling and Logging
```bash
#!/bin/bash
# Best practice: Error handling and logging
# Set log file
LOG_FILE="/var/log/build.func.log"
# Function to log messages
log_message() {
echo "$(date): $1" >> "$LOG_FILE"
}
# Function to create container with error handling
create_container() {
local app=$1
local ctid=$2
log_message "Starting container creation for $app (ID: $ctid)"
# Set variables
export APP="$app"
export CTID="$ctid"
export var_hostname="${app}-server"
export var_os="debian"
export var_version="12"
export var_cpu="2"
export var_ram="2048"
export var_disk="10"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.$ctid"
export var_template_storage="local"
export var_container_storage="local"
# Create container
if source build.func; then
log_message "Container $app created successfully (ID: $ctid)"
return 0
else
log_message "Error: Failed to create container $app (ID: $ctid)"
return 1
fi
}
# Create containers
create_container "plex" "100"
create_container "nextcloud" "101"
create_container "nginx" "102"
```

View File

@ -0,0 +1,260 @@
# build.func Documentation
## Overview
This directory contains comprehensive documentation for the `build.func` script, which is the core orchestration script for Proxmox LXC container creation in the Community Scripts project.
## Documentation Files
### 📊 [BUILD_FUNC_FLOWCHART.md](./BUILD_FUNC_FLOWCHART.md)
Visual ASCII flowchart showing the main execution flow, decision trees, and key decision points in the build.func script.
**Contents:**
- Main execution flow diagram
- Installation mode selection flows
- Storage selection workflow
- GPU passthrough decision logic
- Variable precedence chain
- Error handling flow
- Integration points
### 🔧 [BUILD_FUNC_ENVIRONMENT_VARIABLES.md](./BUILD_FUNC_ENVIRONMENT_VARIABLES.md)
Complete reference of all environment variables used in build.func, organized by category and usage context.
**Contents:**
- Core container variables
- Operating system variables
- Resource configuration variables
- Network configuration variables
- Storage configuration variables
- Feature flags
- GPU passthrough variables
- API and diagnostics variables
- Settings persistence variables
- Variable precedence chain
- Critical variables for non-interactive use
- Common variable combinations
### 📚 [BUILD_FUNC_FUNCTIONS_REFERENCE.md](./BUILD_FUNC_FUNCTIONS_REFERENCE.md)
Alphabetical function reference with detailed descriptions, parameters, dependencies, and usage information.
**Contents:**
- Initialization functions
- UI and menu functions
- Storage functions
- Container creation functions
- GPU and hardware functions
- Settings persistence functions
- Utility functions
- Function call flow
- Function dependencies
- Function usage examples
- Function error handling
### 🔄 [BUILD_FUNC_EXECUTION_FLOWS.md](./BUILD_FUNC_EXECUTION_FLOWS.md)
Detailed execution flows for different installation modes and scenarios, including variable precedence and decision trees.
**Contents:**
- Default install flow
- Advanced install flow
- My defaults flow
- App defaults flow
- Variable precedence chain
- Storage selection logic
- GPU passthrough flow
- Network configuration flow
- Container creation flow
- Error handling flows
- Integration flows
- Performance considerations
### 🏗️ [BUILD_FUNC_ARCHITECTURE.md](./BUILD_FUNC_ARCHITECTURE.md)
High-level architectural overview including module dependencies, data flow, integration points, and system architecture.
**Contents:**
- High-level architecture diagram
- Module dependencies
- Data flow architecture
- Integration architecture
- System architecture components
- User interface components
- Security architecture
- Performance architecture
- Deployment architecture
- Maintenance architecture
- Future architecture considerations
### 💡 [BUILD_FUNC_USAGE_EXAMPLES.md](./BUILD_FUNC_USAGE_EXAMPLES.md)
Practical usage examples covering common scenarios, CLI examples, and environment variable combinations.
**Contents:**
- Basic usage examples
- Silent/non-interactive examples
- Network configuration examples
- Storage configuration examples
- Feature configuration examples
- Settings persistence examples
- Error handling examples
- Integration examples
- Best practices
## Quick Start Guide
### For New Users
1. Start with [BUILD_FUNC_FLOWCHART.md](./BUILD_FUNC_FLOWCHART.md) to understand the overall flow
2. Review [BUILD_FUNC_ENVIRONMENT_VARIABLES.md](./BUILD_FUNC_ENVIRONMENT_VARIABLES.md) for configuration options
3. Follow examples in [BUILD_FUNC_USAGE_EXAMPLES.md](./BUILD_FUNC_USAGE_EXAMPLES.md)
### For Developers
1. Read [BUILD_FUNC_ARCHITECTURE.md](./BUILD_FUNC_ARCHITECTURE.md) for system overview
2. Study [BUILD_FUNC_FUNCTIONS_REFERENCE.md](./BUILD_FUNC_FUNCTIONS_REFERENCE.md) for function details
3. Review [BUILD_FUNC_EXECUTION_FLOWS.md](./BUILD_FUNC_EXECUTION_FLOWS.md) for implementation details
### For System Administrators
1. Focus on [BUILD_FUNC_USAGE_EXAMPLES.md](./BUILD_FUNC_USAGE_EXAMPLES.md) for deployment scenarios
2. Review [BUILD_FUNC_ENVIRONMENT_VARIABLES.md](./BUILD_FUNC_ENVIRONMENT_VARIABLES.md) for configuration management
3. Check [BUILD_FUNC_ARCHITECTURE.md](./BUILD_FUNC_ARCHITECTURE.md) for security and performance considerations
## Key Concepts
### Variable Precedence
Variables are resolved in this order (highest to lowest priority):
1. Hard environment variables (set before script execution)
2. App-specific .vars file (`/usr/local/community-scripts/defaults/<app>.vars`)
3. Global default.vars file (`/usr/local/community-scripts/default.vars`)
4. Built-in defaults (set in `base_settings()` function)
### Installation Modes
- **Default Install**: Uses built-in defaults, minimal prompts
- **Advanced Install**: Full interactive configuration via whiptail
- **My Defaults**: Loads from global default.vars file
- **App Defaults**: Loads from app-specific .vars file
### Storage Selection Logic
1. If only 1 storage exists for content type → auto-select
2. If preselected via environment variables → validate and use
3. Otherwise → prompt user via whiptail
### GPU Passthrough Flow
1. Detect hardware (Intel/AMD/NVIDIA)
2. Check if app is in GPU_APPS list OR container is privileged
3. Auto-select if single GPU type, prompt if multiple
4. Configure `/etc/pve/lxc/<ctid>.conf` with proper device entries
5. Fix GIDs post-creation to match container's video/render groups
## Common Use Cases
### Basic Container Creation
```bash
export APP="plex"
export CTID="100"
export var_hostname="plex-server"
export var_os="debian"
export var_version="12"
export var_cpu="4"
export var_ram="4096"
export var_disk="20"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.100"
export var_template_storage="local"
export var_container_storage="local"
source build.func
```
### GPU Passthrough
```bash
export APP="jellyfin"
export CTID="101"
export var_hostname="jellyfin-server"
export var_os="debian"
export var_version="12"
export var_cpu="8"
export var_ram="16384"
export var_disk="30"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.101"
export var_template_storage="local"
export var_container_storage="local"
export GPU_APPS="jellyfin"
export var_gpu="nvidia"
export ENABLE_PRIVILEGED="true"
source build.func
```
### Silent/Non-Interactive Deployment
```bash
#!/bin/bash
# Automated deployment
export APP="nginx"
export CTID="102"
export var_hostname="nginx-proxy"
export var_os="alpine"
export var_version="3.18"
export var_cpu="1"
export var_ram="512"
export var_disk="2"
export var_net="vmbr0"
export var_gateway="192.168.1.1"
export var_ip="192.168.1.102"
export var_template_storage="local"
export var_container_storage="local"
export ENABLE_UNPRIVILEGED="true"
source build.func
```
## Troubleshooting
### Common Issues
1. **Container creation fails**: Check resource availability and configuration validity
2. **Storage errors**: Verify storage exists and supports required content types
3. **Network errors**: Validate network configuration and IP address availability
4. **GPU passthrough issues**: Check hardware detection and container privileges
5. **Permission errors**: Verify user permissions and container privileges
### Debug Mode
Enable verbose output for debugging:
```bash
export VERBOSE="true"
export DIAGNOSTICS="true"
source build.func
```
### Log Files
Check system logs for detailed error information:
- `/var/log/syslog`
- `/var/log/pve/lxc/<ctid>.log`
- Container-specific logs
## Contributing
When contributing to build.func documentation:
1. Update relevant documentation files
2. Add examples for new features
3. Update architecture diagrams if needed
4. Test all examples before submitting
5. Follow the existing documentation style
## Related Documentation
- [Main README](../../README.md) - Project overview
- [Installation Guide](../../install/) - Installation scripts
- [Container Templates](../../ct/) - Container templates
- [Tools](../../tools/) - Additional tools and utilities
## Support
For issues and questions:
1. Check this documentation first
2. Review the [troubleshooting section](#troubleshooting)
3. Check existing issues in the project repository
4. Create a new issue with detailed information
---
*Last updated: $(date)*
*Documentation version: 1.0*

View File

@ -0,0 +1,28 @@
# cloud-init.func Flowchart
Cloud-init VM provisioning flow.
## Cloud-Init Generation and Application
```
generate_cloud_init()
generate_user_data()
setup_ssh_keys()
Apply to VM
VM Boot
cloud-init phases
├─ system
├─ config
└─ final
VM Ready ✓
```
---
**Last Updated**: December 2025

View File

@ -0,0 +1,30 @@
# cloud-init.func Functions Reference
Cloud-init and VM provisioning functions.
## Core Functions
### generate_cloud_init()
Generate cloud-init configuration.
### generate_user_data()
Generate user-data script for VM.
### apply_cloud_init()
Apply cloud-init to VM.
### setup_ssh_keys()
Deploy SSH public keys.
### setup_static_ip()
Configure static IP on VM.
### setup_dns()
Configure DNS for VM.
### setup_ipv6()
Enable IPv6 on VM.
---
**Last Updated**: December 2025

View File

@ -0,0 +1,7 @@
# cloud-init.func Integration Guide
Cloud-init integration with Proxmox VM provisioning.
---
**Last Updated**: December 2025

View File

@ -0,0 +1,17 @@
# cloud-init.func Usage Examples
Examples for VM cloud-init configuration.
### Example: Basic Cloud-Init
```bash
#!/usr/bin/env bash
generate_cloud_init > cloud-init.yaml
setup_ssh_keys "$VMID" "$SSH_KEY"
apply_cloud_init "$VMID" cloud-init.yaml
```
---
**Last Updated**: December 2025

View File

@ -0,0 +1,339 @@
# cloud-init.func Documentation
## Overview
The `cloud-init.func` file provides cloud-init configuration and VM initialization functions for Proxmox VE virtual machines. It handles user data, cloud-config generation, and VM setup automation.
## Purpose and Use Cases
- **VM Cloud-Init Setup**: Generate and apply cloud-init configurations for VMs
- **User Data Generation**: Create user-data scripts for VM initialization
- **Cloud-Config**: Generate cloud-config YAML for VM provisioning
- **SSH Key Management**: Setup SSH keys for VM access
- **Network Configuration**: Configure networking for VMs
- **Automated VM Provisioning**: Complete VM setup without manual intervention
## Quick Reference
### Key Function Groups
- **Cloud-Init Core**: Generate and apply cloud-init configurations
- **User Data**: Create initialization scripts for VMs
- **SSH Setup**: Deploy SSH keys automatically
- **Network Configuration**: Setup networking during VM provisioning
- **VM Customization**: Apply custom settings to VMs
### Dependencies
- **External**: `cloud-init`, `curl`, `qemu-img`
- **Internal**: Uses functions from `core.func`, `error_handler.func`
### Integration Points
- Used by: VM creation scripts (vm/*.sh)
- Uses: Environment variables from build.func
- Provides: VM initialization and cloud-init services
## Documentation Files
### 📊 [CLOUD_INIT_FUNC_FLOWCHART.md](./CLOUD_INIT_FUNC_FLOWCHART.md)
Visual execution flows showing cloud-init generation and VM provisioning workflows.
### 📚 [CLOUD_INIT_FUNC_FUNCTIONS_REFERENCE.md](./CLOUD_INIT_FUNC_FUNCTIONS_REFERENCE.md)
Complete alphabetical reference of all cloud-init functions.
### 💡 [CLOUD_INIT_FUNC_USAGE_EXAMPLES.md](./CLOUD_INIT_FUNC_USAGE_EXAMPLES.md)
Practical examples for VM cloud-init setup and customization.
### 🔗 [CLOUD_INIT_FUNC_INTEGRATION.md](./CLOUD_INIT_FUNC_INTEGRATION.md)
How cloud-init.func integrates with VM creation and Proxmox workflows.
## Key Features
### Cloud-Init Configuration
- **User Data Generation**: Create custom initialization scripts
- **Cloud-Config YAML**: Generate standardized cloud-config
- **SSH Keys**: Automatically deploy public keys
- **Package Installation**: Install packages during VM boot
- **Custom Commands**: Run arbitrary commands on first boot
### VM Network Setup
- **DHCP Configuration**: Configure DHCP for automatic IP assignment
- **Static IP Setup**: Configure static IP addresses
- **IPv6 Support**: Enable IPv6 on VMs
- **DNS Configuration**: Set DNS servers for VM
- **Firewall Rules**: Basic firewall configuration
### Security Features
- **SSH Key Injection**: Deploy SSH keys during VM creation
- **Disable Passwords**: Disable password authentication
- **Sudoers Configuration**: Setup sudo access
- **User Management**: Create and configure users
## Function Categories
### 🔹 Cloud-Init Core Functions
- `generate_cloud_init()` - Create cloud-init configuration
- `generate_user_data()` - Generate user-data script
- `apply_cloud_init()` - Apply cloud-init to VM
- `validate_cloud_init()` - Validate cloud-config syntax
### 🔹 SSH & Security Functions
- `setup_ssh_keys()` - Deploy SSH public keys
- `setup_sudo()` - Configure sudoers
- `create_user()` - Create new user account
- `disable_password_auth()` - Disable password login
### 🔹 Network Configuration Functions
- `setup_dhcp()` - Configure DHCP networking
- `setup_static_ip()` - Configure static IP
- `setup_dns()` - Configure DNS servers
- `setup_ipv6()` - Enable IPv6 support
### 🔹 VM Customization Functions
- `install_packages()` - Install packages during boot
- `run_custom_commands()` - Execute custom scripts
- `configure_hostname()` - Set VM hostname
- `configure_timezone()` - Set VM timezone
## Cloud-Init Workflow
```
VM Created
cloud-init (system) boot phase
User-Data Script Execution
├─ Install packages
├─ Deploy SSH keys
├─ Configure network
└─ Create users
cloud-init config phase
Apply cloud-config settings
cloud-init final phase
VM Ready for Use
```
## Common Usage Patterns
### Basic VM Setup with Cloud-Init
```bash
#!/usr/bin/env bash
source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
# Generate cloud-init configuration
cat > cloud-init.yaml <<EOF
#cloud-config
hostname: myvm
timezone: UTC
packages:
- curl
- wget
- git
users:
- name: ubuntu
ssh_authorized_keys:
- ssh-rsa AAAAB3...
sudo: ALL=(ALL) NOPASSWD:ALL
bootcmd:
- echo "VM initializing..."
runcmd:
- apt-get update
- apt-get upgrade -y
EOF
# Apply to VM
qm set VMID --cicustom local:snippets/cloud-init.yaml
```
### With SSH Key Deployment
```bash
#!/usr/bin/env bash
source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
# Get SSH public key
SSH_KEY=$(cat ~/.ssh/id_rsa.pub)
# Generate cloud-init with SSH key
generate_user_data > user-data.txt
# Inject SSH key
setup_ssh_keys "$VMID" "$SSH_KEY"
# Create VM with cloud-init
qm create $VMID ... --cicustom local:snippets/user-data
```
### Network Configuration
```bash
#!/usr/bin/env bash
source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
# Static IP setup
setup_static_ip "192.168.1.100" "255.255.255.0" "192.168.1.1"
# DNS configuration
setup_dns "8.8.8.8 8.8.4.4"
# IPv6 support
setup_ipv6
```
## Best Practices
### ✅ DO
- Validate cloud-config syntax before applying
- Use cloud-init for automated setup
- Deploy SSH keys for secure access
- Test cloud-init configuration in non-production first
- Use DHCP for easier VM deployment
- Document custom cloud-init configurations
- Version control cloud-init templates
### ❌ DON'T
- Use weak SSH keys or passwords
- Leave SSH password authentication enabled
- Hardcode credentials in cloud-init
- Skip validation of cloud-config
- Use untrusted cloud-init sources
- Forget to set timezone on VMs
- Mix cloud-init versions
## Cloud-Config Format
### Example Cloud-Config
```yaml
#cloud-config
# This is a comment
# System configuration
hostname: myvm
timezone: UTC
package_upgrade: true
# Packages to install
packages:
- curl
- wget
- git
- build-essential
# SSH keys for users
ssh_authorized_keys:
- ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC...
# Users to create
users:
- name: ubuntu
home: /home/ubuntu
shell: /bin/bash
sudo: ['ALL=(ALL) NOPASSWD:ALL']
ssh_authorized_keys:
- ssh-rsa AAAAB3...
# Commands to run on boot
runcmd:
- apt-get update
- apt-get upgrade -y
- systemctl restart ssh
# Files to create
write_files:
- path: /etc/profile.d/custom.sh
content: |
export CUSTOM_VAR="value"
```
## VM Network Configuration
### DHCP Configuration
```bash
network:
version: 2
ethernets:
eth0:
dhcp4: true
dhcp6: true
```
### Static IP Configuration
```bash
network:
version: 2
ethernets:
eth0:
addresses:
- 192.168.1.100/24
gateway4: 192.168.1.1
nameservers:
addresses: [8.8.8.8, 8.8.4.4]
```
## Troubleshooting
### "Cloud-Init Configuration Not Applied"
```bash
# Check cloud-init status in VM
cloud-init status
cloud-init status --long
# View cloud-init logs
tail /var/log/cloud-init.log
```
### "SSH Keys Not Deployed"
```bash
# Verify SSH key in cloud-config
grep ssh_authorized_keys user-data.txt
# Check permissions
ls -la ~/.ssh/authorized_keys
```
### "Network Not Configured"
```bash
# Check network configuration
ip addr show
ip route show
# View netplan (if used)
cat /etc/netplan/*.yaml
```
### "Packages Failed to Install"
```bash
# Check cloud-init package log
tail /var/log/cloud-init-output.log
# Manual package installation
apt-get update && apt-get install -y package-name
```
## Related Documentation
- **[install.func/](../install.func/)** - Container installation (similar workflow)
- **[core.func/](../core.func/)** - Utility functions
- **[error_handler.func/](../error_handler.func/)** - Error handling
- **[UPDATED_APP-install.md](../../UPDATED_APP-install.md)** - Application setup guide
- **Proxmox Docs**: https://pve.proxmox.com/wiki/Cloud-Init
## Recent Updates
### Version 2.0 (Dec 2025)
- ✅ Enhanced cloud-init validation
- ✅ Improved SSH key deployment
- ✅ Better network configuration support
- ✅ Added IPv6 support
- ✅ Streamlined user and package setup
---
**Last Updated**: December 2025
**Maintainers**: community-scripts team
**License**: MIT

View File

@ -0,0 +1,316 @@
# core.func Execution Flowchart
## Main Execution Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ core.func Loading │
│ Entry point when core.func is sourced by other scripts │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Load Prevention Check │
│ • Check if _CORE_FUNC_LOADED is set │
│ • Return early if already loaded │
│ • Set _CORE_FUNC_LOADED=1 to prevent reloading │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ LOAD_FUNCTIONS() │
│ Main function loader - sets up all core utilities │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Core Function Loading Sequence │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────────────┐ │
│ │ color() │ │ formatting() │ │ icons() │ │
│ │ │ │ │ │ │ │
│ │ • Set ANSI │ │ • Set format │ │ • Set symbolic icons │ │
│ │ color codes │ │ helpers │ │ • Define message │ │
│ │ • Define │ │ • Tab, bold, │ │ symbols │ │
│ │ colors │ │ line reset │ │ • Status indicators │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────────────────┘ │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────────────┐ │
│ │ default_vars() │ │ set_std_mode() │ │ Additional Functions │ │
│ │ │ │ │ │ │ │
│ │ • Set retry │ │ • Set verbose │ │ • Add more functions │ │
│ │ variables │ │ mode │ │ as needed │ │
│ │ • Initialize │ │ • Configure │ │ │ │
│ │ counters │ │ STD variable │ │ │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## System Check Functions Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ System Validation Flow │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ PVE_CHECK() │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Get PVE │ │ Check PVE │ │ Check PVE │ │ │
│ │ │ Version │ │ 8.x Support │ │ 9.x Support │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ • pveversion │ │ • Allow 8.0-8.9│ │ • Allow ONLY 9.0 │ │ │
│ │ │ • Parse version │ │ • Reject others │ │ • Reject 9.1+ │ │ │
│ │ │ • Extract │ │ • Exit if │ │ • Exit if │ │ │
│ │ │ major.minor │ │ unsupported │ │ unsupported │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ ARCH_CHECK() │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Check │ │ AMD64 Check │ │ PiMox Warning │ │ │
│ │ │ Architecture │ │ │ │ │ │ │
│ │ │ │ │ • dpkg --print- │ │ • Show PiMox │ │ │
│ │ │ • Get system │ │ architecture │ │ message │ │ │
│ │ │ architecture │ │ • Must be │ │ • Point to ARM64 │ │ │
│ │ │ • Compare with │ │ "amd64" │ │ support │ │ │
│ │ │ "amd64" │ │ • Exit if not │ │ • Exit script │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ SHELL_CHECK() │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Check │ │ Bash Check │ │ Error Handling │ │ │
│ │ │ Shell Type │ │ │ │ │ │ │
│ │ │ │ │ • ps -p $$ -o │ │ • Clear screen │ │ │
│ │ │ • Get current │ │ comm= │ │ • Show error │ │ │
│ │ │ shell │ │ • Must be │ │ • Sleep and exit │ │ │
│ │ │ • Compare with │ │ "bash" │ │ │ │ │
│ │ │ "bash" │ │ • Exit if not │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ ROOT_CHECK() │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Check │ │ Root Check │ │ Sudo Check │ │ │
│ │ │ User ID │ │ │ │ │ │ │
│ │ │ │ │ • id -u │ │ • Check parent │ │ │
│ │ │ • Get user ID │ │ • Must be 0 │ │ process │ │ │
│ │ │ • Check if │ │ • Exit if not │ │ • Detect sudo │ │ │
│ │ │ root (0) │ │ root │ │ usage │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## Message System Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Message System Flow │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ MSG_INFO() │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Message │ │ Duplicate │ │ Display Mode │ │ │
│ │ │ Validation │ │ Check │ │ Selection │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ • Check if │ │ • Track shown │ │ • Verbose mode: │ │ │
│ │ │ message │ │ messages │ │ Show directly │ │ │
│ │ │ exists │ │ • Skip if │ │ • Normal mode: │ │ │
│ │ │ • Return if │ │ already │ │ Start spinner │ │ │
│ │ │ empty │ │ shown │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ SPINNER() │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Spinner │ │ Animation │ │ Display │ │ │
│ │ │ Initialization│ │ Loop │ │ Control │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ • Define │ │ • Cycle through │ │ • Print spinner │ │ │
│ │ │ characters │ │ characters │ │ character │ │ │
│ │ │ • Set index │ │ • Sleep 0.1s │ │ • Print message │ │ │
│ │ │ • Start loop │ │ • Increment │ │ • Clear line │ │ │
│ │ │ │ │ index │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ STOP_SPINNER() │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Get Spinner │ │ Kill Process │ │ Cleanup │ │ │
│ │ │ PID │ │ │ │ │ │ │
│ │ │ │ │ • Send TERM │ │ • Remove PID file │ │ │
│ │ │ • From │ │ • Wait for │ │ • Unset variables │ │ │
│ │ │ SPINNER_PID │ │ termination │ │ • Reset terminal │ │ │
│ │ │ • From PID │ │ • Force kill │ │ settings │ │ │
│ │ │ file │ │ if needed │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## Silent Execution Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ SILENT() Execution Flow │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Command Execution │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Setup │ │ Execute │ │ Capture Output │ │ │
│ │ │ Environment │ │ Command │ │ │ │ │
│ │ │ │ │ │ │ • Redirect stdout │ │ │
│ │ │ • Disable │ │ • Run command │ │ to log file │ │ │
│ │ │ error │ │ • Capture │ │ • Redirect stderr │ │ │
│ │ │ handling │ │ return code │ │ to log file │ │ │
│ │ │ • Remove │ │ • Store exit │ │ • Log all output │ │ │
│ │ │ traps │ │ code │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Error Handling │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Check Exit │ │ Load Error │ │ Display Error │ │ │
│ │ │ Code │ │ Handler │ │ Information │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ • If exit code │ │ • Source │ │ • Show error code │ │ │
│ │ │ != 0 │ │ error_handler │ │ • Show explanation │ │ │
│ │ │ • Proceed to │ │ if needed │ │ • Show command │ │ │
│ │ │ error │ │ • Get error │ │ • Show log lines │ │ │
│ │ │ handling │ │ explanation │ │ • Show full log │ │ │
│ │ │ │ │ │ │ command │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Log Management │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Log File │ │ Log Display │ │ Log Access │ │ │
│ │ │ Management │ │ │ │ │ │ │
│ │ │ │ │ • Show last 10 │ │ • Provide command │ │ │
│ │ │ • Create log │ │ lines │ │ to view full log │ │ │
│ │ │ file path │ │ • Count total │ │ • Show line count │ │ │
│ │ │ • Use process │ │ lines │ │ • Enable debugging │ │ │
│ │ │ ID in name │ │ • Format │ │ │ │ │
│ │ │ │ │ output │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## Header Management Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Header Management Flow │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ GET_HEADER() │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Prepare │ │ Check Local │ │ Download Header │ │ │
│ │ │ Parameters │ │ File │ │ │ │ │
│ │ │ │ │ │ │ • Construct URL │ │ │
│ │ │ • Get app name │ │ • Check if │ │ • Download file │ │ │
│ │ │ from APP │ │ file exists │ │ • Save to local │ │ │
│ │ │ • Get app type │ │ • Check if │ │ path │ │ │
│ │ │ from APP_TYPE │ │ file has │ │ • Return success │ │ │
│ │ │ • Construct │ │ content │ │ status │ │ │
│ │ │ paths │ │ • Return if │ │ │ │ │
│ │ │ │ │ available │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ HEADER_INFO() │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Get Header │ │ Clear Screen │ │ Display Header │ │ │
│ │ │ Content │ │ │ │ │ │ │
│ │ │ │ │ • Clear │ │ • Show header │ │ │
│ │ │ • Call │ │ terminal │ │ content if │ │ │
│ │ │ get_header() │ │ • Get terminal │ │ available │ │ │
│ │ │ • Handle │ │ width │ │ • Format output │ │ │
│ │ │ errors │ │ • Set default │ │ • Center content │ │ │
│ │ │ • Return │ │ width if │ │ if possible │ │ │
│ │ │ content │ │ needed │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## Swap Management Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ CHECK_OR_CREATE_SWAP() Flow │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Swap Detection │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Check Active │ │ Swap Found │ │ No Swap Found │ │ │
│ │ │ Swap │ │ │ │ │ │ │
│ │ │ │ │ • Show success │ │ • Show error │ │ │
│ │ │ • Use swapon │ │ message │ │ message │ │ │
│ │ │ command │ │ • Return 0 │ │ • Ask user for │ │ │
│ │ │ • Check for │ │ │ │ creation │ │ │
│ │ │ swap devices │ │ │ │ • Proceed to │ │ │
│ │ │ • Return │ │ │ │ creation flow │ │ │
│ │ │ status │ │ │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Swap Creation │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ User Input │ │ Size │ │ File Creation │ │ │
│ │ │ Collection │ │ Validation │ │ │ │ │
│ │ │ │ │ │ │ • Create swap file │ │ │
│ │ │ • Ask for │ │ • Validate │ │ with dd │ │ │
│ │ │ confirmation │ │ numeric input │ │ • Set permissions │ │ │
│ │ │ • Convert to │ │ • Check range │ │ • Format swap │ │ │
│ │ │ lowercase │ │ • Abort if │ │ • Activate swap │ │ │
│ │ │ • Check for │ │ invalid │ │ • Show success │ │ │
│ │ │ y/yes │ │ │ │ message │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## Integration Points
### With Other Scripts
- **build.func**: Provides system checks and UI functions
- **tools.func**: Uses core utilities for extended operations
- **api.func**: Uses system checks and error handling
- **error_handler.func**: Provides error explanations for silent execution
### External Dependencies
- **curl**: For downloading header files
- **tput**: For terminal control (installed if missing)
- **swapon/mkswap**: For swap management
- **pveversion**: For Proxmox version checking
### Data Flow
- **Input**: Environment variables, command parameters
- **Processing**: System validation, UI rendering, command execution
- **Output**: Messages, log files, exit codes, system state changes

View File

@ -0,0 +1,637 @@
# core.func Functions Reference
## Overview
This document provides a comprehensive alphabetical reference of all functions in `core.func`, including parameters, dependencies, usage examples, and error handling.
## Function Categories
### Initialization Functions
#### `load_functions()`
**Purpose**: Main function loader that initializes all core utilities
**Parameters**: None
**Returns**: None
**Side Effects**:
- Sets `__FUNCTIONS_LOADED=1` to prevent reloading
- Calls all core function groups in sequence
- Initializes color, formatting, icons, defaults, and standard mode
**Dependencies**: None
**Environment Variables Used**: `__FUNCTIONS_LOADED`
**Usage Example**:
```bash
# Automatically called when core.func is sourced
source core.func
# load_functions() is called automatically
```
### Color and Formatting Functions
#### `color()`
**Purpose**: Set ANSI color codes for styled terminal output
**Parameters**: None
**Returns**: None
**Side Effects**: Sets global color variables
**Dependencies**: None
**Environment Variables Used**: None
**Sets Variables**:
- `YW`: Yellow
- `YWB`: Bright yellow
- `BL`: Blue
- `RD`: Red
- `BGN`: Bright green
- `GN`: Green
- `DGN`: Dark green
- `CL`: Clear/reset
**Usage Example**:
```bash
color
echo -e "${GN}Success message${CL}"
echo -e "${RD}Error message${CL}"
```
#### `color_spinner()`
**Purpose**: Set color codes specifically for spinner output
**Parameters**: None
**Returns**: None
**Side Effects**: Sets spinner-specific color variables
**Dependencies**: None
**Environment Variables Used**: None
**Sets Variables**:
- `CS_YW`: Yellow for spinner
- `CS_YWB`: Bright yellow for spinner
- `CS_CL`: Clear for spinner
#### `formatting()`
**Purpose**: Define formatting helpers for terminal output
**Parameters**: None
**Returns**: None
**Side Effects**: Sets global formatting variables
**Dependencies**: None
**Environment Variables Used**: None
**Sets Variables**:
- `BFR`: Back and forward reset
- `BOLD`: Bold text
- `HOLD`: Space character
- `TAB`: Two spaces
- `TAB3`: Six spaces
### Icon Functions
#### `icons()`
**Purpose**: Set symbolic icons used throughout user feedback and prompts
**Parameters**: None
**Returns**: None
**Side Effects**: Sets global icon variables
**Dependencies**: `formatting()` (for TAB variable)
**Environment Variables Used**: `TAB`, `CL`
**Sets Variables**:
- `CM`: Check mark
- `CROSS`: Cross mark
- `DNSOK`: DNS success
- `DNSFAIL`: DNS failure
- `INFO`: Information icon
- `OS`: Operating system icon
- `OSVERSION`: OS version icon
- `CONTAINERTYPE`: Container type icon
- `DISKSIZE`: Disk size icon
- `CPUCORE`: CPU core icon
- `RAMSIZE`: RAM size icon
- `SEARCH`: Search icon
- `VERBOSE_CROPPED`: Verbose mode icon
- `VERIFYPW`: Password verification icon
- `CONTAINERID`: Container ID icon
- `HOSTNAME`: Hostname icon
- `BRIDGE`: Bridge icon
- `NETWORK`: Network icon
- `GATEWAY`: Gateway icon
- `DISABLEIPV6`: IPv6 disable icon
- `DEFAULT`: Default settings icon
- `MACADDRESS`: MAC address icon
- `VLANTAG`: VLAN tag icon
- `ROOTSSH`: SSH key icon
- `CREATING`: Creating icon
- `ADVANCED`: Advanced settings icon
- `FUSE`: FUSE icon
- `HOURGLASS`: Hourglass icon
### Default Variables Functions
#### `default_vars()`
**Purpose**: Set default retry and wait variables for system actions
**Parameters**: None
**Returns**: None
**Side Effects**: Sets retry configuration variables
**Dependencies**: None
**Environment Variables Used**: None
**Sets Variables**:
- `RETRY_NUM`: Number of retry attempts (default: 10)
- `RETRY_EVERY`: Seconds between retries (default: 3)
- `i`: Retry counter initialized to RETRY_NUM
#### `set_std_mode()`
**Purpose**: Set default verbose mode for script execution
**Parameters**: None
**Returns**: None
**Side Effects**: Sets STD variable based on VERBOSE setting
**Dependencies**: None
**Environment Variables Used**: `VERBOSE`
**Sets Variables**:
- `STD`: "silent" if VERBOSE != "yes", empty string if VERBOSE = "yes"
### Silent Execution Functions
#### `silent()`
**Purpose**: Execute commands silently with detailed error reporting
**Parameters**: `$*` - Command and arguments to execute
**Returns**: None (exits on error)
**Side Effects**:
- Executes command with output redirected to log file
- On error, displays detailed error information
- Exits with command's exit code
**Dependencies**: `error_handler.func` (for error explanations)
**Environment Variables Used**: `SILENT_LOGFILE`
**Usage Example**:
```bash
silent apt-get update
silent apt-get install -y package-name
```
**Error Handling**:
- Captures command output to `/tmp/silent.$$.log`
- Shows error code explanation
- Displays last 10 lines of log
- Provides command to view full log
### System Check Functions
#### `shell_check()`
**Purpose**: Verify that the script is running in Bash shell
**Parameters**: None
**Returns**: None (exits if not Bash)
**Side Effects**:
- Checks current shell process
- Exits with error message if not Bash
**Dependencies**: None
**Environment Variables Used**: None
**Usage Example**:
```bash
shell_check
# Script continues if Bash, exits if not
```
#### `root_check()`
**Purpose**: Ensure script is running as root user
**Parameters**: None
**Returns**: None (exits if not root)
**Side Effects**:
- Checks user ID and parent process
- Exits with error message if not root
**Dependencies**: None
**Environment Variables Used**: None
**Usage Example**:
```bash
root_check
# Script continues if root, exits if not
```
#### `pve_check()`
**Purpose**: Verify Proxmox VE version compatibility
**Parameters**: None
**Returns**: None (exits if unsupported version)
**Side Effects**:
- Checks PVE version using pveversion command
- Exits with error message if unsupported
**Dependencies**: `pveversion` command
**Environment Variables Used**: None
**Supported Versions**:
- Proxmox VE 8.0 - 8.9
- Proxmox VE 9.0 (only)
**Usage Example**:
```bash
pve_check
# Script continues if supported version, exits if not
```
#### `arch_check()`
**Purpose**: Verify system architecture is AMD64
**Parameters**: None
**Returns**: None (exits if not AMD64)
**Side Effects**:
- Checks system architecture
- Exits with PiMox warning if not AMD64
**Dependencies**: `dpkg` command
**Environment Variables Used**: None
**Usage Example**:
```bash
arch_check
# Script continues if AMD64, exits if not
```
#### `ssh_check()`
**Purpose**: Detect and warn about external SSH usage
**Parameters**: None
**Returns**: None
**Side Effects**:
- Checks SSH_CLIENT environment variable
- Warns if connecting from external IP
- Allows local connections (127.0.0.1 or host IP)
**Dependencies**: None
**Environment Variables Used**: `SSH_CLIENT`
**Usage Example**:
```bash
ssh_check
# Shows warning if external SSH, continues anyway
```
### Header Management Functions
#### `get_header()`
**Purpose**: Download and cache application header files
**Parameters**: None (uses APP and APP_TYPE variables)
**Returns**: Header content on success, empty on failure
**Side Effects**:
- Downloads header from remote URL
- Caches header locally
- Creates directory structure if needed
**Dependencies**: `curl` command
**Environment Variables Used**: `APP`, `APP_TYPE`
**Usage Example**:
```bash
export APP="plex"
export APP_TYPE="ct"
header_content=$(get_header)
```
#### `header_info()`
**Purpose**: Display application header information
**Parameters**: None (uses APP variable)
**Returns**: None
**Side Effects**:
- Clears screen
- Displays header content
- Gets terminal width for formatting
**Dependencies**: `get_header()`, `tput` command
**Environment Variables Used**: `APP`
**Usage Example**:
```bash
export APP="plex"
header_info
# Displays Plex header information
```
### Utility Functions
#### `ensure_tput()`
**Purpose**: Ensure tput command is available for terminal control
**Parameters**: None
**Returns**: None
**Side Effects**:
- Installs ncurses package if tput missing
- Works on Alpine and Debian-based systems
**Dependencies**: `apk` or `apt-get` package managers
**Environment Variables Used**: None
**Usage Example**:
```bash
ensure_tput
# Installs ncurses if needed, continues if already available
```
#### `is_alpine()`
**Purpose**: Detect if running on Alpine Linux
**Parameters**: None
**Returns**: 0 if Alpine, 1 if not Alpine
**Side Effects**: None
**Dependencies**: None
**Environment Variables Used**: `var_os`, `PCT_OSTYPE`
**Usage Example**:
```bash
if is_alpine; then
echo "Running on Alpine Linux"
else
echo "Not running on Alpine Linux"
fi
```
#### `is_verbose_mode()`
**Purpose**: Check if verbose mode is enabled
**Parameters**: None
**Returns**: 0 if verbose mode, 1 if not verbose
**Side Effects**: None
**Dependencies**: None
**Environment Variables Used**: `VERBOSE`, `var_verbose`
**Usage Example**:
```bash
if is_verbose_mode; then
echo "Verbose mode enabled"
else
echo "Verbose mode disabled"
fi
```
#### `fatal()`
**Purpose**: Display fatal error and terminate script
**Parameters**: `$1` - Error message
**Returns**: None (terminates script)
**Side Effects**:
- Displays error message
- Sends INT signal to current process
**Dependencies**: `msg_error()`
**Environment Variables Used**: None
**Usage Example**:
```bash
fatal "Critical error occurred"
# Script terminates after displaying error
```
### Spinner Functions
#### `spinner()`
**Purpose**: Display animated spinner for progress indication
**Parameters**: None (uses SPINNER_MSG variable)
**Returns**: None (runs indefinitely)
**Side Effects**:
- Displays rotating spinner characters
- Uses terminal control sequences
**Dependencies**: `color_spinner()`
**Environment Variables Used**: `SPINNER_MSG`
**Usage Example**:
```bash
SPINNER_MSG="Processing..."
spinner &
SPINNER_PID=$!
# Spinner runs in background
```
#### `clear_line()`
**Purpose**: Clear current terminal line
**Parameters**: None
**Returns**: None
**Side Effects**: Clears current line using terminal control
**Dependencies**: `tput` command
**Environment Variables Used**: None
#### `stop_spinner()`
**Purpose**: Stop running spinner and cleanup
**Parameters**: None
**Returns**: None
**Side Effects**:
- Kills spinner process
- Removes PID file
- Resets terminal settings
- Unsets spinner variables
**Dependencies**: None
**Environment Variables Used**: `SPINNER_PID`, `SPINNER_MSG`
**Usage Example**:
```bash
stop_spinner
# Stops spinner and cleans up
```
### Message Functions
#### `msg_info()`
**Purpose**: Display informational message with spinner
**Parameters**: `$1` - Message text
**Returns**: None
**Side Effects**:
- Starts spinner if not in verbose mode
- Tracks shown messages to prevent duplicates
- Displays message with hourglass icon in verbose mode
**Dependencies**: `spinner()`, `is_verbose_mode()`, `is_alpine()`
**Environment Variables Used**: `MSG_INFO_SHOWN`
**Usage Example**:
```bash
msg_info "Installing package..."
# Shows spinner with message
```
#### `msg_ok()`
**Purpose**: Display success message
**Parameters**: `$1` - Success message text
**Returns**: None
**Side Effects**:
- Stops spinner
- Displays green checkmark with message
- Removes message from shown tracking
**Dependencies**: `stop_spinner()`
**Environment Variables Used**: `MSG_INFO_SHOWN`
**Usage Example**:
```bash
msg_ok "Package installed successfully"
# Shows green checkmark with message
```
#### `msg_error()`
**Purpose**: Display error message
**Parameters**: `$1` - Error message text
**Returns**: None
**Side Effects**:
- Stops spinner
- Displays red cross with message
**Dependencies**: `stop_spinner()`
**Environment Variables Used**: None
**Usage Example**:
```bash
msg_error "Installation failed"
# Shows red cross with message
```
#### `msg_warn()`
**Purpose**: Display warning message
**Parameters**: `$1` - Warning message text
**Returns**: None
**Side Effects**:
- Stops spinner
- Displays yellow info icon with message
**Dependencies**: `stop_spinner()`
**Environment Variables Used**: None
**Usage Example**:
```bash
msg_warn "This operation may take some time"
# Shows yellow info icon with message
```
#### `msg_custom()`
**Purpose**: Display custom message with specified symbol and color
**Parameters**:
- `$1` - Custom symbol (default: "[*]")
- `$2` - Color code (default: "\e[36m")
- `$3` - Message text
**Returns**: None
**Side Effects**:
- Stops spinner
- Displays custom formatted message
**Dependencies**: `stop_spinner()`
**Environment Variables Used**: None
**Usage Example**:
```bash
msg_custom "⚡" "\e[33m" "Custom warning message"
# Shows custom symbol and color with message
```
#### `msg_debug()`
**Purpose**: Display debug message if debug mode enabled
**Parameters**: `$*` - Debug message text
**Returns**: None
**Side Effects**:
- Only displays if var_full_verbose is set
- Shows timestamp and debug prefix
**Dependencies**: None
**Environment Variables Used**: `var_full_verbose`, `var_verbose`
**Usage Example**:
```bash
export var_full_verbose=1
msg_debug "Debug information here"
# Shows debug message with timestamp
```
### System Management Functions
#### `check_or_create_swap()`
**Purpose**: Check for active swap and optionally create swap file
**Parameters**: None
**Returns**: 0 if swap exists or created, 1 if skipped
**Side Effects**:
- Checks for active swap
- Prompts user to create swap if none found
- Creates swap file if user confirms
**Dependencies**: `swapon`, `dd`, `mkswap` commands
**Environment Variables Used**: None
**Usage Example**:
```bash
if check_or_create_swap; then
echo "Swap is available"
else
echo "No swap available"
fi
```
## Function Call Hierarchy
### Initialization Flow
```
load_functions()
├── color()
├── formatting()
├── icons()
├── default_vars()
└── set_std_mode()
```
### Message System Flow
```
msg_info()
├── is_verbose_mode()
├── is_alpine()
├── spinner()
└── color_spinner()
msg_ok()
├── stop_spinner()
└── clear_line()
msg_error()
└── stop_spinner()
msg_warn()
└── stop_spinner()
```
### System Check Flow
```
pve_check()
├── pveversion command
└── version parsing
arch_check()
├── dpkg command
└── architecture check
shell_check()
├── ps command
└── shell detection
root_check()
├── id command
└── parent process check
```
### Silent Execution Flow
```
silent()
├── Command execution
├── Output redirection
├── Error handling
├── error_handler.func loading
└── Log management
```
## Error Handling Patterns
### System Check Errors
- All system check functions exit with appropriate error messages
- Clear indication of what's wrong and how to fix it
- Graceful exit with sleep delay for user to read message
### Silent Execution Errors
- Commands executed via `silent()` capture output to log file
- On failure, displays error code explanation
- Shows last 10 lines of log output
- Provides command to view full log
### Spinner Errors
- Spinner functions handle process cleanup on exit
- Trap handlers ensure spinners are stopped
- Terminal settings are restored on error
## Environment Variable Dependencies
### Required Variables
- `APP`: Application name for header display
- `APP_TYPE`: Application type (ct/vm) for header paths
- `VERBOSE`: Verbose mode setting
### Optional Variables
- `var_os`: OS type for Alpine detection
- `PCT_OSTYPE`: Alternative OS type variable
- `var_verbose`: Alternative verbose setting
- `var_full_verbose`: Debug mode setting
### Internal Variables
- `_CORE_FUNC_LOADED`: Prevents multiple loading
- `__FUNCTIONS_LOADED`: Prevents multiple function loading
- `SILENT_LOGFILE`: Silent execution log file path
- `SPINNER_PID`: Spinner process ID
- `SPINNER_MSG`: Spinner message text
- `MSG_INFO_SHOWN`: Tracks shown info messages

View File

@ -0,0 +1,517 @@
# core.func Integration Guide
## Overview
This document describes how `core.func` integrates with other components in the Proxmox Community Scripts project, including dependencies, data flow, and API surface.
## Dependencies
### External Dependencies
#### Required Commands
- **`pveversion`**: Proxmox VE version checking
- **`dpkg`**: Architecture detection
- **`ps`**: Process and shell detection
- **`id`**: User ID checking
- **`curl`**: Header file downloading
- **`swapon`**: Swap status checking
- **`dd`**: Swap file creation
- **`mkswap`**: Swap file formatting
#### Optional Commands
- **`tput`**: Terminal control (installed if missing)
- **`apk`**: Alpine package manager
- **`apt-get`**: Debian package manager
### Internal Dependencies
#### error_handler.func
- **Purpose**: Provides error code explanations for silent execution
- **Usage**: Automatically loaded when `silent()` encounters errors
- **Integration**: Called via `explain_exit_code()` function
- **Data Flow**: Error code → explanation → user display
## Integration Points
### With build.func
#### System Validation
```bash
# build.func uses core.func for system checks
source core.func
pve_check
arch_check
shell_check
root_check
```
#### User Interface
```bash
# build.func uses core.func for UI elements
msg_info "Creating container..."
msg_ok "Container created successfully"
msg_error "Container creation failed"
```
#### Silent Execution
```bash
# build.func uses core.func for command execution
silent pct create "$CTID" "$TEMPLATE" \
--hostname "$HOSTNAME" \
--memory "$MEMORY" \
--cores "$CORES"
```
### With tools.func
#### Utility Functions
```bash
# tools.func uses core.func utilities
source core.func
# System checks
pve_check
root_check
# UI elements
msg_info "Running maintenance tasks..."
msg_ok "Maintenance completed"
```
#### Error Handling
```bash
# tools.func uses core.func for error handling
if silent systemctl restart service; then
msg_ok "Service restarted"
else
msg_error "Service restart failed"
fi
```
### With api.func
#### System Validation
```bash
# api.func uses core.func for system checks
source core.func
pve_check
root_check
```
#### API Operations
```bash
# api.func uses core.func for API calls
msg_info "Connecting to Proxmox API..."
if silent curl -k -H "Authorization: PVEAPIToken=$API_TOKEN" \
"$API_URL/api2/json/nodes/$NODE/lxc"; then
msg_ok "API connection successful"
else
msg_error "API connection failed"
fi
```
### With error_handler.func
#### Error Explanations
```bash
# error_handler.func provides explanations for core.func
explain_exit_code() {
local code="$1"
case "$code" in
1) echo "General error" ;;
2) echo "Misuse of shell builtins" ;;
126) echo "Command invoked cannot execute" ;;
127) echo "Command not found" ;;
128) echo "Invalid argument to exit" ;;
*) echo "Unknown error code" ;;
esac
}
```
### With install.func
#### Installation Process
```bash
# install.func uses core.func for installation
source core.func
# System checks
pve_check
root_check
# Installation steps
msg_info "Installing packages..."
silent apt-get update
silent apt-get install -y package
msg_ok "Installation completed"
```
### With alpine-install.func
#### Alpine-Specific Operations
```bash
# alpine-install.func uses core.func for Alpine operations
source core.func
# Alpine detection
if is_alpine; then
msg_info "Detected Alpine Linux"
silent apk add --no-cache package
else
msg_info "Detected Debian-based system"
silent apt-get install -y package
fi
```
### With alpine-tools.func
#### Alpine Utilities
```bash
# alpine-tools.func uses core.func for Alpine tools
source core.func
# Alpine-specific operations
if is_alpine; then
msg_info "Running Alpine-specific operations..."
# Alpine tools logic
msg_ok "Alpine operations completed"
fi
```
### With passthrough.func
#### Hardware Passthrough
```bash
# passthrough.func uses core.func for hardware operations
source core.func
# System checks
pve_check
root_check
# Hardware operations
msg_info "Configuring GPU passthrough..."
if silent lspci | grep -i nvidia; then
msg_ok "NVIDIA GPU detected"
else
msg_warn "No NVIDIA GPU found"
fi
```
### With vm-core.func
#### VM Operations
```bash
# vm-core.func uses core.func for VM management
source core.func
# System checks
pve_check
root_check
# VM operations
msg_info "Creating virtual machine..."
silent qm create "$VMID" \
--name "$VMNAME" \
--memory "$MEMORY" \
--cores "$CORES"
msg_ok "Virtual machine created"
```
## Data Flow
### Input Data
#### Environment Variables
- **`APP`**: Application name for header display
- **`APP_TYPE`**: Application type (ct/vm) for header paths
- **`VERBOSE`**: Verbose mode setting
- **`var_os`**: OS type for Alpine detection
- **`PCT_OSTYPE`**: Alternative OS type variable
- **`var_verbose`**: Alternative verbose setting
- **`var_full_verbose`**: Debug mode setting
#### Command Parameters
- **Function arguments**: Passed to individual functions
- **Command arguments**: Passed to `silent()` function
- **User input**: Collected via `read` commands
### Processing Data
#### System Information
- **Proxmox version**: Parsed from `pveversion` output
- **Architecture**: Retrieved from `dpkg --print-architecture`
- **Shell type**: Detected from process information
- **User ID**: Retrieved from `id -u`
- **SSH connection**: Detected from `SSH_CLIENT` environment
#### UI State
- **Message tracking**: `MSG_INFO_SHOWN` associative array
- **Spinner state**: `SPINNER_PID` and `SPINNER_MSG` variables
- **Terminal state**: Cursor position and display mode
#### Error Information
- **Exit codes**: Captured from command execution
- **Log output**: Redirected to temporary log files
- **Error explanations**: Retrieved from error_handler.func
### Output Data
#### User Interface
- **Colored messages**: ANSI color codes for terminal output
- **Icons**: Symbolic representations for different message types
- **Spinners**: Animated progress indicators
- **Formatted text**: Consistent message formatting
#### System State
- **Exit codes**: Returned from functions
- **Log files**: Created for silent execution
- **Configuration**: Modified system settings
- **Process state**: Spinner processes and cleanup
## API Surface
### Public Functions
#### System Validation
- **`pve_check()`**: Proxmox VE version validation
- **`arch_check()`**: Architecture validation
- **`shell_check()`**: Shell validation
- **`root_check()`**: Privilege validation
- **`ssh_check()`**: SSH connection warning
#### User Interface
- **`msg_info()`**: Informational messages
- **`msg_ok()`**: Success messages
- **`msg_error()`**: Error messages
- **`msg_warn()`**: Warning messages
- **`msg_custom()`**: Custom messages
- **`msg_debug()`**: Debug messages
#### Spinner Control
- **`spinner()`**: Start spinner animation
- **`stop_spinner()`**: Stop spinner and cleanup
- **`clear_line()`**: Clear current terminal line
#### Silent Execution
- **`silent()`**: Execute commands with error handling
#### Utility Functions
- **`is_alpine()`**: Alpine Linux detection
- **`is_verbose_mode()`**: Verbose mode detection
- **`fatal()`**: Fatal error handling
- **`ensure_tput()`**: Terminal control setup
#### Header Management
- **`get_header()`**: Download application headers
- **`header_info()`**: Display header information
#### System Management
- **`check_or_create_swap()`**: Swap file management
### Internal Functions
#### Initialization
- **`load_functions()`**: Function loader
- **`color()`**: Color setup
- **`formatting()`**: Formatting setup
- **`icons()`**: Icon setup
- **`default_vars()`**: Default variables
- **`set_std_mode()`**: Standard mode setup
#### Color Management
- **`color_spinner()`**: Spinner colors
### Global Variables
#### Color Variables
- **`YW`**, **`YWB`**, **`BL`**, **`RD`**, **`BGN`**, **`GN`**, **`DGN`**, **`CL`**: Color codes
- **`CS_YW`**, **`CS_YWB`**, **`CS_CL`**: Spinner colors
#### Formatting Variables
- **`BFR`**, **`BOLD`**, **`HOLD`**, **`TAB`**, **`TAB3`**: Formatting helpers
#### Icon Variables
- **`CM`**, **`CROSS`**, **`INFO`**, **`OS`**, **`OSVERSION`**, etc.: Message icons
#### Configuration Variables
- **`RETRY_NUM`**, **`RETRY_EVERY`**: Retry settings
- **`STD`**: Standard mode setting
- **`SILENT_LOGFILE`**: Log file path
#### State Variables
- **`_CORE_FUNC_LOADED`**: Loading prevention
- **`__FUNCTIONS_LOADED`**: Function loading prevention
- **`SPINNER_PID`**, **`SPINNER_MSG`**: Spinner state
- **`MSG_INFO_SHOWN`**: Message tracking
## Integration Patterns
### Standard Integration Pattern
```bash
#!/usr/bin/env bash
# Standard integration pattern
# 1. Source core.func first
source core.func
# 2. Run system checks
pve_check
arch_check
shell_check
root_check
# 3. Set up error handling
trap 'stop_spinner' EXIT INT TERM
# 4. Use UI functions
msg_info "Starting operation..."
# 5. Use silent execution
silent command
# 6. Show completion
msg_ok "Operation completed"
```
### Minimal Integration Pattern
```bash
#!/usr/bin/env bash
# Minimal integration pattern
source core.func
pve_check
root_check
msg_info "Running operation..."
silent command
msg_ok "Operation completed"
```
### Advanced Integration Pattern
```bash
#!/usr/bin/env bash
# Advanced integration pattern
source core.func
# System validation
pve_check
arch_check
shell_check
root_check
ssh_check
# Error handling
trap 'stop_spinner' EXIT INT TERM
# Verbose mode handling
if is_verbose_mode; then
msg_info "Verbose mode enabled"
fi
# OS-specific operations
if is_alpine; then
msg_info "Alpine Linux detected"
# Alpine-specific logic
else
msg_info "Debian-based system detected"
# Debian-specific logic
fi
# Operation execution
msg_info "Starting operation..."
if silent command; then
msg_ok "Operation succeeded"
else
msg_error "Operation failed"
exit 1
fi
```
## Error Handling Integration
### Silent Execution Error Flow
```
silent() command
├── Execute command
├── Capture output to log
├── Check exit code
├── If error:
│ ├── Load error_handler.func
│ ├── Get error explanation
│ ├── Display error details
│ ├── Show log excerpt
│ └── Exit with error code
└── If success: Continue
```
### System Check Error Flow
```
System Check Function
├── Check system state
├── If valid: Return 0
└── If invalid:
├── Display error message
├── Show fix instructions
├── Sleep for user to read
└── Exit with error code
```
## Performance Considerations
### Loading Optimization
- **Single Loading**: `_CORE_FUNC_LOADED` prevents multiple loading
- **Function Loading**: `__FUNCTIONS_LOADED` prevents multiple function loading
- **Lazy Loading**: Functions loaded only when needed
### Memory Usage
- **Minimal Footprint**: Core functions use minimal memory
- **Variable Reuse**: Global variables reused across functions
- **Cleanup**: Spinner processes cleaned up on exit
### Execution Speed
- **Fast Checks**: System checks are optimized for speed
- **Efficient Spinners**: Spinner animation uses minimal CPU
- **Quick Messages**: Message functions optimized for performance
## Security Considerations
### Privilege Escalation
- **Root Check**: Ensures script runs with sufficient privileges
- **Shell Check**: Validates shell environment
- **Process Validation**: Checks parent process for sudo usage
### Input Validation
- **Parameter Checking**: Functions validate input parameters
- **Error Handling**: Proper error handling prevents crashes
- **Safe Execution**: Silent execution with proper error handling
### System Protection
- **Version Validation**: Ensures compatible Proxmox version
- **Architecture Check**: Prevents execution on unsupported systems
- **SSH Warning**: Warns about external SSH usage
## Future Integration Considerations
### Extensibility
- **Function Groups**: Easy to add new function groups
- **Message Types**: Easy to add new message types
- **System Checks**: Easy to add new system checks
### Compatibility
- **Version Support**: Easy to add new Proxmox versions
- **OS Support**: Easy to add new operating systems
- **Architecture Support**: Easy to add new architectures
### Performance
- **Optimization**: Functions can be optimized for better performance
- **Caching**: Results can be cached for repeated operations
- **Parallelization**: Operations can be parallelized where appropriate

View File

@ -0,0 +1,728 @@
# core.func Usage Examples
## Overview
This document provides practical usage examples for `core.func` functions, covering common scenarios, integration patterns, and best practices.
## Basic Script Setup
### Standard Script Initialization
```bash
#!/usr/bin/env bash
# Standard script setup using core.func
# Source core functions
source core.func
# Run system checks
pve_check
arch_check
shell_check
root_check
# Optional: Check SSH connection
ssh_check
# Set up error handling
trap 'stop_spinner' EXIT INT TERM
# Your script logic here
msg_info "Starting script execution"
# ... script code ...
msg_ok "Script completed successfully"
```
### Minimal Script Setup
```bash
#!/usr/bin/env bash
# Minimal setup for simple scripts
source core.func
# Basic checks only
pve_check
root_check
# Simple execution
msg_info "Running operation"
# ... your code ...
msg_ok "Operation completed"
```
## Message Display Examples
### Progress Indication
```bash
#!/usr/bin/env bash
source core.func
# Show progress with spinner
msg_info "Downloading package..."
sleep 2
msg_ok "Download completed"
msg_info "Installing package..."
sleep 3
msg_ok "Installation completed"
msg_info "Configuring service..."
sleep 1
msg_ok "Configuration completed"
```
### Error Handling
```bash
#!/usr/bin/env bash
source core.func
# Function with error handling
install_package() {
local package="$1"
msg_info "Installing $package..."
if silent apt-get install -y "$package"; then
msg_ok "$package installed successfully"
return 0
else
msg_error "Failed to install $package"
return 1
fi
}
# Usage
if install_package "nginx"; then
msg_ok "Nginx installation completed"
else
msg_error "Nginx installation failed"
exit 1
fi
```
### Warning Messages
```bash
#!/usr/bin/env bash
source core.func
# Show warnings for potentially dangerous operations
msg_warn "This will modify system configuration"
read -p "Continue? [y/N]: " confirm
if [[ "$confirm" =~ ^[yY]$ ]]; then
msg_info "Proceeding with modification..."
# ... dangerous operation ...
msg_ok "Modification completed"
else
msg_info "Operation cancelled"
fi
```
### Custom Messages
```bash
#!/usr/bin/env bash
source core.func
# Custom message with specific icon and color
msg_custom "🚀" "\e[32m" "Launching application"
msg_custom "⚡" "\e[33m" "High performance mode enabled"
msg_custom "🔒" "\e[31m" "Security mode activated"
```
### Debug Messages
```bash
#!/usr/bin/env bash
source core.func
# Enable debug mode
export var_full_verbose=1
# Debug messages
msg_debug "Variable value: $some_variable"
msg_debug "Function called: $FUNCNAME"
msg_debug "Current directory: $(pwd)"
```
## Silent Execution Examples
### Package Management
```bash
#!/usr/bin/env bash
source core.func
# Update package lists
msg_info "Updating package lists..."
silent apt-get update
# Install packages
msg_info "Installing required packages..."
silent apt-get install -y curl wget git
# Upgrade packages
msg_info "Upgrading packages..."
silent apt-get upgrade -y
msg_ok "Package management completed"
```
### File Operations
```bash
#!/usr/bin/env bash
source core.func
# Create directories
msg_info "Creating directory structure..."
silent mkdir -p /opt/myapp/{config,logs,data}
# Set permissions
msg_info "Setting permissions..."
silent chmod 755 /opt/myapp
silent chmod 644 /opt/myapp/config/*
# Copy files
msg_info "Copying configuration files..."
silent cp config/* /opt/myapp/config/
msg_ok "File operations completed"
```
### Service Management
```bash
#!/usr/bin/env bash
source core.func
# Start service
msg_info "Starting service..."
silent systemctl start myservice
# Enable service
msg_info "Enabling service..."
silent systemctl enable myservice
# Check service status
msg_info "Checking service status..."
if silent systemctl is-active --quiet myservice; then
msg_ok "Service is running"
else
msg_error "Service failed to start"
fi
```
### Network Operations
```bash
#!/usr/bin/env bash
source core.func
# Test network connectivity
msg_info "Testing network connectivity..."
if silent ping -c 1 8.8.8.8; then
msg_ok "Network connectivity confirmed"
else
msg_error "Network connectivity failed"
fi
# Download files
msg_info "Downloading configuration..."
silent curl -fsSL https://example.com/config -o /tmp/config
# Extract archives
msg_info "Extracting archive..."
silent tar -xzf /tmp/archive.tar.gz -C /opt/
```
## System Check Examples
### Comprehensive System Validation
```bash
#!/usr/bin/env bash
source core.func
# Complete system validation
validate_system() {
msg_info "Validating system requirements..."
# Check Proxmox version
if pve_check; then
msg_ok "Proxmox VE version is supported"
fi
# Check architecture
if arch_check; then
msg_ok "System architecture is supported"
fi
# Check shell
if shell_check; then
msg_ok "Shell environment is correct"
fi
# Check privileges
if root_check; then
msg_ok "Running with sufficient privileges"
fi
# Check SSH connection
ssh_check
msg_ok "System validation completed"
}
# Run validation
validate_system
```
### Conditional System Checks
```bash
#!/usr/bin/env bash
source core.func
# Check if running in container
if [[ -f /.dockerenv ]] || [[ -f /run/.containerenv ]]; then
msg_warn "Running inside container"
# Skip some checks
else
# Full system checks
pve_check
arch_check
fi
# Always check shell and privileges
shell_check
root_check
```
## Header Management Examples
### Application Header Display
```bash
#!/usr/bin/env bash
source core.func
# Set application information
export APP="plex"
export APP_TYPE="ct"
# Display header
header_info
# Continue with application setup
msg_info "Setting up Plex Media Server..."
```
### Custom Header Handling
```bash
#!/usr/bin/env bash
source core.func
# Get header content
export APP="nextcloud"
export APP_TYPE="ct"
header_content=$(get_header)
if [[ -n "$header_content" ]]; then
echo "Header found:"
echo "$header_content"
else
msg_warn "No header found for $APP"
fi
```
## Swap Management Examples
### Interactive Swap Creation
```bash
#!/usr/bin/env bash
source core.func
# Check and create swap
if check_or_create_swap; then
msg_ok "Swap is available"
else
msg_warn "No swap available - continuing without swap"
fi
```
### Automated Swap Check
```bash
#!/usr/bin/env bash
source core.func
# Check swap without prompting
check_swap_quiet() {
if swapon --noheadings --show | grep -q 'swap'; then
msg_ok "Swap is active"
return 0
else
msg_warn "No active swap detected"
return 1
fi
}
if check_swap_quiet; then
msg_info "System has sufficient swap"
else
msg_warn "Consider adding swap for better performance"
fi
```
## Spinner Usage Examples
### Long-Running Operations
```bash
#!/usr/bin/env bash
source core.func
# Long-running operation with spinner
long_operation() {
msg_info "Processing large dataset..."
# Simulate long operation
for i in {1..100}; do
sleep 0.1
# Update spinner message periodically
if (( i % 20 == 0 )); then
SPINNER_MSG="Processing... $i%"
fi
done
msg_ok "Dataset processing completed"
}
long_operation
```
### Background Operations
```bash
#!/usr/bin/env bash
source core.func
# Background operation with spinner
background_operation() {
msg_info "Starting background process..."
# Start spinner
SPINNER_MSG="Processing in background..."
spinner &
SPINNER_PID=$!
# Do background work
sleep 5
# Stop spinner
stop_spinner
msg_ok "Background process completed"
}
background_operation
```
## Integration Examples
### With build.func
```bash
#!/usr/bin/env bash
# Integration with build.func
source core.func
source build.func
# Use core functions for system validation
pve_check
arch_check
root_check
# Use build.func for container creation
export APP="plex"
export CTID="100"
# ... container creation ...
```
### With tools.func
```bash
#!/usr/bin/env bash
# Integration with tools.func
source core.func
source tools.func
# Use core functions for UI
msg_info "Starting maintenance tasks..."
# Use tools.func for maintenance
update_system
cleanup_logs
optimize_storage
msg_ok "Maintenance completed"
```
### With error_handler.func
```bash
#!/usr/bin/env bash
# Integration with error_handler.func
source core.func
source error_handler.func
# Use core functions for execution
msg_info "Running operation..."
# Silent execution will use error_handler for explanations
silent apt-get install -y package
msg_ok "Operation completed"
```
## Best Practices Examples
### Error Handling Pattern
```bash
#!/usr/bin/env bash
source core.func
# Robust error handling
run_with_error_handling() {
local operation="$1"
local description="$2"
msg_info "$description"
if silent "$operation"; then
msg_ok "$description completed successfully"
return 0
else
msg_error "$description failed"
return 1
fi
}
# Usage
run_with_error_handling "apt-get update" "Package list update"
run_with_error_handling "apt-get install -y nginx" "Nginx installation"
```
### Verbose Mode Handling
```bash
#!/usr/bin/env bash
source core.func
# Handle verbose mode
if is_verbose_mode; then
msg_info "Verbose mode enabled - showing detailed output"
# Show more information
else
msg_info "Normal mode - showing minimal output"
# Show less information
fi
```
### Alpine Linux Detection
```bash
#!/usr/bin/env bash
source core.func
# Handle different OS types
if is_alpine; then
msg_info "Detected Alpine Linux"
# Use Alpine-specific commands
silent apk add --no-cache package
else
msg_info "Detected Debian-based system"
# Use Debian-specific commands
silent apt-get install -y package
fi
```
### Conditional Execution
```bash
#!/usr/bin/env bash
source core.func
# Conditional execution based on system state
if [[ -f /etc/nginx/nginx.conf ]]; then
msg_warn "Nginx configuration already exists"
read -p "Overwrite? [y/N]: " overwrite
if [[ "$overwrite" =~ ^[yY]$ ]]; then
msg_info "Overwriting configuration..."
# ... overwrite logic ...
else
msg_info "Skipping configuration"
fi
else
msg_info "Creating new Nginx configuration..."
# ... create logic ...
fi
```
## Advanced Usage Examples
### Custom Spinner Messages
```bash
#!/usr/bin/env bash
source core.func
# Custom spinner with progress
download_with_progress() {
local url="$1"
local file="$2"
msg_info "Starting download..."
# Start spinner
SPINNER_MSG="Downloading..."
spinner &
SPINNER_PID=$!
# Download with progress
curl -L "$url" -o "$file" --progress-bar
# Stop spinner
stop_spinner
msg_ok "Download completed"
}
download_with_progress "https://example.com/file.tar.gz" "/tmp/file.tar.gz"
```
### Message Deduplication
```bash
#!/usr/bin/env bash
source core.func
# Messages are automatically deduplicated
for i in {1..5}; do
msg_info "Processing item $i"
# This message will only show once
done
# Different messages will show separately
msg_info "Starting phase 1"
msg_info "Starting phase 2"
msg_info "Starting phase 3"
```
### Terminal Control
```bash
#!/usr/bin/env bash
source core.func
# Ensure terminal control is available
ensure_tput
# Use terminal control
clear_line
echo "This line will be cleared"
clear_line
echo "New content"
```
## Troubleshooting Examples
### Debug Mode
```bash
#!/usr/bin/env bash
source core.func
# Enable debug mode
export var_full_verbose=1
export VERBOSE="yes"
# Debug information
msg_debug "Script started"
msg_debug "Current user: $(whoami)"
msg_debug "Current directory: $(pwd)"
msg_debug "Environment variables: $(env | grep -E '^(APP|CTID|VERBOSE)')"
```
### Silent Execution Debugging
```bash
#!/usr/bin/env bash
source core.func
# Debug silent execution
debug_silent() {
local cmd="$1"
local log_file="/tmp/debug.$$.log"
echo "Command: $cmd" > "$log_file"
echo "Timestamp: $(date)" >> "$log_file"
echo "Working directory: $(pwd)" >> "$log_file"
echo "Environment:" >> "$log_file"
env >> "$log_file"
echo "--- Command Output ---" >> "$log_file"
if silent "$cmd"; then
msg_ok "Command succeeded"
else
msg_error "Command failed - check $log_file for details"
fi
}
debug_silent "apt-get update"
```
### Error Recovery
```bash
#!/usr/bin/env bash
source core.func
# Error recovery pattern
retry_operation() {
local max_attempts=3
local attempt=1
while [[ $attempt -le $max_attempts ]]; do
msg_info "Attempt $attempt of $max_attempts"
if silent "$@"; then
msg_ok "Operation succeeded on attempt $attempt"
return 0
else
msg_warn "Attempt $attempt failed"
((attempt++))
if [[ $attempt -le $max_attempts ]]; then
msg_info "Retrying in 5 seconds..."
sleep 5
fi
fi
done
msg_error "Operation failed after $max_attempts attempts"
return 1
}
# Usage
retry_operation "apt-get install -y package"
```

View File

@ -0,0 +1,181 @@
# core.func Documentation
## Overview
The `core.func` file provides fundamental utility functions and system checks that form the foundation for all other scripts in the Proxmox Community Scripts project. It handles basic system operations, user interface elements, validation, and core infrastructure.
## Purpose and Use Cases
- **System Validation**: Checks for Proxmox VE compatibility, architecture, shell requirements
- **User Interface**: Provides colored output, icons, spinners, and formatted messages
- **Core Utilities**: Basic functions used across all scripts
- **Error Handling**: Silent execution with detailed error reporting
- **System Information**: OS detection, verbose mode handling, swap management
## Quick Reference
### Key Function Groups
- **System Checks**: `pve_check()`, `arch_check()`, `shell_check()`, `root_check()`
- **User Interface**: `msg_info()`, `msg_ok()`, `msg_error()`, `msg_warn()`, `spinner()`
- **Core Utilities**: `silent()`, `is_alpine()`, `is_verbose_mode()`, `get_header()`
- **System Management**: `check_or_create_swap()`, `ensure_tput()`
### Dependencies
- **External**: `curl` for downloading headers, `tput` for terminal control
- **Internal**: `error_handler.func` for error explanations
### Integration Points
- Used by: All other `.func` files and installation scripts
- Uses: `error_handler.func` for error explanations
- Provides: Core utilities for `build.func`, `tools.func`, `api.func`
## Documentation Files
### 📊 [CORE_FLOWCHART.md](./CORE_FLOWCHART.md)
Visual execution flows showing how core functions interact and the system validation process.
### 📚 [CORE_FUNCTIONS_REFERENCE.md](./CORE_FUNCTIONS_REFERENCE.md)
Complete alphabetical reference of all functions with parameters, dependencies, and usage details.
### 💡 [CORE_USAGE_EXAMPLES.md](./CORE_USAGE_EXAMPLES.md)
Practical examples showing how to use core functions in scripts and common patterns.
### 🔗 [CORE_INTEGRATION.md](./CORE_INTEGRATION.md)
How core.func integrates with other components and provides foundational services.
## Key Features
### System Validation
- **Proxmox VE Version Check**: Supports PVE 8.0-8.9 and 9.0
- **Architecture Check**: Ensures AMD64 architecture (excludes PiMox)
- **Shell Check**: Validates Bash shell usage
- **Root Check**: Ensures root privileges
- **SSH Check**: Warns about external SSH usage
### User Interface
- **Colored Output**: ANSI color codes for styled terminal output
- **Icons**: Symbolic icons for different message types
- **Spinners**: Animated progress indicators
- **Formatted Messages**: Consistent message formatting across scripts
### Core Utilities
- **Silent Execution**: Execute commands with detailed error reporting
- **OS Detection**: Alpine Linux detection
- **Verbose Mode**: Handle verbose output settings
- **Header Management**: Download and display application headers
- **Swap Management**: Check and create swap files
## Common Usage Patterns
### Basic Script Setup
```bash
# Source core functions
source core.func
# Run system checks
pve_check
arch_check
shell_check
root_check
```
### Message Display
```bash
# Show progress
msg_info "Installing package..."
# Show success
msg_ok "Package installed successfully"
# Show error
msg_error "Installation failed"
# Show warning
msg_warn "This operation may take some time"
```
### Silent Command Execution
```bash
# Execute command silently with error handling
silent apt-get update
silent apt-get install -y package-name
```
## Environment Variables
### Core Variables
- `VERBOSE`: Enable verbose output mode
- `SILENT_LOGFILE`: Path to silent execution log file
- `APP`: Application name for header display
- `APP_TYPE`: Application type (ct/vm) for header paths
### Internal Variables
- `_CORE_FUNC_LOADED`: Prevents multiple loading
- `__FUNCTIONS_LOADED`: Prevents multiple function loading
- `RETRY_NUM`: Number of retry attempts (default: 10)
- `RETRY_EVERY`: Seconds between retries (default: 3)
## Error Handling
### Silent Execution Errors
- Commands executed via `silent()` capture output to log file
- On failure, displays error code explanation
- Shows last 10 lines of log output
- Provides command to view full log
### System Check Failures
- Each system check function exits with appropriate error message
- Clear indication of what's wrong and how to fix it
- Graceful exit with sleep delay for user to read message
## Best Practices
### Script Initialization
1. Source `core.func` first
2. Run system checks early
3. Set up error handling
4. Use appropriate message functions
### Message Usage
1. Use `msg_info()` for progress updates
2. Use `msg_ok()` for successful completions
3. Use `msg_error()` for failures
4. Use `msg_warn()` for warnings
### Silent Execution
1. Use `silent()` for commands that might fail
2. Check return codes after silent execution
3. Provide meaningful error messages
## Troubleshooting
### Common Issues
1. **Proxmox Version**: Ensure running supported PVE version
2. **Architecture**: Script only works on AMD64 systems
3. **Shell**: Must use Bash shell
4. **Permissions**: Must run as root
5. **Network**: SSH warnings for external connections
### Debug Mode
Enable verbose output for debugging:
```bash
export VERBOSE="yes"
source core.func
```
### Log Files
Check silent execution logs:
```bash
cat /tmp/silent.$$.log
```
## Related Documentation
- [build.func](../build.func/) - Main container creation script
- [error_handler.func](../error_handler.func/) - Error handling utilities
- [tools.func](../tools.func/) - Extended utility functions
- [api.func](../api.func/) - Proxmox API interactions
---
*This documentation covers the core.func file which provides fundamental utilities for all Proxmox Community Scripts.*

View File

@ -0,0 +1,347 @@
# error_handler.func Execution Flowchart
## Main Error Handling Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Error Handler Initialization │
│ Entry point when error_handler.func is sourced by other scripts │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ CATCH_ERRORS() │
│ Initialize error handling traps and strict mode │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Trap Setup Sequence │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────────────┐ │
│ │ Set Strict │ │ Set Error │ │ Set Signal │ │
│ │ Mode │ │ Trap │ │ Traps │ │
│ │ │ │ │ │ │ │
│ │ • -Ee │ │ • ERR trap │ │ • EXIT trap │ │
│ │ • -o pipefail │ │ • error_handler │ │ • INT trap │ │
│ │ • -u (if │ │ function │ │ • TERM trap │ │
│ │ STRICT_UNSET) │ │ │ │ │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## Error Handler Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ ERROR_HANDLER() Flow │
│ Main error handler triggered by ERR trap or manual call │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Error Detection │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Error Information Collection │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Get Exit │ │ Get Command │ │ Get Line │ │ │
│ │ │ Code │ │ Information │ │ Number │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ • From $? or │ │ • From │ │ • From │ │ │
│ │ │ parameter │ │ BASH_COMMAND │ │ BASH_LINENO[0] │ │ │
│ │ │ • Store in │ │ • Clean $STD │ │ • Default to │ │ │
│ │ │ exit_code │ │ references │ │ "unknown" │ │ │
│ │ │ │ │ • Store in │ │ • Store in │ │ │
│ │ │ │ │ command │ │ line_number │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Success Check │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Exit Code Validation │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Check Exit │ │ Success │ │ Error │ │
│ │ │ Code │ │ Path │ │ Path │ │
│ │ │ │ │ │ │ │ │
│ │ │ • If exit_code │ │ • Return 0 │ │ • Continue to │ │
│ │ │ == 0 │ │ • No error │ │ error handling │ │
│ │ │ • Success │ │ processing │ │ • Process error │ │
│ │ │ • No error │ │ │ │ information │ │
│ │ │ handling │ │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Error Processing │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Error Explanation │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Get Error │ │ Display Error │ │ Log Error │ │ │
│ │ │ Explanation │ │ Information │ │ Information │ │ │
│ │ │ │ │ │ │ │ │
│ │ │ • Call │ │ • Show error │ │ • Write to debug │ │
│ │ │ explain_exit_ │ │ message │ │ log if enabled │ │
│ │ │ code() │ │ • Show line │ │ • Include │ │
│ │ │ • Get human- │ │ number │ │ timestamp │ │
│ │ │ readable │ │ • Show command │ │ • Include exit │ │
│ │ │ message │ │ • Show exit │ │ code │ │
│ │ │ │ │ code │ │ • Include command │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Silent Log Integration │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Silent Log Display │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Check Silent │ │ Display Log │ │ Exit with │ │
│ │ │ Log File │ │ Content │ │ Error Code │ │
│ │ │ │ │ │ │ │ │
│ │ │ • Check if │ │ • Show last 20 │ │ • Exit with │ │
│ │ │ SILENT_ │ │ lines │ │ original exit │ │
│ │ │ LOGFILE set │ │ • Show file │ │ code │ │
│ │ │ • Check if │ │ path │ │ • Terminate script │ │
│ │ │ file exists │ │ • Format │ │ execution │ │
│ │ │ • Check if │ │ output │ │ │ │
│ │ │ file has │ │ │ │ │ │
│ │ │ content │ │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## Signal Handling Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Signal Handler Flow │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Signal Detection │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ SIGINT │ │ SIGTERM │ │ EXIT │ │ │
│ │ │ (Ctrl+C) │ │ (Termination) │ │ (Script End) │ │ │
│ │ │ │ │ │ │ │ │
│ │ │ • User │ │ • System │ │ • Normal script │ │
│ │ │ interruption │ │ termination │ │ completion │ │
│ │ │ • Graceful │ │ • Graceful │ │ • Error exit │ │
│ │ │ handling │ │ handling │ │ • Signal exit │ │
│ │ │ • Exit code │ │ • Exit code │ │ • Cleanup │ │
│ │ │ 130 │ │ 143 │ │ operations │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ ON_INTERRUPT() Flow │
│ Handles SIGINT (Ctrl+C) signals │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Interrupt Processing │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ User Interruption Handling │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Display │ │ Cleanup │ │ Exit with │ │ │
│ │ │ Message │ │ Operations │ │ Code 130 │ │ │
│ │ │ │ │ │ │ │ │
│ │ │ • Show │ │ • Stop │ │ • Exit with │ │
│ │ │ interruption │ │ processes │ │ SIGINT code │ │
│ │ │ message │ │ • Clean up │ │ • Terminate script │ │
│ │ │ • Use red │ │ temporary │ │ execution │ │
│ │ │ color │ │ files │ │ │ │
│ │ │ • Clear │ │ • Remove lock │ │ │ │
│ │ │ terminal │ │ files │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## Exit Handler Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ ON_EXIT() Flow │
│ Handles script exit cleanup │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Exit Cleanup │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Cleanup Operations │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Lock File │ │ Temporary │ │ Exit with │ │ │
│ │ │ Cleanup │ │ File │ │ Original Code │ │ │
│ │ │ │ │ Cleanup │ │ │ │
│ │ │ • Check if │ │ • Remove │ │ • Exit with │ │
│ │ │ lockfile │ │ temporary │ │ original exit │ │
│ │ │ variable set │ │ files │ │ code │ │
│ │ │ • Check if │ │ • Clean up │ │ • Preserve exit │ │
│ │ │ lockfile │ │ process │ │ status │ │
│ │ │ exists │ │ state │ │ • Terminate │ │
│ │ │ • Remove │ │ │ │ execution │ │
│ │ │ lockfile │ │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## Error Code Explanation Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ EXPLAIN_EXIT_CODE() Flow │
│ Converts numeric exit codes to human-readable explanations │
└─────────────────────┬───────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Error Code Classification │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Error Code Categories │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Generic/ │ │ Package │ │ Node.js │ │ │
│ │ │ Shell │ │ Manager │ │ Errors │ │ │
│ │ │ Errors │ │ Errors │ │ │ │
│ │ │ │ │ │ │ • 243: Out of │ │
│ │ │ • 1: General │ │ • 100: APT │ │ memory │ │
│ │ │ error │ │ package │ │ • 245: Invalid │ │
│ │ │ • 2: Shell │ │ error │ │ option │ │
│ │ │ builtin │ │ • 101: APT │ │ • 246: Parse │ │
│ │ │ misuse │ │ config error │ │ error │ │
│ │ │ • 126: Cannot │ │ • 255: DPKG │ │ • 247: Fatal │ │
│ │ │ execute │ │ fatal error │ │ error │ │
│ │ │ • 127: Command │ │ │ │ • 248: Addon │ │
│ │ │ not found │ │ │ │ failure │ │
│ │ │ • 128: Invalid │ │ │ │ • 249: Inspector │ │
│ │ │ exit │ │ │ │ error │ │
│ │ │ • 130: SIGINT │ │ │ │ • 254: Unknown │ │
│ │ │ • 137: SIGKILL │ │ │ │ fatal error │ │
│ │ │ • 139: Segfault │ │ │ │ │ │
│ │ │ • 143: SIGTERM │ │ │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Python │ │ Database │ │ Proxmox │ │ │
│ │ │ Errors │ │ Errors │ │ Custom │ │ │
│ │ │ │ │ │ │ Errors │ │
│ │ │ • 210: Virtual │ │ • PostgreSQL: │ │ • 200: Lock file │ │
│ │ │ env missing │ │ 231-234 │ │ failed │ │
│ │ │ • 211: Dep │ │ • MySQL: 241- │ │ • 203: Missing │ │
│ │ │ resolution │ │ 244 │ │ CTID │ │
│ │ │ • 212: Install │ │ • MongoDB: 251- │ │ • 204: Missing │ │
│ │ │ aborted │ │ 254 │ │ PCT_OSTYPE │ │
│ │ │ │ │ │ │ • 205: Invalid │ │
│ │ │ │ │ │ │ CTID │ │
│ │ │ │ │ │ │ • 209: Container │ │
│ │ │ │ │ │ │ creation failed │ │
│ │ │ │ │ │ │ • 210: Cluster │ │
│ │ │ │ │ │ │ not quorate │ │
│ │ │ │ │ │ │ • 214: No storage │ │
│ │ │ │ │ │ │ space │ │
│ │ │ │ │ │ │ • 215: CTID not │ │
│ │ │ │ │ │ │ listed │ │
│ │ │ │ │ │ │ • 216: RootFS │ │
│ │ │ │ │ │ │ missing │ │
│ │ │ │ │ │ │ • 217: Storage │ │
│ │ │ │ │ │ │ not supported │ │
│ │ │ │ │ │ │ • 220: Template │ │
│ │ │ │ │ │ │ path error │ │
│ │ │ │ │ │ │ • 222: Template │ │
│ │ │ │ │ │ │ download failed │ │
│ │ │ │ │ │ │ • 223: Template │ │
│ │ │ │ │ │ │ not available │ │
│ │ │ │ │ │ │ • 231: LXC stack │ │
│ │ │ │ │ │ │ upgrade failed │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Default Case │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Unknown Error Handling │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Check for │ │ Return │ │ Log Unknown │ │ │
│ │ │ Unknown │ │ Generic │ │ Error │ │ │
│ │ │ Code │ │ Message │ │ │ │
│ │ │ │ │ │ │ • Log to debug │ │
│ │ │ • If no match │ │ • "Unknown │ │ file if enabled │ │
│ │ │ found │ │ error" │ │ • Include error │ │
│ │ │ • Use default │ │ • Return to │ │ code │ │
│ │ │ case │ │ caller │ │ • Include │ │
│ │ │ │ │ │ │ timestamp │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## Debug Logging Flow
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Debug Log Integration │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ Debug Log Writing │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────┐ │ │
│ │ │ Check Debug │ │ Write Error │ │ Format Log │ │ │
│ │ │ Log File │ │ Information │ │ Entry │ │ │
│ │ │ │ │ │ │ │ │
│ │ │ • Check if │ │ • Timestamp │ │ • Error separator │ │
│ │ │ DEBUG_LOGFILE │ │ • Exit code │ │ • Structured │ │
│ │ │ set │ │ • Explanation │ │ format │ │
│ │ │ • Check if │ │ • Line number │ │ • Easy to parse │ │
│ │ │ file exists │ │ • Command │ │ • Easy to read │ │
│ │ │ • Check if │ │ • Append to │ │ │ │
│ │ │ file writable │ │ file │ │ │ │
│ │ └─────────────────┘ └─────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
## Integration Points
### With core.func
- **Silent Execution**: Provides error explanations for silent() function
- **Color Variables**: Uses color variables for error display
- **Log Integration**: Integrates with SILENT_LOGFILE
### With Other Scripts
- **Error Traps**: Sets up ERR trap for automatic error handling
- **Signal Traps**: Handles SIGINT, SIGTERM, and EXIT signals
- **Cleanup**: Provides cleanup on script exit
### External Dependencies
- **None**: Pure Bash implementation
- **Color Support**: Requires color variables from core.func
- **Log Files**: Uses standard file operations

View File

@ -0,0 +1,424 @@
# error_handler.func Functions Reference
## Overview
This document provides a comprehensive alphabetical reference of all functions in `error_handler.func`, including parameters, dependencies, usage examples, and error handling.
## Function Categories
### Error Explanation Functions
#### `explain_exit_code()`
**Purpose**: Convert numeric exit codes to human-readable explanations
**Parameters**:
- `$1` - Exit code to explain
**Returns**: Human-readable error explanation string
**Side Effects**: None
**Dependencies**: None
**Environment Variables Used**: None
**Supported Exit Codes**:
- **Generic/Shell**: 1, 2, 126, 127, 128, 130, 137, 139, 143
- **Package Manager**: 100, 101, 255
- **Node.js**: 243, 245, 246, 247, 248, 249, 254
- **Python**: 210, 211, 212
- **PostgreSQL**: 231, 232, 233, 234
- **MySQL/MariaDB**: 241, 242, 243, 244
- **MongoDB**: 251, 252, 253, 254
- **Proxmox Custom**: 200, 203, 204, 205, 209, 210, 214, 215, 216, 217, 220, 222, 223, 231
**Usage Example**:
```bash
explanation=$(explain_exit_code 127)
echo "Error 127: $explanation"
# Output: Error 127: Command not found
```
**Error Code Examples**:
```bash
explain_exit_code 1 # "General error / Operation not permitted"
explain_exit_code 126 # "Command invoked cannot execute (permission problem?)"
explain_exit_code 127 # "Command not found"
explain_exit_code 130 # "Terminated by Ctrl+C (SIGINT)"
explain_exit_code 200 # "Custom: Failed to create lock file"
explain_exit_code 999 # "Unknown error"
```
### Error Handling Functions
#### `error_handler()`
**Purpose**: Main error handler triggered by ERR trap or manual call
**Parameters**:
- `$1` - Exit code (optional, defaults to $?)
- `$2` - Command that failed (optional, defaults to BASH_COMMAND)
**Returns**: None (exits with error code)
**Side Effects**:
- Displays detailed error information
- Logs error to debug file if enabled
- Shows silent log content if available
- Exits with original error code
**Dependencies**: `explain_exit_code()`
**Environment Variables Used**: `DEBUG_LOGFILE`, `SILENT_LOGFILE`
**Usage Example**:
```bash
# Automatic error handling via ERR trap
set -e
trap 'error_handler' ERR
# Manual error handling
error_handler 127 "command_not_found"
```
**Error Information Displayed**:
- Error message with color coding
- Line number where error occurred
- Exit code with explanation
- Command that failed
- Silent log content (last 20 lines)
- Debug log entry (if enabled)
### Signal Handling Functions
#### `on_interrupt()`
**Purpose**: Handle SIGINT (Ctrl+C) signals gracefully
**Parameters**: None
**Returns**: None (exits with code 130)
**Side Effects**:
- Displays interruption message
- Exits with SIGINT code (130)
**Dependencies**: None
**Environment Variables Used**: None
**Usage Example**:
```bash
# Set up interrupt handler
trap on_interrupt INT
# User presses Ctrl+C
# Handler displays: "Interrupted by user (SIGINT)"
# Script exits with code 130
```
#### `on_terminate()`
**Purpose**: Handle SIGTERM signals gracefully
**Parameters**: None
**Returns**: None (exits with code 143)
**Side Effects**:
- Displays termination message
- Exits with SIGTERM code (143)
**Dependencies**: None
**Environment Variables Used**: None
**Usage Example**:
```bash
# Set up termination handler
trap on_terminate TERM
# System sends SIGTERM
# Handler displays: "Terminated by signal (SIGTERM)"
# Script exits with code 143
```
### Cleanup Functions
#### `on_exit()`
**Purpose**: Handle script exit cleanup
**Parameters**: None
**Returns**: None (exits with original exit code)
**Side Effects**:
- Removes lock file if set
- Exits with original exit code
**Dependencies**: None
**Environment Variables Used**: `lockfile`
**Usage Example**:
```bash
# Set up exit handler
trap on_exit EXIT
# Set lock file
lockfile="/tmp/my_script.lock"
# Script exits normally or with error
# Handler removes lock file and exits
```
### Initialization Functions
#### `catch_errors()`
**Purpose**: Initialize error handling traps and strict mode
**Parameters**: None
**Returns**: None
**Side Effects**:
- Sets strict error handling mode
- Sets up error traps
- Sets up signal traps
- Sets up exit trap
**Dependencies**: None
**Environment Variables Used**: `STRICT_UNSET`
**Strict Mode Settings**:
- `-E`: Exit on command failure
- `-e`: Exit on any error
- `-o pipefail`: Exit on pipe failure
- `-u`: Exit on unset variables (if STRICT_UNSET=1)
**Trap Setup**:
- `ERR`: Calls `error_handler` on command failure
- `EXIT`: Calls `on_exit` on script exit
- `INT`: Calls `on_interrupt` on SIGINT
- `TERM`: Calls `on_terminate` on SIGTERM
**Usage Example**:
```bash
# Initialize error handling
catch_errors
# Script now has full error handling
# All errors will be caught and handled
```
## Function Call Hierarchy
### Error Handling Flow
```
Command Failure
├── ERR trap triggered
├── error_handler() called
│ ├── Get exit code
│ ├── Get command info
│ ├── Get line number
│ ├── explain_exit_code()
│ ├── Display error info
│ ├── Log to debug file
│ ├── Show silent log
│ └── Exit with error code
```
### Signal Handling Flow
```
Signal Received
├── Signal trap triggered
├── Appropriate handler called
│ ├── on_interrupt() for SIGINT
│ ├── on_terminate() for SIGTERM
│ └── on_exit() for EXIT
└── Exit with signal code
```
### Initialization Flow
```
catch_errors()
├── Set strict mode
│ ├── -E (exit on failure)
│ ├── -e (exit on error)
│ ├── -o pipefail (pipe failure)
│ └── -u (unset variables, if enabled)
└── Set up traps
├── ERR → error_handler
├── EXIT → on_exit
├── INT → on_interrupt
└── TERM → on_terminate
```
## Error Code Reference
### Generic/Shell Errors
| Code | Description |
|------|-------------|
| 1 | General error / Operation not permitted |
| 2 | Misuse of shell builtins (e.g. syntax error) |
| 126 | Command invoked cannot execute (permission problem?) |
| 127 | Command not found |
| 128 | Invalid argument to exit |
| 130 | Terminated by Ctrl+C (SIGINT) |
| 137 | Killed (SIGKILL / Out of memory?) |
| 139 | Segmentation fault (core dumped) |
| 143 | Terminated (SIGTERM) |
### Package Manager Errors
| Code | Description |
|------|-------------|
| 100 | APT: Package manager error (broken packages / dependency problems) |
| 101 | APT: Configuration error (bad sources.list, malformed config) |
| 255 | DPKG: Fatal internal error |
### Node.js Errors
| Code | Description |
|------|-------------|
| 243 | Node.js: Out of memory (JavaScript heap out of memory) |
| 245 | Node.js: Invalid command-line option |
| 246 | Node.js: Internal JavaScript Parse Error |
| 247 | Node.js: Fatal internal error |
| 248 | Node.js: Invalid C++ addon / N-API failure |
| 249 | Node.js: Inspector error |
| 254 | npm/pnpm/yarn: Unknown fatal error |
### Python Errors
| Code | Description |
|------|-------------|
| 210 | Python: Virtualenv / uv environment missing or broken |
| 211 | Python: Dependency resolution failed |
| 212 | Python: Installation aborted (permissions or EXTERNALLY-MANAGED) |
### Database Errors
| Code | Description |
|------|-------------|
| 231 | PostgreSQL: Connection failed (server not running / wrong socket) |
| 232 | PostgreSQL: Authentication failed (bad user/password) |
| 233 | PostgreSQL: Database does not exist |
| 234 | PostgreSQL: Fatal error in query / syntax |
| 241 | MySQL/MariaDB: Connection failed (server not running / wrong socket) |
| 242 | MySQL/MariaDB: Authentication failed (bad user/password) |
| 243 | MySQL/MariaDB: Database does not exist |
| 244 | MySQL/MariaDB: Fatal error in query / syntax |
| 251 | MongoDB: Connection failed (server not running) |
| 252 | MongoDB: Authentication failed (bad user/password) |
| 253 | MongoDB: Database not found |
| 254 | MongoDB: Fatal query error |
### Proxmox Custom Errors
| Code | Description |
|------|-------------|
| 200 | Custom: Failed to create lock file |
| 203 | Custom: Missing CTID variable |
| 204 | Custom: Missing PCT_OSTYPE variable |
| 205 | Custom: Invalid CTID (<100) |
| 209 | Custom: Container creation failed |
| 210 | Custom: Cluster not quorate |
| 214 | Custom: Not enough storage space |
| 215 | Custom: Container ID not listed |
| 216 | Custom: RootFS entry missing in config |
| 217 | Custom: Storage does not support rootdir |
| 220 | Custom: Unable to resolve template path |
| 222 | Custom: Template download failed after 3 attempts |
| 223 | Custom: Template not available after download |
| 231 | Custom: LXC stack upgrade/retry failed |
## Environment Variable Dependencies
### Required Variables
- **`lockfile`**: Lock file path for cleanup (set by calling script)
### Optional Variables
- **`DEBUG_LOGFILE`**: Path to debug log file for error logging
- **`SILENT_LOGFILE`**: Path to silent execution log file
- **`STRICT_UNSET`**: Enable strict unset variable checking (0/1)
### Internal Variables
- **`exit_code`**: Current exit code
- **`command`**: Failed command
- **`line_number`**: Line number where error occurred
- **`explanation`**: Error explanation text
## Error Handling Patterns
### Automatic Error Handling
```bash
#!/usr/bin/env bash
source error_handler.func
# Initialize error handling
catch_errors
# All commands are now monitored
# Errors will be automatically caught and handled
```
### Manual Error Handling
```bash
#!/usr/bin/env bash
source error_handler.func
# Manual error handling
if ! command -v required_tool >/dev/null 2>&1; then
error_handler 127 "required_tool not found"
fi
```
### Custom Error Codes
```bash
#!/usr/bin/env bash
source error_handler.func
# Use custom error codes
if [[ ! -f /required/file ]]; then
echo "Error: Required file missing"
exit 200 # Custom error code
fi
```
### Signal Handling
```bash
#!/usr/bin/env bash
source error_handler.func
# Set up signal handling
trap on_interrupt INT
trap on_terminate TERM
trap on_exit EXIT
# Script handles signals gracefully
```
## Integration Examples
### With core.func
```bash
#!/usr/bin/env bash
source core.func
source error_handler.func
# Silent execution uses error_handler for explanations
silent apt-get install -y package
# If command fails, error_handler provides explanation
```
### With build.func
```bash
#!/usr/bin/env bash
source core.func
source error_handler.func
source build.func
# Container creation with error handling
# Errors are caught and explained
```
### With tools.func
```bash
#!/usr/bin/env bash
source core.func
source error_handler.func
source tools.func
# Tool operations with error handling
# All errors are properly handled and explained
```
## Best Practices
### Error Handling Setup
1. Source error_handler.func early in script
2. Call catch_errors() to initialize traps
3. Use appropriate exit codes for different error types
4. Provide meaningful error messages
### Signal Handling
1. Always set up signal traps
2. Provide graceful cleanup on interruption
3. Use appropriate exit codes for signals
4. Clean up temporary files and processes
### Error Reporting
1. Use explain_exit_code() for user-friendly messages
2. Log errors to debug files when needed
3. Provide context information (line numbers, commands)
4. Integrate with silent execution logging
### Custom Error Codes
1. Use Proxmox custom error codes (200-231) for container/VM errors
2. Use standard error codes for common operations
3. Document custom error codes in script comments
4. Provide clear error messages for custom codes

View File

@ -0,0 +1,512 @@
# error_handler.func Integration Guide
## Overview
This document describes how `error_handler.func` integrates with other components in the Proxmox Community Scripts project, including dependencies, data flow, and API surface.
## Dependencies
### External Dependencies
#### Required Commands
- **None**: Pure Bash implementation
#### Optional Commands
- **None**: No external command dependencies
### Internal Dependencies
#### core.func
- **Purpose**: Provides color variables for error display
- **Usage**: Uses `RD`, `CL`, `YWB` color variables
- **Integration**: Called automatically when core.func is sourced
- **Data Flow**: Color variables → error display formatting
## Integration Points
### With core.func
#### Silent Execution Integration
```bash
# core.func silent() function uses error_handler.func
silent() {
local cmd="$*"
local caller_line="${BASH_LINENO[0]:-unknown}"
# Execute command
"$@" >>"$SILENT_LOGFILE" 2>&1
local rc=$?
if [[ $rc -ne 0 ]]; then
# Load error_handler.func if needed
if ! declare -f explain_exit_code >/dev/null 2>&1; then
source error_handler.func
fi
# Get error explanation
local explanation
explanation="$(explain_exit_code "$rc")"
# Display error with explanation
printf "\e[?25h"
echo -e "\n${RD}[ERROR]${CL} in line ${RD}${caller_line}${CL}: exit code ${RD}${rc}${CL} (${explanation})"
echo -e "${RD}Command:${CL} ${YWB}${cmd}${CL}\n"
exit "$rc"
fi
}
```
#### Color Variable Usage
```bash
# error_handler.func uses color variables from core.func
error_handler() {
# ... error handling logic ...
# Use color variables for error display
echo -e "\n${RD}[ERROR]${CL} in line ${RD}${line_number}${CL}: exit code ${RD}${exit_code}${CL} (${explanation}): while executing command ${YWB}${command}${CL}\n"
}
on_interrupt() {
echo -e "\n${RD}Interrupted by user (SIGINT)${CL}"
exit 130
}
on_terminate() {
echo -e "\n${RD}Terminated by signal (SIGTERM)${CL}"
exit 143
}
```
### With build.func
#### Container Creation Error Handling
```bash
# build.func uses error_handler.func for container operations
source core.func
source error_handler.func
# Container creation with error handling
create_container() {
# Set up error handling
catch_errors
# Container creation operations
silent pct create "$CTID" "$TEMPLATE" \
--hostname "$HOSTNAME" \
--memory "$MEMORY" \
--cores "$CORES"
# If creation fails, error_handler provides explanation
}
```
#### Template Download Error Handling
```bash
# build.func uses error_handler.func for template operations
download_template() {
# Template download with error handling
if ! silent curl -fsSL "$TEMPLATE_URL" -o "$TEMPLATE_FILE"; then
# error_handler provides detailed explanation
exit 222 # Template download failed
fi
}
```
### With tools.func
#### Maintenance Operations Error Handling
```bash
# tools.func uses error_handler.func for maintenance operations
source core.func
source error_handler.func
# Maintenance operations with error handling
update_system() {
catch_errors
# System update operations
silent apt-get update
silent apt-get upgrade -y
# Error handling provides explanations for failures
}
cleanup_logs() {
catch_errors
# Log cleanup operations
silent find /var/log -name "*.log" -mtime +30 -delete
# Error handling provides explanations for permission issues
}
```
### With api.func
#### API Operations Error Handling
```bash
# api.func uses error_handler.func for API operations
source core.func
source error_handler.func
# API operations with error handling
api_call() {
catch_errors
# API call with error handling
if ! silent curl -k -H "Authorization: PVEAPIToken=$API_TOKEN" \
"$API_URL/api2/json/nodes/$NODE/lxc"; then
# error_handler provides explanation for API failures
exit 1
fi
}
```
### With install.func
#### Installation Process Error Handling
```bash
# install.func uses error_handler.func for installation operations
source core.func
source error_handler.func
# Installation with error handling
install_package() {
local package="$1"
catch_errors
# Package installation
silent apt-get install -y "$package"
# Error handling provides explanations for installation failures
}
```
### With alpine-install.func
#### Alpine Installation Error Handling
```bash
# alpine-install.func uses error_handler.func for Alpine operations
source core.func
source error_handler.func
# Alpine installation with error handling
install_alpine_package() {
local package="$1"
catch_errors
# Alpine package installation
silent apk add --no-cache "$package"
# Error handling provides explanations for Alpine-specific failures
}
```
### With alpine-tools.func
#### Alpine Tools Error Handling
```bash
# alpine-tools.func uses error_handler.func for Alpine tools
source core.func
source error_handler.func
# Alpine tools with error handling
alpine_tool_operation() {
catch_errors
# Alpine-specific tool operations
silent alpine_command
# Error handling provides explanations for Alpine tool failures
}
```
### With passthrough.func
#### Hardware Passthrough Error Handling
```bash
# passthrough.func uses error_handler.func for hardware operations
source core.func
source error_handler.func
# Hardware passthrough with error handling
configure_gpu_passthrough() {
catch_errors
# GPU passthrough operations
silent lspci | grep -i nvidia
# Error handling provides explanations for hardware failures
}
```
### With vm-core.func
#### VM Operations Error Handling
```bash
# vm-core.func uses error_handler.func for VM operations
source core.func
source error_handler.func
# VM operations with error handling
create_vm() {
catch_errors
# VM creation operations
silent qm create "$VMID" \
--name "$VMNAME" \
--memory "$MEMORY" \
--cores "$CORES"
# Error handling provides explanations for VM creation failures
}
```
## Data Flow
### Input Data
#### Environment Variables
- **`DEBUG_LOGFILE`**: Path to debug log file for error logging
- **`SILENT_LOGFILE`**: Path to silent execution log file
- **`STRICT_UNSET`**: Enable strict unset variable checking (0/1)
- **`lockfile`**: Lock file path for cleanup (set by calling script)
#### Function Parameters
- **Exit codes**: Passed to `explain_exit_code()` and `error_handler()`
- **Command information**: Passed to `error_handler()` for context
- **Signal information**: Passed to signal handlers
#### System Information
- **Exit codes**: Retrieved from `$?` variable
- **Command information**: Retrieved from `BASH_COMMAND` variable
- **Line numbers**: Retrieved from `BASH_LINENO[0]` variable
- **Process information**: Retrieved from system calls
### Processing Data
#### Error Code Processing
- **Code classification**: Categorize exit codes by type
- **Explanation lookup**: Map codes to human-readable messages
- **Context collection**: Gather command and line information
- **Log preparation**: Format error information for logging
#### Signal Processing
- **Signal detection**: Identify received signals
- **Handler selection**: Choose appropriate signal handler
- **Cleanup operations**: Perform necessary cleanup
- **Exit code setting**: Set appropriate exit codes
#### Log Processing
- **Debug logging**: Write error information to debug log
- **Silent log integration**: Display silent log content
- **Log formatting**: Format log entries for readability
- **Log analysis**: Provide log analysis capabilities
### Output Data
#### Error Information
- **Error messages**: Human-readable error explanations
- **Context information**: Line numbers, commands, timestamps
- **Color formatting**: ANSI color codes for terminal display
- **Log content**: Silent log excerpts and debug information
#### System State
- **Exit codes**: Returned from functions
- **Log files**: Created and updated for error tracking
- **Cleanup status**: Lock file removal and process cleanup
- **Signal handling**: Graceful signal processing
## API Surface
### Public Functions
#### Error Explanation
- **`explain_exit_code()`**: Convert exit codes to explanations
- **Parameters**: Exit code to explain
- **Returns**: Human-readable explanation string
- **Usage**: Called by error_handler() and other functions
#### Error Handling
- **`error_handler()`**: Main error handler function
- **Parameters**: Exit code (optional), command (optional)
- **Returns**: None (exits with error code)
- **Usage**: Called by ERR trap or manually
#### Signal Handling
- **`on_interrupt()`**: Handle SIGINT signals
- **`on_terminate()`**: Handle SIGTERM signals
- **`on_exit()`**: Handle script exit cleanup
- **Parameters**: None
- **Returns**: None (exits with signal code)
- **Usage**: Called by signal traps
#### Initialization
- **`catch_errors()`**: Initialize error handling
- **Parameters**: None
- **Returns**: None
- **Usage**: Called to set up error handling traps
### Internal Functions
#### None
- All functions in error_handler.func are public
- No internal helper functions
- Direct implementation of all functionality
### Global Variables
#### Configuration Variables
- **`DEBUG_LOGFILE`**: Debug log file path
- **`SILENT_LOGFILE`**: Silent log file path
- **`STRICT_UNSET`**: Strict mode setting
- **`lockfile`**: Lock file path
#### State Variables
- **`exit_code`**: Current exit code
- **`command`**: Failed command
- **`line_number`**: Line number where error occurred
- **`explanation`**: Error explanation text
## Integration Patterns
### Standard Integration Pattern
```bash
#!/usr/bin/env bash
# Standard integration pattern
# 1. Source core.func first
source core.func
# 2. Source error_handler.func
source error_handler.func
# 3. Initialize error handling
catch_errors
# 4. Use silent execution
silent command
# 5. Errors are automatically handled
```
### Minimal Integration Pattern
```bash
#!/usr/bin/env bash
# Minimal integration pattern
source error_handler.func
catch_errors
# Basic error handling
command
```
### Advanced Integration Pattern
```bash
#!/usr/bin/env bash
# Advanced integration pattern
source core.func
source error_handler.func
# Set up comprehensive error handling
export DEBUG_LOGFILE="/tmp/debug.log"
export SILENT_LOGFILE="/tmp/silent.log"
lockfile="/tmp/script.lock"
touch "$lockfile"
catch_errors
trap on_interrupt INT
trap on_terminate TERM
trap on_exit EXIT
# Advanced error handling
silent command
```
## Error Handling Integration
### Automatic Error Handling
- **ERR Trap**: Automatically catches command failures
- **Error Explanation**: Provides human-readable error messages
- **Context Information**: Shows line numbers and commands
- **Log Integration**: Displays silent log content
### Manual Error Handling
- **Custom Error Codes**: Use Proxmox custom error codes
- **Error Recovery**: Implement retry logic with error handling
- **Conditional Handling**: Different handling for different error types
- **Error Analysis**: Analyze error patterns and trends
### Signal Handling Integration
- **Graceful Interruption**: Handle Ctrl+C gracefully
- **Clean Termination**: Handle SIGTERM signals
- **Exit Cleanup**: Clean up resources on script exit
- **Lock File Management**: Remove lock files on exit
## Performance Considerations
### Error Handling Overhead
- **Minimal Impact**: Error handling adds minimal overhead
- **Trap Setup**: Trap setup is done once during initialization
- **Error Processing**: Error processing is only done on failures
- **Log Writing**: Log writing is only done when enabled
### Memory Usage
- **Minimal Footprint**: Error handler uses minimal memory
- **Variable Reuse**: Global variables reused across functions
- **No Memory Leaks**: Proper cleanup prevents memory leaks
- **Efficient Processing**: Efficient error code processing
### Execution Speed
- **Fast Error Detection**: Quick error detection and handling
- **Efficient Explanation**: Fast error code explanation lookup
- **Minimal Delay**: Minimal delay in error handling
- **Quick Exit**: Fast exit on error conditions
## Security Considerations
### Error Information Disclosure
- **Controlled Disclosure**: Only necessary error information is shown
- **Log Security**: Log files have appropriate permissions
- **Sensitive Data**: Sensitive data is not logged
- **Error Sanitization**: Error messages are sanitized
### Signal Handling Security
- **Signal Validation**: Only expected signals are handled
- **Cleanup Security**: Secure cleanup of temporary files
- **Lock File Security**: Secure lock file management
- **Process Security**: Secure process termination
### Log File Security
- **File Permissions**: Log files have appropriate permissions
- **Log Rotation**: Log files are rotated to prevent disk filling
- **Log Cleanup**: Old log files are cleaned up
- **Log Access**: Log access is controlled
## Future Integration Considerations
### Extensibility
- **New Error Codes**: Easy to add new error code explanations
- **Custom Handlers**: Easy to add custom error handlers
- **Signal Extensions**: Easy to add new signal handlers
- **Log Formats**: Easy to add new log formats
### Compatibility
- **Bash Version**: Compatible with different Bash versions
- **System Compatibility**: Compatible with different systems
- **Script Compatibility**: Compatible with different script types
- **Error Code Compatibility**: Compatible with different error codes
### Performance
- **Optimization**: Error handling can be optimized for better performance
- **Caching**: Error explanations can be cached for faster lookup
- **Parallel Processing**: Error handling can be parallelized
- **Resource Management**: Better resource management for error handling

Some files were not shown because too many files have changed in this diff Show More