aboutsummarylogtreecommitdiffstats
path: root/astrbotctl.functions
blob: 24dd9f33eb5c5690529f04683d7410bf4a187fbe (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
#!/bin/bash
# astrbotctl - shared functions library
# shellcheck shell=bash
# Source this file: . "$(dirname "$0")/astrbotctl.functions"

# ─── Constants (can be overridden before sourcing) ────────────────────────────
SYSTEM_ROOT="${SYSTEM_ROOT:-/var/lib/astrbot}"
CONFIG_DIR="${CONFIG_DIR:-/etc/astrbot}"
APP_DIR="${APP_DIR:-/opt/astrbot}"
CACHE_DIR="${CACHE_DIR:-/var/cache/astrbot}"
CERTBOT_INSTANCE_CERTS_DIR="${CERTBOT_INSTANCE_CERTS_DIR:-/etc/astrbot/certs}"
UPSTREAM_URL="${UPSTREAM_URL:-https://github.com/AstrBotDevs/AstrBot.git}"
UPSTREAM_BRANCH="${UPSTREAM_BRANCH:-master}"

# Update / rollback config (can be overridden in /etc/astrbot/update.conf)
UPDATE_STABILITY_SECS="${UPDATE_STABILITY_SECS:-60}"
UPDATE_AUTO_ROLLBACK="${UPDATE_AUTO_ROLLBACK:-1}"
# shellcheck disable=SC2034 # Consumed by astrbotctl after this library is sourced.
UPDATE_SNAPSHOT_DIR="${CACHE_DIR}/update-snapshots"
ROLLBACK_HEALTH_SECS="${ROLLBACK_HEALTH_SECS:-5}"

# ─── Path helpers ─────────────────────────────────────────────────────────────

instance_root() {
    echo "$SYSTEM_ROOT/${instance?instance not set}"
}

conf_file() {
    echo "$CONFIG_DIR/${instance?instance not set}.conf"
}

venv_dir() {
    echo "${ASTRBOT_ROOT:-$SYSTEM_ROOT/${instance?instance not set}}/.venv"
}

venv_sync_marker_file() {
    echo "$(venv_dir)/.astrbot-app-version"
}

venv_rollback_marker_file() {
    echo "$(venv_dir)/.astrbot-rollback"
}

venv_maintenance_lock_file() {
    echo "${ASTRBOT_ROOT:-$SYSTEM_ROOT/${instance?instance not set}}/.venv-maintenance.lock"
}

current_app_version() {
    [ -f "$APP_DIR/.version" ] || return 1
    cat "$APP_DIR/.version"
}

certbot_instance_cert_dir() {
    echo "$CERTBOT_INSTANCE_CERTS_DIR/${instance?instance not set}"
}

certbot_hook_path() {
    echo "/etc/letsencrypt/renewal-hooks/deploy/astrbot-${instance?instance not set}.sh"
}

# ─── Guards ──────────────────────────────────────────────────────────────────

require_root() {
    [ "$(id -u)" -eq 0 ] && return 0
    echo "❌ Error: This command requires root privileges (sudo)." >&2
    exit 1
}

require_instance() {
    if [ -z "${instance:-}" ]; then
        echo "Usage: astrbotctl <command> <instance_name>" >&2
        exit 1
    fi
    validate_instance_name "$instance" || exit 1
}

# Instance names are also used in fixed filesystem and systemd unit paths.
# Reject separators and dot-only forms before any lifecycle operation derives them.
validate_instance_name() {
    local candidate="${1:-}"

    if [[ ! "$candidate" =~ ^[a-zA-Z0-9][a-zA-Z0-9_-]*$ ]]; then
        echo "❌ Error: Invalid instance name: ${candidate:-<empty>}" >&2
        return 1
    fi
}

# ─── Config helpers ──────────────────────────────────────────────────────────

# Write through a same-directory temporary file, never through the destination.
# The writer receives the remaining arguments and emits the complete contents.
# mode=preserve retains existing mode/ownership, defaulting to 0644 for new files.
_atomic_replace_file() (
    local destination="$1" mode="$2" owner="$3" temporary=""
    shift 3
    trap '[ -z "$temporary" ] || rm -f -- "$temporary"' EXIT
    if [ -L "$destination" ] || { [ -e "$destination" ] && [ ! -f "$destination" ]; }; then
        echo "Error: Refusing non-regular output path: $destination" >&2
        exit 1
    fi
    umask 077
    temporary="$(mktemp -- "$(dirname "$destination")/.$(basename "$destination").XXXXXX")" || exit $?
    "$@" >"$temporary" || exit $?
    if [ "$mode" = preserve ] && [ -f "$destination" ]; then
        chown --reference="$destination" -- "$temporary" || exit $?
        chmod --reference="$destination" -- "$temporary" || exit $?
    else
        chmod "${mode/preserve/0644}" -- "$temporary" || exit $?
    fi
    [ -z "$owner" ] || chown "$owner" -- "$temporary" || exit $?
    mv --no-copy -fT -- "$temporary" "$destination" || exit $?
    temporary=""
)

# Double-quoted values shared by Bash source and systemd EnvironmentFile.
_escape_conf_value() {
    local value="$1"
    value="${value//\\/\\\\}"
    value="${value//\"/\\\"}"
    value="${value//\$/\\\$}"
    value="${value//\`/\\\`}"
    printf '%s' "$value"
}

_write_upserted_conf() {
    local path="$1" key="$2" escaped="$3" line found=0
    if [ -f "$path" ]; then
        while IFS= read -r line || [ -n "$line" ]; do
            if [[ "$line" == "$key="* ]]; then
                if [ "$found" -eq 0 ]; then
                    printf '%s="%s"\n' "$key" "$escaped" || return $?
                    found=1
                fi
            else
                printf '%s\n' "$line" || return $?
            fi
        done <"$path" || return $?
    fi
    [ "$found" -eq 1 ] || printf '%s="%s"\n' "$key" "$escaped" || return $?
    return 0
}

upsert_conf_var() {
    local conf_path="$1" key="$2" value="$3" escaped
    [[ "$key" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]] &&
        [[ "$value" != *$'\n'* && "$value" != *$'\r'* ]] || {
        echo 'Error: Expected a valid variable name and a single-line value.' >&2
        return 2
    }
    escaped="$(_escape_conf_value "$value")" || return $?
    _atomic_replace_file "$conf_path" preserve "" _write_upserted_conf "$conf_path" "$key" "$escaped"
}

# Snapshot supported defaults on the first load, not on library import. Restore
# both set and unset values before each instance, including template/API defaults.
_restore_instance_config_baseline() {
    local key
    local keys="INSTANCE_NAME ASTRBOT_ROOT ASTRBOT_LOG_LEVEL ASTRBOT_RELOAD
        ASTRBOT_DISABLE_METRICS PYTHON DEMO_MODE TESTING ASTRBOT_DESKTOP_CLIENT
        ASTRBOT_SYSTEMD ASTRBOT_DASHBOARD_ENABLE ASTRBOT_CORS_ALLOW_ORIGIN
        ASTRBOT_HOST ASTRBOT_PORT ASTRBOT_SSL_ENABLE ASTRBOT_SSL_CERT
        ASTRBOT_SSL_KEY ASTRBOT_SSL_CA_CERTS http_proxy https_proxy no_proxy
        DASHSCOPE_API_KEY COZE_API_KEY COZE_BOT_ID TEST_MODE LOG_DIR
        ASTRBOT_DASHBOARD_SSL_ENABLE ASTRBOT_CERTBOT_MANAGED
        ASTRBOT_CERTBOT_CERT_NAME ASTRBOT_CERTBOT_DOMAINS ASTRBOT_CERTBOT_EMAIL"
    if ! declare -p _ASTRBOT_CONFIG_BASELINE >/dev/null 2>&1; then
        declare -gA _ASTRBOT_CONFIG_BASELINE=()
        for key in $keys; do
            if [[ -v "$key" ]]; then
                _ASTRBOT_CONFIG_BASELINE["$key"]="${!key}"
            fi
        done
    fi
    for key in $keys; do
        unset "$key" || return $?
        if [[ ${_ASTRBOT_CONFIG_BASELINE[$key]+present} ]]; then
            printf -v "$key" '%s' "${_ASTRBOT_CONFIG_BASELINE[$key]}" || return $?
        fi
    done
    return 0
}

# Preserve the caller's allexport setting, including when source fails.
load_instance_config() {
    local config_path status=0 had_allexport=0
    [[ $- != *a* ]] || had_allexport=1
    config_path="$(conf_file)" || return $?
    _restore_instance_config_baseline || return $?
    ASTRBOT_ROOT="$(instance_root)" || return $?
    export ASTRBOT_ROOT
    if [ -f "$config_path" ]; then
        set -a
        # shellcheck disable=SC1090 # Trusted per-instance shell configuration.
        if . "$config_path"; then :; else status=$?; fi
    fi
    if [ "$had_allexport" -eq 1 ]; then set -a; else set +a; fi
    # Historical alias, not a second runtime directory.
    export ASTRBOT_HOME="$ASTRBOT_ROOT"
    return "$status"
}

# ─── Port allocation ─────────────────────────────────────────────────────────

# Find a free port starting from $1 (default 3000).
# Checks both assigned ports in config files and currently listening ports.
_normalize_port() {
    [[ "$1" =~ ^[0-9]{1,5}$ ]] || return 1
    local number=$((10#$1))
    ((number > 0 && number <= 65535)) || return 1
    printf '%s\n' "$number"
}

find_free_port() {
    local port candidate path line value active endpoint
    local -A used=()
    local port_pattern="^[[:space:]]*ASTRBOT_PORT[[:space:]]*=[[:space:]]*(\"[0-9]+\"|'[0-9]+'|[0-9]+)[[:space:]]*(#.*)?$"
    port="$(_normalize_port "${1:-3000}")" || return 2
    for path in "$CONFIG_DIR"/*.conf; do
        [ -f "$path" ] || continue
        while IFS= read -r line || [ -n "$line" ]; do
            [[ "$line" =~ $port_pattern ]] || continue
            value="${BASH_REMATCH[1]}"
            value="${value//\"/}"
            value="${value//\'/}"
            if candidate="$(_normalize_port "$value")"; then used["$candidate"]=1; fi
        done <"$path"
    done
    # Read ss completely. No grep -q/SIGPIPE interaction with caller pipefail.
    if active="$(ss -lntH 2>/dev/null)"; then
        while read -r _ _ _ endpoint _; do
            if candidate="$(_normalize_port "${endpoint##*:}")"; then used["$candidate"]=1; fi
        done <<<"$active"
    fi
    while ((port <= 65535)); do
        if [[ ! ${used[$port]+present} ]]; then
            export ASTRBOT_PORT="$port"
            return 0
        fi
        port=$((port + 1))
    done
    echo 'Error: No free dashboard port is available.' >&2
    return 1
}

# ─── Runtime environment ─────────────────────────────────────────────────────

# Migrate the old `$ASTRBOT_ROOT/home` runtime tree without overwriting any
# canonical path. New instances never create that directory. A non-empty
# conflict is intentionally preserved so an administrator can decide whether
# the two trees contain duplicate or distinct data.
migrate_legacy_home() {
    local root="$1"
    local legacy_home="$root/home"
    local source_path entry destination

    [ -e "$legacy_home" ] || [ -L "$legacy_home" ] || return 0
    if [ ! -d "$legacy_home" ] || [ -L "$legacy_home" ]; then
        echo "⚠️  Refusing to migrate non-directory legacy runtime path: $legacy_home" >&2
        return 0
    fi

    while IFS= read -r -d '' source_path; do
        entry="${source_path##*/}"
        destination="$root/$entry"

        if [ -L "$source_path" ]; then
            echo "⚠️  Preserving symlink in legacy runtime path: $source_path" >&2
            continue
        fi

        if [ -e "$destination" ] || [ -L "$destination" ]; then
            if [ -d "$source_path" ] &&
                [ -z "$(find -P "$source_path" -mindepth 1 -maxdepth 1 -print -quit)" ]; then
                rmdir -- "$source_path" || true
            else
                echo "⚠️  Preserving legacy path because the canonical path exists: $source_path" >&2
            fi
            continue
        fi

        mv -- "$source_path" "$destination" ||
            echo "⚠️  Could not migrate legacy runtime path: $source_path" >&2
    done < <(find -P "$legacy_home" -mindepth 1 -maxdepth 1 -print0)

    rmdir -- "$legacy_home" 2>/dev/null || true
}

# Set up XDG and uv environment variables for an instance.
# Call this before running any astrbot command in a subprocess.
setup_runtime_env() {
    export ASTRBOT_ROOT="${ASTRBOT_ROOT:-$(instance_root)}"
    migrate_legacy_home "$ASTRBOT_ROOT" || return $?
    export ASTRBOT_HOME="$ASTRBOT_ROOT"

    # AstrBot resolves its application data relative to the working directory
    # (`data/`). Use the same instance root for HOME and the XDG tree so the
    # package has one coherent runtime layout.
    runtime_root="$ASTRBOT_ROOT"
    runtime_cache="$runtime_root/.cache"
    runtime_config="$runtime_root/.config"
    runtime_data="$runtime_root/.local/share"
    runtime_state="$runtime_root/.local/state"

    export HOME="$runtime_root"
    export XDG_CACHE_HOME="$runtime_cache"
    export XDG_CONFIG_HOME="$runtime_config"
    export XDG_DATA_HOME="$runtime_data"
    export XDG_STATE_HOME="$runtime_state"
    export UV_PROJECT_ENVIRONMENT="$ASTRBOT_ROOT/.venv"
    export UV_PYTHON_INSTALL_DIR="$CACHE_DIR/python"
    export CARGO_HOME="/var/lib/astrbot/.cargo"
    export RUSTUP_HOME="/var/lib/astrbot/.rustup"
    export CARGO_TARGET_DIR="$CACHE_DIR/cargo_target"
    export ASTRBOT_SYSTEMD=1
    export ASTRBOT_DESKTOP_CLIENT=0

    generate_env_file || return $?
    return 0
}

_write_runtime_env() {
    local var
    local vars="HOME XDG_CACHE_HOME XDG_CONFIG_HOME XDG_DATA_HOME XDG_STATE_HOME
        UV_PROJECT_ENVIRONMENT UV_PYTHON_INSTALL_DIR CARGO_HOME RUSTUP_HOME
        CARGO_TARGET_DIR ASTRBOT_SYSTEMD ASTRBOT_DESKTOP_CLIENT ASTRBOT_ROOT
        ASTRBOT_HOME ASTRBOT_HOST ASTRBOT_PORT ASTRBOT_DASHBOARD_ENABLE
        ASTRBOT_LOG_LEVEL ASTRBOT_RELOAD ASTRBOT_DISABLE_METRICS
        ASTRBOT_SSL_ENABLE ASTRBOT_SSL_CERT ASTRBOT_SSL_KEY ASTRBOT_SSL_CA_CERTS
        http_proxy https_proxy no_proxy"
    for var in $vars; do
        printf '%s=%q\n' "$var" "${!var-}" || return $?
    done
    printf 'VIRTUAL_ENV=%q\nPATH=%q\n' "$UV_PROJECT_ENVIRONMENT" "$UV_PROJECT_ENVIRONMENT/bin:$PATH" || return $?
    return 0
}

# Instance directories are service-writable. Run both the reader/transformer
# and atomic publisher without root privileges, including temporary-file opens.
_replace_instance_file() {
    local destination="$1"
    shift
    if [ "$(id -u)" -eq 0 ] && id astrbot >/dev/null 2>&1; then
        runuser -u astrbot -- bash -c '
            . "$1" || exit $?
            shift
            destination="$1"
            shift
            mkdir -p -- "$(dirname "$destination")" || exit $?
            _atomic_replace_file "$destination" 0600 "" "$@"
        ' bash "${BASH_SOURCE[0]}" "$destination" "$@"
    else
        mkdir -p -- "$(dirname "$destination")" || return $?
        _atomic_replace_file "$destination" 0600 "" "$@"
    fi
}

# This file is sourced by Bash, not parsed as a dotenv/EnvironmentFile document.
generate_env_file() (
    set -o pipefail
    _write_runtime_env | _replace_instance_file "$ASTRBOT_ROOT/.env" cat
)

# Create all required runtime directories under ASTRBOT_ROOT.
ensure_runtime_dirs() {
    mkdir -p \
        "$HOME" \
        "$XDG_CONFIG_HOME" \
        "$XDG_DATA_HOME" \
        "$XDG_STATE_HOME" \
        "$ASTRBOT_ROOT/data" \
        "$ASTRBOT_ROOT/data/config" \
        "$ASTRBOT_ROOT/data/plugins" \
        "$ASTRBOT_ROOT/data/temp" \
        "$ASTRBOT_ROOT/data/skills" \
        "$ASTRBOT_ROOT/data/site-packages" \
        "$ASTRBOT_ROOT/data/knowledge_base" \
        "$ASTRBOT_ROOT/data/backups" \
        "$ASTRBOT_ROOT/data/t2i_templates" \
        "$ASTRBOT_ROOT/data/webchat"
}

# ─── Privilege dropping ───────────────────────────────────────────────────────

# Run a command as the astrbot user with .env sourced.
# Handles recursive privilege-dropping prevention via ASTRBOT_PRIVDROP_DONE.
_runuser_with_env() {
    local env_file="$1" runtime_root="$2"
    shift 2

    if [ "$(id -u)" -eq 0 ] && [ -z "${ASTRBOT_PRIVDROP_DONE:-}" ] && id astrbot >/dev/null 2>&1; then
        runuser -u astrbot -- env \
            ASTRBOT_PRIVDROP_DONE=1 \
            bash -c 'set -a && . "$1" && . /usr/bin/astrbotctl.functions && set +a && ensure_runtime_dirs && cd "$2" && exec "${@:3}"' \
            bash "$env_file" "$runtime_root" "$@"
    else
        (
            set -a
            # shellcheck disable=SC1090 # Generated Bash assignments, not a library.
            . "$env_file" || exit $?
            set +a
            ensure_runtime_dirs && cd "$runtime_root" || exit $?
            exec "$@"
        )
    fi
}

# Run an astrbot command (from the shared venv) with full runtime env.
run_astrbot_env_cmd() {
    local command_cwd
    setup_runtime_env || return $?
    command_cwd="$runtime_root"

    if [ "${1:-}" = "--command-cwd" ]; then
        command_cwd="${2?Missing directory after --command-cwd}"
        shift 2
    fi

    _runuser_with_env "$ASTRBOT_ROOT/.env" "$command_cwd" "$@"
}

# Ensure the instance venv is present and synced with the packaged app.
# shellcheck disable=SC2120 # Optional --force is intentionally supported.
ensure_instance_env_synced() {
    local force=0
    if [ "${1:-}" = "--force" ]; then
        force=1
        shift
    fi
    [ "$#" -eq 0 ] || {
        echo "❌ Error: Unknown ensure_instance_env_synced option." >&2
        return 2
    }
    setup_runtime_env || return $?

    # Self-heal app dir before syncing
    _ensure_app_dir || return 1

    local env_file="$ASTRBOT_ROOT/.env"
    local venv_python="$UV_PROJECT_ENVIRONMENT/bin/python"
    local venv_astrbot="$UV_PROJECT_ENVIRONMENT/bin/astrbot"
    local marker_file rollback_marker current_version last_synced_version needs_sync sync_reason command_status
    local venv_created=0
    marker_file="$(venv_sync_marker_file)"
    rollback_marker="$(venv_rollback_marker_file)"
    current_version="$(current_app_version 2>/dev/null || true)"
    last_synced_version="$(cat "$marker_file" 2>/dev/null || true)"
    needs_sync=0
    sync_reason=""

    if [ -d "$UV_PROJECT_ENVIRONMENT" ] && [ ! -L "$UV_PROJECT_ENVIRONMENT" ] &&
        [ -f "$UV_PROJECT_ENVIRONMENT/pyvenv.cfg" ] && [ ! -L "$UV_PROJECT_ENVIRONMENT/pyvenv.cfg" ] &&
        [ -x "$venv_python" ] && [ -x "$venv_astrbot" ]; then
        :
    else
        echo ">>> Initializing virtual environment for instance: $instance"
        if run_astrbot_env_cmd uv venv "$UV_PROJECT_ENVIRONMENT" --python 3.12 --clear; then
            venv_created=1
        else
            command_status=$?
            return "$command_status"
        fi
    fi

    if [ -e "$rollback_marker" ] || [ -L "$rollback_marker" ]; then
        if ! venv_rollback_marker_is_valid "$UV_PROJECT_ENVIRONMENT"; then
            echo "❌ Error: Invalid rollback marker or virtualenv for instance '$instance'." >&2
            return 1
        fi
        if [ "$force" -eq 0 ]; then
            echo "⚠️  Using validated rollback virtualenv for instance '$instance'; run astrbotctl sync to retry." >&2
            return 0
        fi
    fi

    if [ "$venv_created" -eq 1 ]; then
        needs_sync=1
        sync_reason="missing or invalid virtualenv"
    elif [ "$force" -eq 1 ]; then
        needs_sync=1
        sync_reason="explicit sync requested"
    elif [ -n "$current_version" ] && [ "$current_version" != "$last_synced_version" ]; then
        needs_sync=1
        sync_reason="app version changed (${last_synced_version:-none} -> $current_version)"
    fi

    if [ "$needs_sync" -eq 1 ]; then
        echo ">>> Syncing Python environment for instance: $instance${sync_reason:+ ($sync_reason)}"
        if run_astrbot_env_cmd env \
            VIRTUAL_ENV="$UV_PROJECT_ENVIRONMENT" \
            PATH="$UV_PROJECT_ENVIRONMENT/bin:$PATH" \
            UV_NO_CONFIG=1 \
            UV_PYTHON_INSTALL_DIR="$ASTRBOT_ROOT/.python" \
            CARGO_HOME="/var/lib/astrbot/.cargo" \
            RUSTUP_HOME="/var/lib/astrbot/.rustup" \
            CARGO_TARGET_DIR="$CACHE_DIR/cargo_target" \
            uv pip install --reinstall "$APP_DIR"; then
            :
        else
            command_status=$?
            return "$command_status"
        fi

        if [ -n "$current_version" ]; then
            if _runuser_with_env "$env_file" "$runtime_root" \
                sh -c 'printf "%s\n" "$1" > "$2"' \
                sh "$current_version" "$marker_file"; then
                :
            else
                command_status=$?
                return "$command_status"
            fi
        fi
        if [ -e "$rollback_marker" ] || [ -L "$rollback_marker" ]; then
            [ -f "$rollback_marker" ] && [ ! -L "$rollback_marker" ] || {
                echo "❌ Error: Refusing to remove invalid rollback marker." >&2
                return 1
            }
            rm -f -- "$rollback_marker"
        fi
    fi
}

# A restored venv deliberately keeps its old application-version marker.  This
# marker makes automatic service starts use that known-good environment until a
# public forced sync succeeds.
venv_rollback_marker_is_valid() {
    local venv_path="$1" marker
    marker="$venv_path/.astrbot-rollback"
    [ -f "$marker" ] && [ ! -L "$marker" ] || return 1
    venv_is_valid "$venv_path" || return 1
    grep -Eq '^version=[^[:space:]]+$' "$marker" &&
        grep -Eq '^reason=[[:alnum:]_-]+$' "$marker"
}

venv_is_valid() {
    local venv_path="$1" owner
    [ -d "$venv_path" ] && [ ! -L "$venv_path" ] || return 1
    [ -f "$venv_path/pyvenv.cfg" ] && [ ! -L "$venv_path/pyvenv.cfg" ] || return 1
    [ -x "$venv_path/bin/python" ] && [ -x "$venv_path/bin/astrbot" ] || return 1
    [ -f "$venv_path/.astrbot-app-version" ] && [ ! -L "$venv_path/.astrbot-app-version" ] || return 1
    grep -Eq '^[^[:space:]]+$' "$venv_path/.astrbot-app-version" || return 1
    if [ -e "$venv_path/.astrbot-rollback" ] || [ -L "$venv_path/.astrbot-rollback" ]; then
        [ -f "$venv_path/.astrbot-rollback" ] && [ ! -L "$venv_path/.astrbot-rollback" ] || return 1
    fi
    if id astrbot >/dev/null 2>&1; then
        owner="$(stat -c '%U:%G' "$venv_path")"
        [ "$owner" = 'astrbot:astrbot' ] || return 1
    fi
}

# O_EXCL also refuses special files created concurrently (unlike noclobber).
_create_venv_maintenance_lock_file() {
    python - "$1" <<'PY'
import os
import sys

try:
    fd = os.open(sys.argv[1], os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)
except FileExistsError:
    pass  # Another starter won; the caller validates and reuses its inode.
else:
    try:
        os.fchmod(fd, 0o644)  # Shared service locks must remain readable.
    finally:
        os.close(fd)
PY
}

ensure_venv_maintenance_lock_file() {
    local lock_file
    lock_file="$(venv_maintenance_lock_file)" || return $?
    if [ ! -e "$lock_file" ] && [ ! -L "$lock_file" ]; then
        _create_venv_maintenance_lock_file "$lock_file" || return $?
    fi
    [ -f "$lock_file" ] && [ ! -L "$lock_file" ] || {
        echo "❌ Error: Refusing non-regular maintenance lock path: $lock_file" >&2
        return 1
    }
}

acquire_venv_maintenance_lock() {
    local lock_file
    ensure_venv_maintenance_lock_file || return $?
    lock_file="$(venv_maintenance_lock_file)"
    exec {VENV_MAINTENANCE_LOCK_FD}>>"$lock_file" || return $?
    if ! flock -n "$VENV_MAINTENANCE_LOCK_FD"; then
        exec {VENV_MAINTENANCE_LOCK_FD}>&-
        unset VENV_MAINTENANCE_LOCK_FD
        echo "⚠️  Instance '$instance' is being started or maintained; no changes made." >&2
        return 75
    fi
}

release_venv_maintenance_lock() {
    [ -n "${VENV_MAINTENANCE_LOCK_FD:-}" ] || return 0
    flock -u "$VENV_MAINTENANCE_LOCK_FD" || true
    exec {VENV_MAINTENANCE_LOCK_FD}>&-
    unset VENV_MAINTENANCE_LOCK_FD
}

create_venv_backup() {
    local source_path="$1" backup_path="$2" backup_parent backup_stage
    venv_is_valid "$source_path" || {
        echo "❌ Error: Refusing to back up invalid virtualenv: $source_path" >&2
        return 1
    }
    backup_parent="$(dirname "$backup_path")"
    mkdir -p -- "$backup_parent" || return 1
    backup_stage="$(mktemp -d "$backup_parent/.${instance}-venv-backup.XXXXXX")" || return 1
    if ! cp -a --reflink=auto "$source_path/." "$backup_stage/" || ! venv_is_valid "$backup_stage"; then
        rm -rf -- "$backup_stage"
        echo "❌ Error: Failed to create a valid virtualenv backup." >&2
        return 1
    fi
    rm -rf -- "$backup_path"
    if ! mv --no-copy -T -- "$backup_stage" "$backup_path"; then
        rm -rf -- "$backup_stage"
        echo "❌ Error: Failed to publish virtualenv backup." >&2
        return 1
    fi
}

write_venv_rollback_marker() (
    local staged_venv="$1" reason="$2" marker version
    marker="$staged_venv/.astrbot-rollback"
    [ ! -L "$marker" ] && { [ ! -e "$marker" ] || [ -f "$marker" ]; } || return 1
    [ -f "$staged_venv/.astrbot-app-version" ] && [ ! -L "$staged_venv/.astrbot-app-version" ] || return 1
    version="$(cat "$staged_venv/.astrbot-app-version")" || return $?
    [[ "$version" =~ ^[^[:space:]]+$ ]] || return 1
    case "$reason" in
    sync_failure | update_failure | stability_failure) ;;
    *) return 1 ;;
    esac
    _atomic_replace_file "$marker" 0644 astrbot:astrbot printf 'version=%s\nreason=%s\n' "$version" "$reason"
)

ATOMIC_RESTORE_CONTAINER=""
ATOMIC_RESTORE_EXCHANGED_PATH=""

restore_venv_backup_atomically() {
    local destination="$1" backup_path="$2" reason="$3"
    local parent base container stage parent_dev stage_dev container_prefix
    ATOMIC_RESTORE_CONTAINER=""
    ATOMIC_RESTORE_EXCHANGED_PATH=""
    venv_is_valid "$backup_path" || {
        echo "❌ Error: Refusing invalid virtualenv backup: $backup_path" >&2
        return 1
    }
    parent="$(dirname "$destination")"
    base="$(basename "$destination")"
    [ -d "$parent" ] && [ ! -L "$parent" ] || return 1
    # `.venv` is already hidden.  Strip only its leading dot before adding the
    # rollback prefix so recovery artifacts have the stable, inspectable name
    # `.venv.rollback.XXXXXX` rather than `..venv.rollback.XXXXXX`.
    container_prefix="${base#.}"
    container="$(mktemp -d "$parent/.${container_prefix}.rollback.XXXXXX")" || return 1
    stage="$container/$base"
    if ! cp -a --reflink=auto "$backup_path" "$stage" || ! venv_is_valid "$stage" ||
        ! write_venv_rollback_marker "$stage" "$reason"; then
        rm -rf -- "$container"
        echo "❌ Error: Failed to stage a valid rollback virtualenv." >&2
        return 1
    fi
    parent_dev="$(stat -c '%d' "$parent")"
    stage_dev="$(stat -c '%d' "$stage")"
    if [ "$parent_dev" != "$stage_dev" ]; then
        rm -rf -- "$container"
        echo "❌ Error: Rollback stage is not on the destination filesystem." >&2
        return 1
    fi
    if [ -e "$destination" ] || [ -L "$destination" ]; then
        if [ ! -d "$destination" ] || [ -L "$destination" ] ||
            ! mv --exchange --no-copy -T -- "$stage" "$destination"; then
            rm -rf -- "$container"
            echo "❌ Error: Atomic rollback exchange failed; live venv was preserved." >&2
            return 1
        fi
        ATOMIC_RESTORE_EXCHANGED_PATH="$stage"
    elif ! mv --no-copy -T -- "$stage" "$destination"; then
        rm -rf -- "$container"
        echo "❌ Error: Atomic rollback publish failed." >&2
        return 1
    fi
    ATOMIC_RESTORE_CONTAINER="$container"
    venv_rollback_marker_is_valid "$destination" || {
        echo "❌ Error: Rollback marker validation failed after publish." >&2
        return 1
    }
}

cleanup_atomic_restore_after_healthy() {
    local backup_path="$1"
    [ -n "${ATOMIC_RESTORE_CONTAINER:-}" ] && rm -rf -- "$ATOMIC_RESTORE_CONTAINER"
    rm -rf -- "$backup_path"
    ATOMIC_RESTORE_CONTAINER=""
    # shellcheck disable=SC2034 # Exposed recovery state, inspected by callers/tests.
    ATOMIC_RESTORE_EXCHANGED_PATH=""
}

report_atomic_restore_preserved() {
    local backup_path="$1"
    echo "⚠️  Rollback recovery retained for inspection:" >&2
    [ -z "${ATOMIC_RESTORE_CONTAINER:-}" ] || echo "    exchanged venv: $ATOMIC_RESTORE_CONTAINER" >&2
    echo "    backup: $backup_path" >&2
}

restart_restored_instance_healthy() {
    local unit="astrbot@$1" sample=0
    systemctl start "$unit" || return 1
    while [ "$sample" -lt "$ROLLBACK_HEALTH_SECS" ]; do
        sleep 1
        systemctl is-active --quiet "$unit" || return 1
        sample=$((sample + 1))
    done
}

# ─── Config rendering ────────────────────────────────────────────────────────

# Sync dashboard-related fields from conf file to cmd_config.json.
# This ensures environment variables (ASTRBOT_PORT, ASTRBOT_HOST, etc.)
# take effect in the runtime config.
sync_cmd_config() {
    local cmd_config="${ASTRBOT_ROOT}/data/cmd_config.json"

    if [ -L "$cmd_config" ] || { [ -e "$cmd_config" ] && [ ! -f "$cmd_config" ]; }; then
        echo "❌ Error: Refusing non-regular dashboard config: $cmd_config" >&2
        return 1
    fi
    # If file does not exist or is empty, AstrBot will create it on first run;
    # nothing to sync yet — bail out to avoid spurious errors.
    if [ ! -f "$cmd_config" ]; then
        return 0
    fi
    if [ ! -s "$cmd_config" ]; then
        echo "⚠️  cmd_config.json is empty; skipping sync (AstrBot will regenerate it on first run)." >&2
        return 0
    fi

    local port
    port="$(_normalize_port "${ASTRBOT_PORT:-3000}")" || return 2
    _replace_instance_file "$cmd_config" _write_dashboard_config "$cmd_config" \
        "$port" "${ASTRBOT_HOST:-0.0.0.0}" "${ASTRBOT_SSL_ENABLE:-false}" \
        "${ASTRBOT_SSL_CERT:-}" "${ASTRBOT_SSL_KEY:-}" "${ASTRBOT_LOG_LEVEL:-INFO}" \
        "${ASTRBOT_DASHBOARD_ENABLE:-true}"
}

# One implementation for all installations; never execute a service-owned
# virtualenv Python as root or truncate cmd_config.json before parsing succeeds.
_write_dashboard_config() {
    python -I - "$@" <<'PY'
import json
import sys

path, port, host, ssl_enabled, cert, key, level, enabled = sys.argv[1:]
with open(path, encoding="utf-8-sig") as config_file:
    data = json.load(config_file)
if not isinstance(data, dict):
    raise ValueError("Dashboard configuration must be a JSON object")
dashboard = data.setdefault("dashboard", {})
ssl = dashboard.setdefault("ssl", {})
dashboard.update(port=int(port), host=host, enable=enabled.lower() in ("true", "1", "yes"))
ssl.update(enable=ssl_enabled.lower() in ("true", "1", "yes"), cert_file=cert, key_file=key)
data["log_level"] = level
json.dump(data, sys.stdout, indent=2, ensure_ascii=False)
sys.stdout.write("\n")
PY
}

# Render /etc/astrbot/tmpl.conf (or $SCRIPT_DIR/tmpl.conf) into an instance config.
# Handles port auto-assignment automatically.
_render_template_content() {
    local content
    content="$(envsubst <"$1")" || return $?
    bash -n <<<"$content" || return $?
    # Do not publish a new shell configuration when runtime JSON sync fails.
    sync_cmd_config >&2 || return $?
    printf '%s\n' "$content"
}

render_config_from_template() (
    local tmpl_file conf_file

    tmpl_file="$CONFIG_DIR/tmpl.conf"
    if [ ! -f "$tmpl_file" ]; then
        # Try script-relative path (for dev/test environments)
        if [ -f "${SCRIPT_DIR:-}/tmpl.conf" ]; then
            tmpl_file="${SCRIPT_DIR}/tmpl.conf"
        else
            echo "❌ Error: Config template not found (looked in $APP_DIR and script paths)." >&2
            return 1
        fi
    fi

    conf_file="$(conf_file)" || return $?
    load_instance_config || return $?

    INSTANCE_NAME="$instance"
    unset ASTRBOT_HOST ASTRBOT_PORT
    ASTRBOT_ROOT="${ASTRBOT_ROOT:-$SYSTEM_ROOT/$instance}"
    ASTRBOT_HOST="0.0.0.0"
    find_free_port 3000 || return $?
    mkdir -p -- "$CONFIG_DIR" || return $?

    export INSTANCE_NAME ASTRBOT_HOST ASTRBOT_PORT ASTRBOT_ROOT \
        ASTRBOT_SSL_ENABLE ASTRBOT_SSL_CERT ASTRBOT_SSL_KEY ASTRBOT_SSL_CA_CERTS
    _atomic_replace_file "$conf_file" preserve "" _render_template_content "$tmpl_file" || return $?

    echo "✅ Config reset to template: $conf_file"
    echo "   (ASTRBOT_PORT=$ASTRBOT_PORT, ASTRBOT_HOST=$ASTRBOT_HOST)"
    return 0
)

# ─── Instance discovery ──────────────────────────────────────────────────────

# Print one instance name per line from CONFIG_DIR/*.conf (only those with data dirs).
# Uses process substitution to avoid the subshell-pipe issue where while-loop
# output doesn't reach the final sort when using a traditional pipeline.
iter_instances() {
    [ ! -d "$CONFIG_DIR" ] && return 0
    local name
    while IFS= read -r conf; do
        [ -f "$conf" ] || continue
        name=$(basename "$conf" .conf)
        [ -d "$SYSTEM_ROOT/$name" ] && printf '%s\n' "$name"
    done < <(find "$CONFIG_DIR" -maxdepth 1 -name '*.conf' -type f 2>/dev/null) |
        sort -u
}

# Remove only idle virtualenvs while holding the same lock used by startup and
# updates. Keep recovery snapshots and never follow an instance-root symlink.
clean_instance_venvs() {
    local root failed=0
    for root in "$SYSTEM_ROOT"/*; do
        [ -d "$root" ] && [ ! -L "$root" ] && [ -d "$root/.venv" ] || continue
        if (
            instance="${root##*/}"
            validate_instance_name "$instance" || exit 1
            ASTRBOT_ROOT="$root"
            acquire_venv_maintenance_lock || exit $?
            if systemctl is-active --quiet "astrbot@$instance" 2>/dev/null; then
                release_venv_maintenance_lock
                echo "⚠️  Keeping active instance virtualenv: $instance" >&2
                exit 75
            fi
            if ! rm -rf -- "$root/.venv"; then
                release_venv_maintenance_lock
                exit 1
            fi
            release_venv_maintenance_lock
        ); then
            :
        else
            failed=1
        fi
    done
    return "$failed"
}

# ─── Certbot helpers ─────────────────────────────────────────────────────────

certbot_live_dir() {
    printf '/etc/letsencrypt/live/%s\n' "$1"
}

# Sync /etc/letsencrypt/live/$cert_name/* → $CERTBOT_INSTANCE_CERTS_DIR/$instance/
sync_certbot_cert_for_instance() {
    local cert_name="$1"
    # NOTE: inline the dest path to avoid zsh local-scope issues with
    # command substitutions that reference other local vars.
    local live_dir
    live_dir="$(certbot_live_dir "$cert_name")" || return $?
    local src_cert="$live_dir/fullchain.pem"
    local src_key="$live_dir/privkey.pem"
    local dest_dir="$CERTBOT_INSTANCE_CERTS_DIR/${instance}"

    [ -f "$src_cert" ] || {
        echo "❌ Error: Certificate file not found: $src_cert" >&2
        return 1
    }
    [ -f "$src_key" ] || {
        echo "❌ Error: Private key file not found: $src_key" >&2
        return 1
    }

    # Determine group flag (skip if 'astrbot' group doesn't exist in this env)
    local -a group_args=()
    if getent group astrbot >/dev/null 2>&1; then group_args=(-g astrbot); fi

    install -d -m750 -o root "${group_args[@]}" "$dest_dir" || return $?
    install -m640 -o root "${group_args[@]}" "$src_cert" "$dest_dir/fullchain.pem" || return $?
    install -m640 -o root "${group_args[@]}" "$src_key" "$dest_dir/privkey.pem"
}

# Write the certbot deploy hook that triggers __certbot-deploy on renewal.
install_certbot_deploy_hook() {
    local cert_name="$1"
    local hook_path
    hook_path="$(certbot_hook_path)"
    local -a group_args=()
    if getent group astrbot >/dev/null 2>&1; then group_args=(-g astrbot); fi

    install -d -m755 "${group_args[@]}" /etc/letsencrypt/renewal-hooks/deploy || return $?
    cat >"$hook_path" <<EOF
#!/bin/sh
set -e
/usr/bin/astrbotctl __certbot-deploy "${instance}" "${cert_name}"
EOF
    chmod 755 "$hook_path"
}

# Enable the system certbot renewal timer if available.
enable_certbot_renew_timer() {
    if systemctl list-unit-files certbot-renew.timer >/dev/null 2>&1; then
        systemctl enable --now certbot-renew.timer && return 0
    fi
    if systemctl list-unit-files certbot.timer >/dev/null 2>&1; then
        systemctl enable --now certbot.timer && return 0
    fi
    echo "⚠️  Warning: No certbot renewal timer unit found. Configure renewal manually." >&2
    return 1
}

# ─── Git helpers ─────────────────────────────────────────────────────────────

# Ensure /opt/astrbot exists.
_ensure_app_dir() {
    if [ -d "$APP_DIR" ] && [ -f "$APP_DIR/pyproject.toml" ]; then
        return 0
    fi

    echo "❌ Error: APP_DIR $APP_DIR does not exist or is missing pyproject.toml." >&2
    echo "   Reinstall or upgrade the astrbot-git package with your package manager or AUR helper to restore it." >&2
    return 1
}

# A server must never create an unrecoverable dashboard password during startup.
# Keep this check deliberately narrow: CLI password provisioning is allowed before
# the service starts, while `run` requires a persisted upstream PBKDF2 hash.
dashboard_password_is_configured() {
    local cmd_config="$ASTRBOT_ROOT/data/cmd_config.json"

    [ -f "$cmd_config" ] || return 1
    python - "$cmd_config" <<'PY'
import json
import sys

try:
    with open(sys.argv[1], encoding="utf-8-sig") as config_file:
        password_hash = json.load(config_file).get("dashboard", {}).get("pbkdf2_password")
except (OSError, ValueError, json.JSONDecodeError):
    raise SystemExit(1)

parts = password_hash.split("$") if isinstance(password_hash, str) else []
is_valid = (
    len(parts) == 4
    and parts[0] == "pbkdf2_sha256"
    and parts[1].isdigit()
    and bool(parts[2])
    and bool(parts[3])
)
raise SystemExit(0 if is_valid else 1)
PY
}

# ─── Core run logic ──────────────────────────────────────────────────────────

# Main entry point for running an AstrBot instance.
# Sets up env, ensures venv exists, then execs into the Python process.
# Called directly by systemd (__run_astrbot) or by 'astrbotctl run'.
run_astrbot() {
    setup_runtime_env || return $?

    # Self-heal: try to restore /opt/astrbot if it's gone
    _ensure_app_dir || {
        echo "❌ Error: /opt/astrbot is missing. Cannot start AstrBot." >&2
        exit 1
    }

    local venv_astrbot="$UV_PROJECT_ENVIRONMENT/bin/astrbot"
    # shellcheck disable=SC2119 # No arguments intentionally means automatic sync.
    ensure_instance_env_synced || {
        echo "❌ Error: Failed to prepare Python environment for instance '$instance'." >&2
        exit 1
    }

    if [ "$#" -eq 0 ] || [ "${1:-}" = "run" ]; then
        if ! dashboard_password_is_configured; then
            echo "❌ Error: Dashboard password is not configured for instance '$instance'." >&2
            echo "   Run: sudo astrbotctl password $instance" >&2
            exit 1
        fi
    fi

    cd "$ASTRBOT_ROOT" || exit

    # Sync env vars from conf file to cmd_config.json so they take effect at runtime
    sync_cmd_config || return $?

    # If no arguments provided, default to running the server 'run' subcommand.
    # Otherwise, pass through the provided arguments as top-level astrbot subcommands.
    local _cmd
    if [ "$#" -eq 0 ]; then
        _cmd=("$venv_astrbot" "run")
    else
        _cmd=("$venv_astrbot" "$@")
    fi
    exec env -i \
        HOME="$HOME" \
        PATH="$UV_PROJECT_ENVIRONMENT/bin:$PATH" \
        ASTRBOT_ROOT="$ASTRBOT_ROOT" \
        ASTRBOT_HOST="$ASTRBOT_HOST" \
        ASTRBOT_PORT="$ASTRBOT_PORT" \
        ASTRBOT_SSL_ENABLE="$ASTRBOT_SSL_ENABLE" \
        ASTRBOT_SSL_CERT="$ASTRBOT_SSL_CERT" \
        ASTRBOT_SSL_KEY="$ASTRBOT_SSL_KEY" \
        ASTRBOT_SSL_CA_CERTS="$ASTRBOT_SSL_CA_CERTS" \
        DASHBOARD_SSL_ENABLE="$ASTRBOT_SSL_ENABLE" \
        DASHBOARD_SSL_CERT="$ASTRBOT_SSL_CERT" \
        DASHBOARD_SSL_KEY="$ASTRBOT_SSL_KEY" \
        DASHBOARD_SSL_CA_CERTS="$ASTRBOT_SSL_CA_CERTS" \
        XDG_CACHE_HOME="$XDG_CACHE_HOME" \
        XDG_CONFIG_HOME="$XDG_CONFIG_HOME" \
        XDG_DATA_HOME="$XDG_DATA_HOME" \
        XDG_STATE_HOME="$XDG_STATE_HOME" \
        UV_PROJECT_ENVIRONMENT="$UV_PROJECT_ENVIRONMENT" \
        UV_PYTHON_INSTALL_DIR="$UV_PYTHON_INSTALL_DIR" \
        ASTRBOT_SYSTEMD="$ASTRBOT_SYSTEMD" \
        ASTRBOT_DESKTOP_CLIENT="$ASTRBOT_DESKTOP_CLIENT" \
        "${_cmd[@]}"
}

# ─── Diagnostic / info ──────────────────────────────────────────────────────

print_help() {
    cat <<'HELP'
AstrBot Control Tool

Usage:
  sudo astrbotctl init <name>                       # Create a new instance
  sudo astrbotctl cp <src> <dst>                   # Copy an instance
  sudo astrbotctl rm <name>                        # Remove an instance
  sudo astrbotctl reset <name>                     # Regenerate config from template
  sudo astrbotctl certbot <name>                   # Issue/renew HTTPS certs
  sudo astrbotctl sync [instance|--all]            # Refresh instance venv(s) from /opt/astrbot
  astrbotctl start <name>                          # Start via systemd
  astrbotctl stop <name>                           # Stop via systemd
  astrbotctl status <name>                         # Check status
  astrbotctl ls                                    # List instances
  astrbotctl paths <name>                          # Print instance-related paths
  sudo astrbotctl password [--username NAME] <name> # Set dashboard password interactively
  astrbotctl admin ...                              # Retired; use password instead
  sudo astrbotctl update [instance|--all]                    # Sync installed package into venv(s), restart, monitor

Credential migration:
  astrbotctl admin is retired. Use `sudo astrbotctl password [--username NAME]
  <name>` so the password is prompted for on the controlling terminal.

Backup migration:
  astrbotctl init -f, export, and import are retired because upstream removed
  the backup CLI. Use the authenticated Dashboard backup and restore workflow;
  restoring data is destructive.

Debugging:
  astrbotctl run <name> [astrbot-run-args]  # Run in foreground
  astrbotctl cli <name> [args]               # Run astrbot command directly
HELP
}

print_paths() {
    local root="${ASTRBOT_ROOT:-$SYSTEM_ROOT/$instance}"
    local home_dir="$root"
    local conf_file log_dir_value

    conf_file="$(conf_file)"
    # uv default: ~/.cache/uv
    log_dir_value="${LOG_DIR:-$root/logs}"

    echo "# Instance: $instance"
    echo "INSTANCE_NAME=$instance"
    echo "SYSTEM_ROOT=$SYSTEM_ROOT"
    echo "ASTRBOT_ROOT=$root"
    echo "HOME_DIR=$home_dir"
    echo "WORKING_DIR=$home_dir"
    echo "DATA_DIR=$root/data"
    echo "CONFIG_FILE=$conf_file"
    echo "VENV_DIR=$(venv_dir)"
    echo "CACHE_DIR=$CACHE_DIR"
    echo "XDG_CACHE_HOME=$root/.cache"
    echo "XDG_CONFIG_HOME=$root/.config"
    echo "XDG_DATA_HOME=$root/.local/share"
    echo "XDG_STATE_HOME=$root/.local/state"
    echo "UV_CACHE_DIR=$root/.cache/uv"
    echo "PYTHON_INSTALL_DIR=$CACHE_DIR/python"
    echo "LOG_DIR=$log_dir_value"
    echo "APP_DIR=$APP_DIR"
    echo "SYSTEMD_UNIT=astrbot@${instance}.service"
    echo "ASTRBOT_HOST=${ASTRBOT_HOST:-}"
    echo "ASTRBOT_PORT=${ASTRBOT_PORT:-}"
    [ -n "${ASTRBOT_DASHBOARD_ENABLE:-}" ] && echo "ASTRBOT_DASHBOARD_ENABLE=$ASTRBOT_DASHBOARD_ENABLE"
}