forked from community-scripts/core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.func
More file actions
2525 lines (2282 loc) · 88.4 KB
/
Copy pathcore.func
File metadata and controls
2525 lines (2282 loc) · 88.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# Copyright (c) 2021-2026 community-scripts ORG
# License: MIT | https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main/LICENSE
# ==============================================================================
# CORE FUNCTIONS - LXC CONTAINER UTILITIES
# ==============================================================================
#
# This file provides core utility functions for LXC container management
# including colors, formatting, validation checks, message output, and
# execution helpers used throughout the Community-Scripts ecosystem.
#
# Usage:
# source <(curl -fsSL https://raw.githubusercontent.com/community-scripts/core/main/core/core.func)
# load_functions
#
# ==============================================================================
[[ -n "${_CORE_FUNC_LOADED:-}" ]] && return
_CORE_FUNC_LOADED=1
if [[ -z "${HOME:-}" ]]; then
HOME="$(getent passwd "$(id -u)" 2>/dev/null | cut -d: -f6)"
export HOME="${HOME:-/root}"
fi
# ==============================================================================
# SECTION 1: INITIALIZATION & SETUP
# ==============================================================================
# ------------------------------------------------------------------------------
# load_functions()
#
# - Initializes all core utility groups (colors, formatting, icons, defaults)
# - Ensures functions are loaded only once via __FUNCTIONS_LOADED flag
# - Must be called at start of any script using these utilities
# ------------------------------------------------------------------------------
load_functions() {
[[ -n "${__FUNCTIONS_LOADED:-}" ]] && return
__FUNCTIONS_LOADED=1
color
formatting
icons
default_vars
set_std_mode
}
# ------------------------------------------------------------------------------
# color()
#
# - Sets ANSI color codes for styled terminal output
# - Variables: YW (yellow), YWB (yellow bright), BL (blue), RD (red)
# GN (green), DGN (dark green), BGN (background green), CL (clear)
# ------------------------------------------------------------------------------
color() {
YW=$(echo "\033[33m")
YWB=$'\e[93m'
BL=$(echo "\033[36m")
RD=$(echo "\033[01;31m")
BGN=$(echo "\033[4;92m")
GN=$(echo "\033[1;92m")
DGN=$(echo "\033[32m")
CL=$(echo "\033[m")
# A dev run repaints the greens red. Every success line, every checkmark and
# the header turn the colour of a warning, so a screenshot or a recording is
# never mistaken for a normal install.
if [[ -n "${dev_mode:-}" ]]; then
BGN=$(echo "\033[4;91m")
GN=$(echo "\033[1;91m")
DGN=$(echo "\033[31m")
fi
}
# ------------------------------------------------------------------------------
# color_spinner()
#
# - Sets ANSI color codes specifically for spinner animation
# - Variables: CS_YW (spinner yellow), CS_YWB (spinner yellow bright),
# CS_CL (spinner clear)
# - Used by spinner() function to avoid color conflicts
# ------------------------------------------------------------------------------
color_spinner() {
CS_YW=$'\033[33m'
CS_YWB=$'\033[93m'
CS_CL=$'\033[m'
}
# ------------------------------------------------------------------------------
# formatting()
#
# - Defines formatting helpers for terminal output
# - BFR: Backspace and clear line sequence
# - BOLD: Bold text escape code
# - TAB/TAB3: Indentation spacing
# ------------------------------------------------------------------------------
formatting() {
BFR="\\r\\033[K"
BOLD=$(echo "\033[1m")
HOLD=" "
TAB=" "
TAB3=" "
}
# ------------------------------------------------------------------------------
# icons()
#
# - Sets symbolic emoji icons used throughout user feedback
# - Provides consistent visual indicators for success, error, info, etc.
# - Icons: CM (checkmark), CROSS (error), INFO (info), HOURGLASS (wait), etc.
# ------------------------------------------------------------------------------
icons() {
CM="${TAB}✔️${TAB}"
CROSS="${TAB}✖️${TAB}"
DNSOK="✔️ "
DNSFAIL="${TAB}✖️${TAB}"
INFO="${TAB}💡${TAB}${CL}"
OVERRIDE="${TAB}🔀${TAB}${CL}"
OS="${TAB}🖥️${TAB}${CL}"
OSVERSION="${TAB}🌟${TAB}${CL}"
CONTAINERTYPE="${TAB}📦${TAB}${CL}"
DISKSIZE="${TAB}💾${TAB}${CL}"
CPUCORE="${TAB}🧠${TAB}${CL}"
RAMSIZE="${TAB}🛠️${TAB}${CL}"
SEARCH="${TAB}🔍${TAB}${CL}"
VERBOSE_CROPPED="🔍${TAB}"
VERIFYPW="${TAB}🔐${TAB}${CL}"
CONTAINERID="${TAB}🆔${TAB}${CL}"
HOSTNAME="${TAB}🏠${TAB}${CL}"
BRIDGE="${TAB}🌉${TAB}${CL}"
NETWORK="${TAB}📡${TAB}${CL}"
GATEWAY="${TAB}🌐${TAB}${CL}"
ICON_DISABLEIPV6="${TAB}🚫${TAB}${CL}"
DEFAULT="${TAB}⚙️${TAB}${CL}"
MACADDRESS="${TAB}🔗${TAB}${CL}"
VLANTAG="${TAB}🏷️${TAB}${CL}"
ROOTSSH="${TAB}🔑${TAB}${CL}"
CREATING="${TAB}🚀${TAB}${CL}"
ADVANCED="${TAB}🧩${TAB}${CL}"
FUSE="${TAB}🗂️${TAB}${CL}"
GPU="${TAB}🎮${TAB}${CL}"
HOURGLASS="${TAB}⏳${TAB}"
}
# Re-provision a toolchain the container was built with but no longer has.
#
# Every setup_* records what it installed under /var/cache/app-versions. When the
# binary that record promises is gone, a script that compiles on update dies at
# exit 127 with its service already stopped. 144 ct scripts call a toolchain in
# their update path without ensuring it first, so this belongs here.
ensure_recorded_toolchains() {
local cache=/var/cache/app-versions
[[ -d "$cache" ]] || return 0
local rec tool bin fn
for rec in "$cache"/*_version.txt; do
[[ -r "$rec" ]] || continue
tool="$(basename "$rec")"
tool="${tool%_version.txt}"
case "$tool" in
rust) bin=cargo fn=setup_rust ;;
go) bin=go fn=setup_go ;;
nodejs) bin=node fn=setup_nodejs ;;
uv) bin=uv fn=setup_uv ;;
composer) bin=composer fn=setup_composer ;;
yq) bin=yq fn=setup_yq ;;
ruby) bin=ruby fn=setup_ruby ;;
*) continue ;;
esac
command -v "$bin" >/dev/null 2>&1 && continue
declare -f "$fn" >/dev/null 2>&1 || continue
msg_warn "${bin} is recorded for this container but missing - reinstalling"
"$fn" || msg_error "Could not restore ${bin}"
done
return 0
}
# ------------------------------------------------------------------------------
# ensure_profile_loaded()
#
# - Sources /etc/profile.d/*.sh scripts if not already loaded
# - Fixes PATH issues when running via pct enter/exec (non-login shells)
# - Safe to call multiple times (uses guard variable)
# - Should be called in update_script() or any script running inside LXC
# ------------------------------------------------------------------------------
ensure_profile_loaded() {
# Skip if already loaded or running on Proxmox host
[[ -n "${_PROFILE_LOADED:-}" ]] && return
command -v pveversion &>/dev/null && return
# Sourced for their PATH side effects, output discarded: 00_lxc-details.sh
# starts with a clear-screen escape and echoes the whole login banner, and the
# redirect also makes its own `[ -t 1 ]` guard false. A script ending on a
# false conditional makes `source` return that status, which as the final
# command of an && list is not exempt from errexit -- that took whole updates
# with it.
if [[ -d /etc/profile.d ]]; then
for script in /etc/profile.d/*.sh; do
[[ -r "$script" ]] || continue
source "$script" >/dev/null 2>&1 || true
done
fi
# rustup records $HOME/.cargo/bin here and nowhere else, and /usr/bin/update
# runs a non-login shell -- so an update that compiles died on "cargo: command
# not found" with cargo installed and fine.
if [[ -r "${HOME:-/root}/.profile" ]]; then
source "${HOME:-/root}/.profile" >/dev/null 2>&1 || true
fi
# Also ensure /usr/local/bin is in PATH (common install location)
if [[ ":$PATH:" != *":/usr/local/bin:"* ]]; then
export PATH="/usr/local/bin:$PATH"
fi
export _PROFILE_LOADED=1
}
# The retired Gitea mirror; GitHub serves the same repos. Mirrored in
# misc/update.sh, which cannot source this file.
# ------------------------------------------------------------------------------
_cs_live_base() {
local u="${1%/}"
case "$u" in
*//git.community-scripts.org/*)
u="${u#*//git.community-scripts.org/}"
u="${u/\/raw\/branch\//\/}"
u="${u/\/raw\/tag\//\/}"
u="${u/\/raw\/commit\//\/}"
printf 'https://raw.githubusercontent.com/%s' "$u"
;;
*) printf '%s' "$u" ;;
esac
}
# ------------------------------------------------------------------------------
# write_update_entrypoint()
#
# Generates /usr/bin/update as a small self-hosting bootstrap. Instead of pulling
# the app script directly (which fails with a raw 404 once a script is removed
# upstream), the bootstrap pulls the shared update helper (misc/update.sh). The
# helper asks the website whether this app can still be updated before touching
# anything, and explains a removal instead of erroring out.
#
# Called at install time and refreshed on every update (see
# migrate_update_entrypoint), so containers move onto the new mechanism the next
# time they update — no per-container migration step needed.
#
# $1 = script slug (for the website status lookup, e.g. "plex")
# $2 = update script name (the ct/<name>.sh to pull, e.g. "plex" or an OS name)
# $3 = (optional) script base URL; defaults to COMMUNITY_SCRIPTS_URL. Passing it
# explicitly lets migration preserve the source a container was built from.
# ------------------------------------------------------------------------------
write_update_entrypoint() {
local slug="${1:-}" name="${2:-}" base_override="${3:-}"
# Without a script name there is nothing to pull; leave any existing entry as-is.
[[ -z "$name" ]] && return 0
local base core_url website
base="$(_cs_live_base "${base_override:-${COMMUNITY_SCRIPTS_URL:-https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main}}")"
core_url="${COMMUNITY_SCRIPTS_CORE_URL:-https://raw.githubusercontent.com/community-scripts/core/main}"
website="${COMMUNITY_SCRIPTS_WEBSITE_URL:-https://community-scripts.org}"
# Temp file in the same directory, then an atomic mv. /usr/bin/update is
# usually the script currently running, and it grows from a one-liner to this.
# Overwriting in place makes the running shell resume at its old byte offset,
# now inside longer content, and execute garbage. mv gives the new content a
# fresh inode and the running shell reads the old one to a clean EOF.
local tmp
tmp="$(mktemp /usr/bin/.update.XXXXXX 2>/dev/null)" || tmp="/usr/bin/.update.tmp.$$"
# First heredoc is unquoted: the resolved values are baked in as the exports the
# bootstrap then reads. Second heredoc is quoted so its ${...} stay literal.
cat >"$tmp" <<EOF
#!/usr/bin/env bash
# Community-Scripts update entrypoint (generated - do not edit by hand).
# Regenerated on install and on every successful update.
export SCRIPT_SLUG="${slug}"
export UPDATE_SCRIPT_NAME="${name}"
export COMMUNITY_SCRIPTS_URL="${base}"
export COMMUNITY_SCRIPTS_CORE_URL="${core_url}"
export COMMUNITY_SCRIPTS_WEBSITE_URL="${website}"
EOF
cat >>"$tmp" <<'EOF'
# Pull the shared helper; it decides whether this app can still be updated. If it
# cannot be fetched, fall back to the legacy direct pull so `update` still works.
_cs_helper="$(curl -fsSL --connect-timeout 10 "${COMMUNITY_SCRIPTS_CORE_URL}/misc/update.sh" 2>/dev/null)"
if [[ -n "$_cs_helper" ]]; then
bash -c "$_cs_helper"
else
echo "Update helper unavailable - falling back to direct update."
bash -c "$(curl -fsSL "${COMMUNITY_SCRIPTS_URL}/ct/${UPDATE_SCRIPT_NAME}.sh")"
fi
EOF
chmod +x "$tmp"
mv -f "$tmp" /usr/bin/update
}
# ------------------------------------------------------------------------------
# migrate_update_entrypoint()
#
# Moves containers still carrying the old direct-pull /usr/bin/update onto the new
# bootstrap. Safe to call on every update. It is conservative: if the entrypoint
# already uses the helper it does nothing, and it preserves the exact script base
# URL the container was built from by reading it out of the legacy entrypoint,
# rather than guessing from the current environment.
# ------------------------------------------------------------------------------
migrate_update_entrypoint() {
# Nothing to do only if it is on the helper, points somewhere that still
# serves scripts, and records a usable name.
if [[ -f /usr/bin/update ]] &&
grep -q "misc/update.sh" /usr/bin/update 2>/dev/null &&
! grep -q "git.community-scripts.org" /usr/bin/update 2>/dev/null &&
grep -qE '^export UPDATE_SCRIPT_NAME="[a-zA-Z0-9._-]+"$' /usr/bin/update 2>/dev/null; then
return 0
fi
local slug name base=""
slug="${SCRIPT_SLUG:-${NSAPP:-${app:-}}}"
slug="$(echo "$slug" | tr '[:upper:]' '[:lower:]' | tr ' ' '-')"
# Prefer the base + script name recorded in the legacy entrypoint, so the
# migrated container keeps pulling from the same repo it always did.
if [[ -f /usr/bin/update ]]; then
local legacy
# No match is normal; grep exiting 1 must not trip the ERR trap.
legacy="$(grep -oE 'https?://[^"]+/ct/[^"]+\.sh' /usr/bin/update 2>/dev/null | head -1 || true)"
if [[ -n "$legacy" ]]; then
base="${legacy%/ct/*}"
name="$(basename "${legacy%.sh}")"
else
# Helper format has no literal url, only the export.
name="$(grep -m1 '^export UPDATE_SCRIPT_NAME=' /usr/bin/update 2>/dev/null | cut -d'"' -f2 || true)"
fi
fi
base="$(_cs_live_base "$base")"
# Anything that is not a slug is a damaged entrypoint, not a name.
[[ "${name:-}" =~ ^[a-zA-Z0-9._-]+$ ]] || name=""
# Fall back to the update environment when the legacy line could not be parsed.
[[ -z "${name:-}" ]] && name="${NSAPP:-${app:-${var_os:-}}}"
[[ -z "$name" ]] && return 0
write_update_entrypoint "$slug" "$name" "$base" 2>/dev/null || true
}
# ------------------------------------------------------------------------------
# default_vars()
#
# - Sets default retry and wait variables used for system actions
# - RETRY_NUM: Maximum number of retry attempts (default: 10)
# - RETRY_EVERY: Seconds to wait between retries (default: 3)
# - i: Counter variable initialized to RETRY_NUM
# ------------------------------------------------------------------------------
default_vars() {
RETRY_NUM=10
RETRY_EVERY=3
i=$RETRY_NUM
}
# ------------------------------------------------------------------------------
# set_std_mode()
#
# - Sets default verbose mode for script and OS execution
# - If VERBOSE=yes: STD="" (show all output)
# - If VERBOSE=no: STD="silent" (suppress output via silent() wrapper)
# - If DEV_MODE_TRACE=true: Enables bash tracing (set -x)
# ------------------------------------------------------------------------------
set_std_mode() {
if [ "${VERBOSE:-no}" = "yes" ]; then
STD=""
else
STD="silent"
fi
# Enable bash tracing if trace mode active
if [[ "${DEV_MODE_TRACE:-false}" == "true" ]]; then
set -x
# BASH_SOURCE is empty at the top level of `bash -c` and inside a
# `source /dev/stdin`, which is exactly how the install script runs in the
# container. Unguarded, set -u aborts the run the moment PS4 is expanded.
export PS4='+(${BASH_SOURCE:-?}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'
fi
}
# `clear` is part of ncurses, which the minimal Fedora and Arch container images
# do not ship. A bare call there returns 127, and under errexit that aborted the
# run before it had done anything -- `update` on a fresh Fedora container died on
# this line. The escape sequence does the same job wherever clear is missing.
_cs_clear() {
if command -v clear >/dev/null 2>&1; then
clear
else
printf '\033[H\033[2J\033[3J'
fi
}
# ==============================================================================
# SECTION 2: VALIDATION CHECKS
# ==============================================================================
# ------------------------------------------------------------------------------
# shell_check()
#
# - Verifies that the script is running under Bash shell
# - Exits with error message if different shell is detected
# - Required because scripts use Bash-specific features
# ------------------------------------------------------------------------------
shell_check() {
if [[ "$(ps -p $$ -o comm=)" != "bash" ]]; then
_cs_clear
msg_error "Your default shell is currently not set to Bash. To use these scripts, please switch to the Bash shell."
echo -e "\nExiting..."
sleep 2
exit 103 # shell is not Bash
fi
}
# ------------------------------------------------------------------------------
# root_check()
#
# - Verifies script is running with root privileges
# - Detects if executed via sudo (which can cause issues)
# - Exits with error if not running as root directly
# ------------------------------------------------------------------------------
root_check() {
if [[ "$(id -u)" -ne 0 || $(ps -o comm= -p $PPID) == "sudo" ]]; then
_cs_clear
msg_error "Please run this script as root."
echo -e "\nExiting..."
sleep 2
exit 104 # not running as root
fi
}
# ------------------------------------------------------------------------------
# on_pve_host()
#
# - Returns 0 when executed on a Proxmox VE node, 1 otherwise
# - Cheap probe used by the guards below; never exits on its own
# ------------------------------------------------------------------------------
on_pve_host() {
command -v pveversion &>/dev/null
}
# ------------------------------------------------------------------------------
# require_pve_host()
#
# - Guard for tools that drive the node itself (pct/pveam/pvesm/pvesh/qm)
# - Aborts when not on a PVE node, then validates the PVE version
# ------------------------------------------------------------------------------
require_pve_host() {
if ! on_pve_host; then
msg_error "${APP:-This script} must be run on the Proxmox VE host."
msg_error "Proxmox tooling (pct/pveam/pvesm/qm) is not available here."
exit 232
fi
pve_check
}
# ------------------------------------------------------------------------------
# confirm_not_pve_host()
#
# - Guard for tools that belong inside an LXC/VM but would technically run
# on the node as well
# - Warns and asks for confirmation instead of hard-failing
# ------------------------------------------------------------------------------
confirm_not_pve_host() {
on_pve_host || return 0
msg_error "Running on the Proxmox VE host is NOT recommended!"
msg_error "${APP:-This script} is meant to be executed inside an LXC container."
echo ""
echo -n "${TAB:- }Continue anyway? (y/N): "
local confirm
declare -f reclaim_tty >/dev/null 2>&1 && reclaim_tty
read -r confirm </dev/tty || true
if [[ ! "${confirm,,}" =~ ^(y|yes)$ ]]; then
msg_warn "Aborted. Please run this inside an LXC container."
exit 0
fi
msg_warn "Proceeding on the Proxmox VE host at your own risk!"
}
# ------------------------------------------------------------------------------
# require_debian_like()
#
# - Guard for addons that have no Alpine code path
# - Aborts early instead of failing halfway through with apt/systemd errors
# ------------------------------------------------------------------------------
require_debian_like() {
if is_alpine; then
msg_error "${APP:-This script} does not support Alpine Linux."
msg_error "Please use a Debian or Ubuntu based LXC container."
exit 238
fi
if ! command -v apt-get &>/dev/null; then
msg_error "${APP:-This script} requires a Debian or Ubuntu based system."
exit 238
fi
}
# ------------------------------------------------------------------------------
# pve_check()
#
# - Validates Proxmox VE version compatibility
# - Supported: PVE 8.0-8.9 and PVE 9.0-9.2
# - Exits with error message if unsupported version detected
# ------------------------------------------------------------------------------
# pveversion and `pveam available` are Perl programs answering the same thing
# all run: the host version and the template catalog. They were invoked 4 and 9
# times, each a fresh process.
#
# The cache is a file, not a variable. Every call site reads these through a
# pipe or $( ), which is a subshell — a variable assigned in there is gone the
# moment it returns, so a shell-variable memo would never hit. $$ stays the
# parent's pid inside a subshell, which makes the path the same for all of them.
_cs_runtime_cache_dir() {
local base probe
for base in /dev/shm "${TMPDIR:-/tmp}" /tmp; do
[[ -d "$base" ]] || continue
probe="${base}/.cs-probe.$$"
# -w can pass where the write still fails, so probe for real.
{ : >"$probe"; } 2>/dev/null || continue
rm -f "$probe" 2>/dev/null
printf '%s' "$base"
return 0
done
return 1
}
_pve_version() {
[[ -n "${PVEVERSION:-}" ]] && { printf '%s' "$PVEVERSION"; return 0; }
local dir cache
dir="$(_cs_runtime_cache_dir)" || {
pveversion 2>/dev/null | awk -F'/' '{print $2}' | awk -F'-' '{print $1}'
return
}
cache="${dir}/cs-pveversion.$$"
[[ -s "$cache" ]] ||
pveversion 2>/dev/null | awk -F'/' '{print $2}' | awk -F'-' '{print $1}' >"$cache"
cat "$cache" 2>/dev/null
}
# PVEVERSION carries the product name on Incus ("Incus 7.3") because telemetry
# reports it verbatim as pve_version. A fixed "PVE Version" prefix therefore
# printed "PVE Version Incus 7.3" on Incus hosts.
_cs_host_version_line() {
local v="${PVEVERSION:-unknown}"
if [[ "$v" == Incus* ]]; then
v="${v#Incus}"
v="${v# }"
printf 'Incus Version %s' "${v:-unknown}"
else
printf 'PVE Version %s' "$v"
fi
}
# "<what> <kind>: owner/repo@ref" for a raw base url. The kind is the part worth
# reading: branch for the official repo on another ref, fork for somebody else's
# copy, source when the host is not one we can take apart.
_cs_ref_line() {
local what="$1" url="${2%/}" official="$3" rest owner repo ref kind
rest="${url#*://}"
case "$rest" in
raw.githubusercontent.com/*) rest="${rest#raw.githubusercontent.com/}" ;;
git.community-scripts.org/*) rest="${rest#git.community-scripts.org/}" ;;
*)
printf '%s source: %s' "$what" "$url"
return 0
;;
esac
# read gives the remainder to the last name, so a ref with slashes survives:
# copilot/revert-aurral-to-node22 is one ref, not two path segments.
IFS=/ read -r owner repo ref <<<"$rest"
if [[ -z "$owner" || -z "$repo" || -z "$ref" ]]; then
printf '%s source: %s' "$what" "$url"
return 0
fi
kind=fork
case " $official " in
*" $owner/$repo "*) kind=branch ;;
esac
printf '%s %s: %s/%s@%s' "$what" "$kind" "$owner" "$repo" "$ref"
}
# Which engine this run is using, when it is not the default one. Prints nothing
# otherwise, so the header only grows a line when there is something to say.
_cs_engine_ref_line() {
local url="${COMMUNITY_SCRIPTS_CORE_URL:-}"
# The literal fallback matters: build.func exports COMMUNITY_SCRIPTS_CORE_URL
# but not _CS_CORE_DEFAULT_URL, so a child process sees the url with nothing
# to compare it against and every ordinary run looks like an override.
local default="${_CS_CORE_DEFAULT_URL:-https://raw.githubusercontent.com/community-scripts/core/main}"
url="${url%/}"
[[ -n "$url" && "$url" != "${default%/}" ]] || return 0
_cs_ref_line Engine "$url" "community-scripts/core"
}
# The same for the scripts, which is the other half of "what am I running" and
# the one people override more often.
_cs_scripts_ref_line() {
local url="${COMMUNITY_SCRIPTS_URL:-}" d
url="${url%/}"
[[ -n "$url" ]] || return 0
# Both official mains count as default, not just one literal: _CS_DEFAULT_URL
# is not exported either, and CI rewrites VED to VE on promotion.
for d in "${_CS_DEFAULT_URL:-}" \
https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main \
https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main; do
[[ -n "$d" && "$url" == "${d%/}" ]] && return 0
done
_cs_ref_line Scripts "$url" \
"community-scripts/ProxmoxVE community-scripts/ProxmoxVED"
}
_pveam_available() {
local dir cache
dir="$(_cs_runtime_cache_dir)" || {
pveam available -section system 2>/dev/null
return
}
cache="${dir}/cs-pveam.$$"
[[ -s "$cache" ]] || pveam available -section system 2>/dev/null >"$cache"
cat "$cache" 2>/dev/null
}
# `pveam update` exists so the next read sees something new, so it drops the
# cache. Every update site goes through here for that reason.
_pveam_update() {
local dir
dir="$(_cs_runtime_cache_dir)" && rm -f "${dir}/cs-pveam.$$"
if command -v timeout &>/dev/null; then
timeout 30 pveam update >/dev/null 2>&1 || return 1
else
pveam update >/dev/null 2>&1 || return 1
fi
return 0
}
pve_check() {
local PVE_VER
if ! on_pve_host; then
msg_error "${APP:-This script} must be run on the Proxmox VE host."
exit 232
fi
PVE_VER="$(_pve_version)"
# Check for Proxmox VE 8.x: allow 8.0–8.9
if [[ "$PVE_VER" =~ ^8\.([0-9]+) ]]; then
local MINOR="${BASH_REMATCH[1]}"
if ((MINOR < 0 || MINOR > 9)); then
msg_error "This version of Proxmox VE is not supported."
msg_error "Supported: Proxmox VE version 8.0 – 8.9"
exit 1
fi
return 0
fi
# Check for Proxmox VE 9.x: allow 9.0–9.2
if [[ "$PVE_VER" =~ ^9\.([0-9]+) ]]; then
local MINOR="${BASH_REMATCH[1]}"
if ((MINOR < 0 || MINOR > 2)); then
msg_error "This version of Proxmox VE is not yet supported."
msg_error "Supported: Proxmox VE version 9.0 – 9.2"
exit 1
fi
return 0
fi
# All other unsupported versions
msg_error "This version of Proxmox VE is not supported."
msg_error "Supported versions: Proxmox VE 8.0 – 8.9 or 9.0 – 9.2"
exit 1
}
# ------------------------------------------------------------------------------
# arch_check()
#
# - Validates system architecture is amd64/x86_64
# - Exits with error message for unsupported architectures (e.g., ARM/PiMox)
#
# var_arm64 has three states:
# yes - known to work, proceed silently
# no - known to be broken (no arm64 artifact, x86-only dependency), abort
# unknown - never verified on arm64 (default). Explain the situation and let
# the user decide, since "no artifact exists" and "nobody tried"
# are very different things and only the latter is worth attempting.
# ------------------------------------------------------------------------------
arch_check() {
local arch
arch="$(dpkg --print-architecture)"
if [[ "$arch" != "amd64" && "$arch" != "arm64" ]]; then
msg_error "This script requires amd64 or arm64 (detected: $arch)."
sleep 2
exit 106
fi
[[ "$arch" != "arm64" ]] && return 0
case "${var_arm64:-unknown}" in
yes)
return 0
;;
no)
msg_error "This script does not support arm64."
sleep 2
exit 106
;;
*)
msg_warn "This script has not been verified on arm64."
echo -e "${TAB}It may work, or it may fail on an architecture-specific dependency."
echo -e "${TAB}If you try it, please report the outcome - success or failure:"
echo -e "${TAB}${BGN}https://github.com/community-scripts/ProxmoxVED/issues${CL}"
echo ""
if [[ ! -t 0 ]]; then
msg_error "Not running interactively - refusing to guess on arm64. Set var_arm64=yes to override."
sleep 2
exit 106
fi
read -r -p "${TAB}Continue anyway? (y/N): " arm64_prompt </dev/tty
if [[ "${arm64_prompt,,}" =~ ^(y|yes)$ ]]; then
msg_ok "Continuing on arm64 - thanks for testing"
return 0
fi
msg_error "Aborted on arm64."
sleep 2
exit 106
;;
esac
}
# ------------------------------------------------------------------------------
# ssh_check()
#
# - Detects if script is running over SSH connection
# - Warns user for external SSH connections (recommends Proxmox shell)
# - Skips warning for local/same-subnet connections
# - Does not abort execution, only warns
# ------------------------------------------------------------------------------
ssh_check() {
if [ -n "$SSH_CLIENT" ]; then
local client_ip=$(awk '{print $1}' <<<"$SSH_CLIENT")
local host_ip=$(hostname -I | awk '{print $1}')
# Check if connection is local (Proxmox WebUI or same machine)
# - localhost (127.0.0.1, ::1)
# - same IP as host
# - local network range (10.x, 172.16-31.x, 192.168.x)
if [[ "$client_ip" == "127.0.0.1" || "$client_ip" == "::1" || "$client_ip" == "$host_ip" ]]; then
return
fi
# Check if client is in same local network (optional, safer approach)
local host_subnet=$(echo "$host_ip" | cut -d. -f1-3)
local client_subnet=$(echo "$client_ip" | cut -d. -f1-3)
if [[ "$host_subnet" == "$client_subnet" ]]; then
return
fi
# Only warn for truly external connections
msg_warn "Running via external SSH (client: $client_ip)."
msg_warn "For better stability, consider using the Proxmox Shell (Console) instead."
fi
}
# ==============================================================================
# SECTION 3: EXECUTION HELPERS
# ==============================================================================
# ------------------------------------------------------------------------------
# get_active_logfile()
#
# - Returns the appropriate log file based on execution context
# - _HOST_LOGFILE: Override for host context (keeps host logging on BUILD_LOG
# even after INSTALL_LOG is exported for the container)
# - INSTALL_LOG: Container operations (application installation)
# - BUILD_LOG: Host operations (container creation)
# - Fallback to BUILD_LOG if neither is set
# ------------------------------------------------------------------------------
get_active_logfile() {
# Host override: _HOST_LOGFILE is set (not exported) in build.func to keep
# host-side logging in BUILD_LOG after INSTALL_LOG is exported for the container.
# Without this, all host msg_info/msg_ok/msg_error would write to
# /root/.install-SESSION.log (a container path) instead of BUILD_LOG.
if [[ -n "${_HOST_LOGFILE:-}" ]]; then
echo "$_HOST_LOGFILE"
elif [[ -n "${INSTALL_LOG:-}" ]]; then
echo "$INSTALL_LOG"
elif [[ -n "${BUILD_LOG:-}" ]]; then
echo "$BUILD_LOG"
else
# Fallback for legacy scripts
echo "/tmp/build-$(date +%Y%m%d_%H%M%S).log"
fi
}
# Legacy compatibility: SILENT_LOGFILE points to active log
SILENT_LOGFILE="$(get_active_logfile)"
# ------------------------------------------------------------------------------
# strip_ansi()
#
# - Removes ANSI escape sequences from input text
# - Used to clean colored output for log files
# - Handles both piped input and arguments
# ------------------------------------------------------------------------------
strip_ansi() {
if [[ $# -gt 0 ]]; then
echo -e "$*" | sed 's/\x1b\[[0-9;]*m//g; s/\x1b\[[0-9;]*[a-zA-Z]//g'
else
sed 's/\x1b\[[0-9;]*m//g; s/\x1b\[[0-9;]*[a-zA-Z]//g'
fi
}
# ------------------------------------------------------------------------------
# log_msg()
#
# - Writes message to active log file without ANSI codes
# - Adds timestamp prefix for log correlation
# - Creates log file if it doesn't exist
# - Arguments: message text (can include ANSI codes, will be stripped)
# ------------------------------------------------------------------------------
log_msg() {
local msg="$*"
local logfile
logfile="$(get_active_logfile)"
[[ -z "$msg" ]] && return
[[ -z "$logfile" ]] && return
# Ensure log directory exists
mkdir -p "$(dirname "$logfile")" 2>/dev/null || true
# Strip ANSI codes and write with timestamp
local clean_msg
clean_msg=$(strip_ansi "$msg")
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $clean_msg" >>"$logfile"
}
# ------------------------------------------------------------------------------
# log_section()
#
# - Writes a section header to the log file
# - Used for separating different phases of installation
# - Arguments: section name
# ------------------------------------------------------------------------------
log_section() {
local section="$1"
local logfile
logfile="$(get_active_logfile)"
[[ -z "$logfile" ]] && return
mkdir -p "$(dirname "$logfile")" 2>/dev/null || true
{
echo ""
echo "================================================================================"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $section"
echo "================================================================================"
} >>"$logfile"
}
# ------------------------------------------------------------------------------
# silent()
#
# - Executes command with output redirected to active log file
# - On error: displays the FAILING COMMAND'S OWN output (not just the last 20
# log lines) and exits with original exit code
# - Records the log byte offset before running so the exact output segment of
# the failing command can be extracted and written to "<logfile>.errinfo"
# for telemetry (the host builds the error trace from this file)
# - Temporarily disables error trap to capture exit code correctly
# ------------------------------------------------------------------------------
silent() {
local cmd="$*"
local caller_line="${BASH_LINENO[0]:-unknown}"
local logfile="$(get_active_logfile)"
local errinfo="${logfile}.errinfo"
# Save current error handling state before disabling.
# This prevents re-enabling error handling when the caller intentionally
# disabled it.
local _restore_errexit=false
[[ "$-" == *e* ]] && _restore_errexit=true
set +Eeuo pipefail
trap - ERR
# Byte offset BEFORE the command runs - everything the log grows by is
# exactly this command's output.
local start_bytes=0
[[ -f "$logfile" ]] && start_bytes=$(stat -c%s "$logfile" 2>/dev/null || echo 0)
[[ ! "$start_bytes" =~ ^[0-9]+$ ]] && start_bytes=0
"$@" >>"$logfile" 2>&1
local rc=$?
# Restore error handling ONLY if it was active before this call.
if $_restore_errexit; then
set -Eeuo pipefail
trap 'error_handler' ERR
fi
if [[ $rc -ne 0 ]]; then
export _SILENT_FAILED_RC="$rc"
export _SILENT_FAILED_CMD="$cmd"
export _SILENT_FAILED_LINE="$caller_line"
export _SILENT_FAILED_LOG="$logfile"
# ── Structured error capture (.errinfo) ──
# Extract exactly THIS command's output (from the recorded byte offset),
# strip ANSI/progress noise, keep the last 60 lines. This file is the
# primary source for the telemetry error trace - self-contained, no
# api.func dependency (containers don't source api.func).
local flat_cmd
flat_cmd=$(printf '%s' "$cmd" | tr '\n' ' ' | head -c 300)
{
echo "EXIT_CODE=${rc}"
echo "LINE=${caller_line}"
echo "COMMAND=${flat_cmd}"
echo "--- OUTPUT ---"
if [[ -s "$logfile" ]]; then
local segment
segment=$(tail -c +"$((start_bytes + 1))" "$logfile" 2>/dev/null |
sed 's/\r$//' |
sed 's/\x1b\[[0-9;]*[a-zA-Z]//g' |
grep -avE '^(Get:|Hit:|Ign:|Fetched |Reading package lists|Reading state information|Building dependency tree|Selecting previously|Preparing to unpack|Unpacking |Processing triggers for|\(Reading database|[0-9]+%[[:space:]]*\[)' |
grep -avE '^[[:space:]]*$' |
tail -n 60)
# If the noise filter swallowed everything, fall back to the raw tail
if [[ -z "$segment" ]]; then
segment=$(tail -c +"$((start_bytes + 1))" "$logfile" 2>/dev/null |
sed 's/\r$//' | sed 's/\x1b\[[0-9;]*[a-zA-Z]//g' | tail -n 60)
fi
printf '%s' "$segment" | head -c 10240
fi
} >"$errinfo" 2>/dev/null || true
return "$rc"
fi
unset _SILENT_FAILED_RC _SILENT_FAILED_CMD _SILENT_FAILED_LINE _SILENT_FAILED_LOG 2>/dev/null || true
rm -f "$errinfo" 2>/dev/null || true
}
# ------------------------------------------------------------------------------
# spinner()
#
# - Displays animated spinner with rotating characters (⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏)
# - Shows SPINNER_MSG alongside animation
# - Runs in infinite loop until killed by stop_spinner()
# - Uses color_spinner() colors for output
# ------------------------------------------------------------------------------
_msg_fit() {
local msg="$1" reserved="${2:-4}" size cols max
size="$(stty size 2>/dev/null </dev/tty)" || size=""
cols="${size##* }"
[[ "$cols" =~ ^[1-9][0-9]*$ ]] || cols="${COLUMNS:-}"
if [[ ! "$cols" =~ ^[1-9][0-9]*$ ]]; then
printf '%s' "$msg"
return 0
fi
max=$((cols - reserved))
((max < 10)) && max=10
if ((${#msg} > max)); then
printf '%s…' "${msg:0:max-1}"
else
printf '%s' "$msg"
fi
}
spinner() {
# Reset bash's command hash table — package upgrades (dnf/pacman) may have
# moved /usr/bin <-> /usr/sbin during /usr-merge, leaving the parent shell
# with stale cached paths that get inherited by this background subshell.
hash -r 2>/dev/null || true
local chars=(⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏)
local msg
msg="$(_msg_fit "${SPINNER_MSG:-Processing...}" 4)"
local i=0
while true; do
local index=$((i++ % ${#chars[@]}))
printf "\r\033[2K%s %b" "${CS_YWB}${chars[$index]}${CS_CL}" "${CS_YWB}${msg}${CS_CL}"
sleep 0.1 2>/dev/null || command sleep 0.1 2>/dev/null || break
done
}
# ------------------------------------------------------------------------------
# clear_line()
#
# - Clears current terminal line using tput or ANSI escape codes
# - Moves cursor to beginning of line (carriage return)
# - Erases from cursor to end of line