aboutsummarylogtreecommitdiffstats
path: root/astrbotctl
blob: 53079de25c61e70d56400765234813b31317b548 (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
#!/bin/bash
set -e

# ─── Locate script and load shared functions ──────────────────────────────────
SCRIPT_DIR="$(cd "$(dirname "$0")" >/dev/null 2>&1 && pwd || printf '%s' ".")"
# shellcheck source=astrbotctl.functions
. "${SCRIPT_DIR}/astrbotctl.functions"

# ─── Entry point ──────────────────────────────────────────────────────────────
cmd="${1:-}"
[ -n "$cmd" ] && shift

case "$cmd" in

# ── Internal: called by certbot deploy hook ───────────────────────────────────
__certbot-deploy)
    instance="${1?}" && shift || exit 1
    cert_name="${1?}" && shift || exit 1
    require_instance
    validate_instance_name "$cert_name" || exit 1
    require_root
    sync_certbot_cert_for_instance "$cert_name"
    systemctl try-restart "astrbot@${instance}.service" >/dev/null 2>&1 || true
    ;;

# ── Internal: systemd service entry point ────────────────────────────────────
__run_astrbot)
    instance="${1?}" && shift || exit 1
    require_instance
    load_instance_config
    run_astrbot run "$@"
    ;;

# ── cli ───────────────────────────────────────────────────────────────────────
cli)
    instance="${1?Usage: astrbotctl cli <instance_name> [args...]}"
    shift
    require_instance
    load_instance_config
    run_astrbot "$@"
    ;;

# ── init ─────────────────────────────────────────────────────────────────────
init)
    instance=""

    while [ "$#" -gt 0 ]; do
        case "$1" in
        -f | --backup)
            echo "❌ Error: Backup restore is no longer supported by astrbotctl." >&2
            echo "   Use the authenticated Dashboard backup restore after initializing an instance." >&2
            exit 2
            ;;
        -h | --help)
            print_help
            exit 0
            ;;
        -*)
            echo "❌ Error: Unknown option: $1" >&2
            exit 1
            ;;
        *)
            [ -n "$instance" ] && {
                echo "❌ Error: Unexpected extra argument: $1" >&2
                exit 1
            }
            instance="$1"
            shift
            ;;
        esac
    done

    require_instance
    require_root

    conf_file="${CONFIG_DIR}/${instance}.conf"
    astrbot_root="${SYSTEM_ROOT}/${instance}"

    [ -e "$astrbot_root" ] || [ -L "$astrbot_root" ] || [ -e "$conf_file" ] || [ -L "$conf_file" ] && {
        echo "❌ Error: Instance data or configuration already exists for '$instance'." >&2
        exit 1
    }

    echo ">>> Initializing instance: $instance"

    tmpl_file="$CONFIG_DIR/tmpl.conf"
    [ ! -f "$tmpl_file" ] && {
        echo "❌ Error: Config template not found at $tmpl_file" >&2
        exit 1
    }

    find_free_port 3000
    install -dm755 -o astrbot -g astrbot "$astrbot_root"

    export INSTANCE_NAME="$instance" ASTRBOT_HOST="0.0.0.0" ASTRBOT_PORT ASTRBOT_ROOT="$astrbot_root"
    envsubst <"$tmpl_file" >"$conf_file"
    chmod 644 "$conf_file"

    # Load so the bootstrap command picks up the right port
    load_instance_config

    echo ">>> Bootstrapping AstrBot data..."
    ensure_instance_env_synced || {
        echo "❌ Error: Failed to prepare Python environment for instance '$instance'." >&2
        exit 1
    }
    venv_astrbot="$(venv_dir)/bin/astrbot"
    run_astrbot_env_cmd --command-cwd "$ASTRBOT_ROOT" \
        bash -c 'printf "Y\nY\n" | "$1" init' bash "$venv_astrbot"
    chown -R astrbot:astrbot "$astrbot_root"
    local_venv_dir="$(venv_dir)"
    [ -d "$local_venv_dir" ] && chown -R astrbot:astrbot "$local_venv_dir"

    echo "✅ Instance initialized."
    echo "   Data Directory: $astrbot_root"
    echo "   Configuration:  $conf_file"
    echo "   Port:           $ASTRBOT_PORT"
    echo ""
    echo "Set a dashboard password before starting the instance:"
    echo "   sudo astrbotctl password $instance"
    echo ""
    echo "Then start the instance:"
    echo "   systemctl start astrbot@$instance"
    ;;

# ── cp ───────────────────────────────────────────────────────────────────────
cp)
    if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then
        echo "Usage: sudo astrbotctl cp <source_instance> <dest_instance>"
        exit 0
    fi
    [ "$#" -eq 2 ] || {
        echo "Usage: sudo astrbotctl cp <source_instance> <dest_instance>" >&2
        exit 2
    }
    src="$1"
    dst="$2"
    validate_instance_name "$src" && validate_instance_name "$dst" || exit 1
    require_root

    src_root="${SYSTEM_ROOT}/${src}"
    dst_root="${SYSTEM_ROOT}/${dst}"
    dst_conf="${CONFIG_DIR}/${dst}.conf"

    [ ! -d "$src_root" ] || [ -L "$src_root" ] && {
        echo "❌ Error: Source instance '$src' does not exist." >&2
        exit 1
    }
    [ -e "$dst_root" ] || [ -L "$dst_root" ] && {
        echo "❌ Error: Destination directory '$dst_root' already exists." >&2
        exit 1
    }
    [ -e "$dst_conf" ] || [ -L "$dst_conf" ] && {
        echo "❌ Error: Destination config '$dst_conf' already exists." >&2
        exit 1
    }

    tmpl_file="$CONFIG_DIR/tmpl.conf"
    [ -f "$tmpl_file" ] || {
        echo "❌ Error: Config template not found at $tmpl_file" >&2
        exit 1
    }

    # Reuse unified port allocation
    instance="$src"
    load_instance_config
    instance="$dst"
    find_free_port 3000

    echo ">>> Copying instance: $src -> $dst"
    echo "    Copying data directory..."
    cp -a -- "$src_root" "$dst_root"
    # Virtualenv entrypoints contain absolute paths and cannot be relocated.
    rm -rf -- "$dst_root/.venv" "$dst_root/.venv-maintenance.lock"
    chown -hR astrbot:astrbot "$dst_root"

    export INSTANCE_NAME="$dst" ASTRBOT_HOST="${ASTRBOT_HOST:-0.0.0.0}" \
        ASTRBOT_PORT ASTRBOT_ROOT="$dst_root"
    envsubst <"$tmpl_file" >"$dst_conf"
    chmod 644 "$dst_conf"

    echo "✅ Instance copied."
    echo "   Source: $src  →  Dest: $dst"
    echo "   Port: $ASTRBOT_PORT"
    echo ""
    echo "To start the new instance:"
    echo "   systemctl start astrbot@$dst"
    ;;

# ── rm ────────────────────────────────────────────────────────────────────────
rm)
    [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ] && {
        echo "Usage: sudo astrbotctl rm <name>"
        exit 0
    }
    instance="${1:-}"
    require_root
    require_instance
    certbot_managed="" certbot_cert_name=""

    conf_file="$(conf_file)"
    exact_root="${SYSTEM_ROOT}/${instance}"
    ASTRBOT_ROOT="$exact_root"
    venv_dir="$exact_root/.venv"

    if [ -f "$conf_file" ]; then
        load_instance_config
        certbot_managed="${ASTRBOT_CERTBOT_MANAGED:-}"
        certbot_cert_name="${ASTRBOT_CERTBOT_CERT_NAME:-}"
    fi

    # A malformed or missing config must never redirect removal outside this
    # package's fixed per-instance data root.
    ASTRBOT_ROOT="$exact_root"

    [ ! -d "$ASTRBOT_ROOT" ] && [ ! -f "$conf_file" ] &&
        {
            echo "❌ Error: Instance '$instance' does not exist." >&2
            exit 1
        }

    echo ">>> Removing instance: $instance"

    systemctl is-active --quiet "astrbot@$instance" 2>/dev/null &&
        {
            echo "    Stopping service..."
            systemctl stop "astrbot@$instance"
        }
    systemctl is-enabled --quiet "astrbot@$instance" 2>/dev/null &&
        {
            echo "    Disabling service..."
            systemctl disable "astrbot@$instance"
        }

    [ -d "$ASTRBOT_ROOT" ] && {
        echo "    Removing data directory: $ASTRBOT_ROOT"
        rm -rf "$ASTRBOT_ROOT"
    }
    [ -f "$conf_file" ] && {
        echo "    Removing configuration: $conf_file"
        rm -f "$conf_file"
    }
    [ -d "$venv_dir" ] && {
        echo "    Removing venv: $venv_dir"
        rm -rf "$venv_dir"
    }
    [ -f "$(certbot_hook_path)" ] && {
        echo "    Removing certbot hook: $(certbot_hook_path)"
        rm -f "$(certbot_hook_path)"
    }
    [ -d "$(certbot_instance_cert_dir)" ] &&
        {
            echo "    Removing cert copy: $(certbot_instance_cert_dir)"
            rm -rf "$(certbot_instance_cert_dir)"
        }

    if [ "$certbot_managed" = "true" ] && [ -n "$certbot_cert_name" ] &&
        command -v certbot >/dev/null 2>&1; then
        echo "    Removing certbot cert: $certbot_cert_name"
        certbot delete --non-interactive --cert-name "$certbot_cert_name" >/dev/null 2>&1 || true
    fi

    echo "✅ Instance '$instance' removed."
    ;;

# ── reset ─────────────────────────────────────────────────────────────────────
reset)
    [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ] && {
        echo "Usage: sudo astrbotctl reset <name>"
        exit 0
    }
    instance="${1:-}"
    require_root
    require_instance

    if render_config_from_template; then
        command -v systemctl >/dev/null 2>&1 &&
            systemctl try-reload-or-restart "astrbot@$instance" 2>/dev/null || true
        exit 0
    fi
    exit 1
    ;;

# ── certbot ───────────────────────────────────────────────────────────────────
certbot)
    [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ] && {
        echo "Usage: sudo astrbotctl certbot <name>"
        exit 0
    }
    instance="${1:-}"
    require_root
    require_instance

    command -v certbot >/dev/null 2>&1 || {
        echo "❌ Error: certbot is not installed." >&2
        exit 1
    }

    load_instance_config
    conf_file="$(conf_file)"

    [ ! -d "$ASTRBOT_ROOT" ] || [ ! -f "$conf_file" ] &&
        {
            echo "❌ Error: Instance '$instance' is not initialized." >&2
            exit 1
        }

    domains="${ASTRBOT_CERTBOT_DOMAINS:-}"
    email="${ASTRBOT_CERTBOT_EMAIL:-}"
    cert_name="astrbot-${instance}"

    printf "Domains for %s (space-separated) [%s]: " "$instance" "$domains"
    read -r d && [ -z "$d" ] && d="$domains"
    [ -z "$d" ] && {
        echo "❌ Error: At least one domain is required." >&2
        exit 1
    }
    domains="$d"

    printf "Email for Let's Encrypt notices [%s]: " "$email"
    read -r e && [ -z "$e" ] && e="$email"
    [ -z "$e" ] && {
        echo "❌ Error: Email is required." >&2
        exit 1
    }
    email="$e"

    # Preserve each domain as one argument; never expand globs or option strings.
    read -r -a domain_list <<<"$domains"
    domain_args=()
    for domain in "${domain_list[@]}"; do
        domain_args+=(-d "$domain")
    done

    ss -lntH "( sport = :80 )" 2>/dev/null | grep -q . && {
        echo "❌ Error: Port 80 is in use. Stop the process using it, then retry." >&2
        exit 1
    }

    echo ">>> Requesting Let's Encrypt certificate..."
    certbot certonly \
        --standalone --preferred-challenges http --http-01-port 80 \
        --agree-tos --non-interactive \
        --email "$email" --cert-name "$cert_name" "${domain_args[@]}"

    sync_certbot_cert_for_instance "$cert_name"

    cert_dir="$(certbot_instance_cert_dir)"
    cert_file="$cert_dir/fullchain.pem"
    key_file="$cert_dir/privkey.pem"

    upsert_conf_var "$conf_file" "ASTRBOT_DASHBOARD_SSL_ENABLE" "true"
    upsert_conf_var "$conf_file" "ASTRBOT_SSL_CERT" "$cert_file"
    upsert_conf_var "$conf_file" "ASTRBOT_SSL_KEY" "$key_file"
    upsert_conf_var "$conf_file" "ASTRBOT_CERTBOT_MANAGED" "true"
    upsert_conf_var "$conf_file" "ASTRBOT_CERTBOT_CERT_NAME" "$cert_name"
    upsert_conf_var "$conf_file" "ASTRBOT_CERTBOT_DOMAINS" "$domains"
    upsert_conf_var "$conf_file" "ASTRBOT_CERTBOT_EMAIL" "$email"

    install_certbot_deploy_hook "$cert_name"
    enable_certbot_renew_timer || true

    echo ">>> Restarting astrbot instance: $instance"
    systemctl restart "astrbot@$instance"

    echo "✅ HTTPS configured for '$instance'"
    echo "   Certificate: $cert_file"
    echo "   Private key: $key_file"
    echo "   Renewal hook: $(certbot_hook_path)"
    ;;

# ── run ───────────────────────────────────────────────────────────────────────
run)
    instance="${1?Usage: astrbotctl run <instance_name> [args...]}"
    shift
    require_instance
    load_instance_config

    [ ! -d "$ASTRBOT_ROOT" ] && {
        echo "❌ Error: Instance directory $ASTRBOT_ROOT does not exist." >&2
        echo "   Run 'sudo astrbotctl init $instance' first." >&2
        exit 1
    }

    echo ">>> Starting AstrBot instance: $instance"

    run_astrbot run "$@"
    ;;

# ── paths ─────────────────────────────────────────────────────────────────────
paths)
    [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ] && {
        echo "Usage: astrbotctl paths <name>"
        exit 0
    }
    instance="${1:-}"
    require_instance
    load_instance_config
    print_paths
    ;;

# ── start / stop / restart / enable / disable / status ────────────────────────
start | stop | restart | enable | disable | status)
    [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ] && {
        echo "Usage: astrbotctl $cmd <name>"
        exit 0
    }
    instance="${1:-}"
    require_instance
    systemctl "$cmd" "astrbot@$instance"
    ;;

# ── retired credential compatibility tombstone ─────────────────────────────────
admin)
    echo "❌ Error: astrbotctl admin is no longer supported." >&2
    echo "   Use: sudo astrbotctl password [--username NAME] <instance>" >&2
    exit 2
    ;;

# ── password ──────────────────────────────────────────────────────────────────
password)
    username="" instance=""

    while [ "$#" -gt 0 ]; do
        case "$1" in
        --username)
            [ -z "${2:-}" ] && {
                echo "❌ Error: Missing value after --username" >&2
                exit 1
            }
            username="$2"
            shift 2
            ;;
        -h | --help)
            echo "Usage: astrbotctl password [--username NAME] <name>"
            echo "Sets the dashboard password through a hidden terminal prompt."
            exit 0
            ;;
        -*)
            echo "❌ Error: Unknown option: $1" >&2
            exit 1
            ;;
        *)
            [ -n "$instance" ] && {
                echo "❌ Error: Unexpected extra argument: $1" >&2
                exit 1
            }
            instance="$1"
            shift
            ;;
        esac
    done

    require_instance
    require_root
    load_instance_config
    [ -d "$ASTRBOT_ROOT" ] && [ -f "$ASTRBOT_ROOT/.astrbot" ] || {
        echo "❌ Error: Instance directory $ASTRBOT_ROOT is not initialized." >&2
        exit 1
    }
    if [ ! -t 0 ]; then
        echo "❌ Error: astrbotctl password requires a controlling terminal for hidden input." >&2
        echo "   Run it directly from an interactive terminal." >&2
        exit 1
    fi
    ensure_instance_env_synced || {
        echo "❌ Error: Failed to prepare Python environment for instance '$instance'." >&2
        exit 1
    }

    venv_astrbot="$(venv_dir)/bin/astrbot"
    password_args=("$venv_astrbot" password)
    [ -z "$username" ] || password_args+=(--username "$username")
    run_astrbot_env_cmd --command-cwd "$ASTRBOT_ROOT" "${password_args[@]}"
    ;;

# ── retired backup compatibility tombstones ────────────────────────────────────
export | import)
    echo "❌ Error: astrbotctl $cmd is no longer supported." >&2
    echo "   Use authenticated Dashboard backup and restore instead; restore is destructive." >&2
    exit 2
    ;;

# ── ls ────────────────────────────────────────────────────────────────────────
ls)
    echo "=== AstrBot Instances ==="
    instances=$(iter_instances)
    if [ -n "$instances" ]; then
        printf '%s\n' "$instances"
    else
        echo "(No instances found)"
    fi
    ;;

# ── clean ─────────────────────────────────────────────────────────────────────
clean)
    require_root

    echo "=== AstrBot Clean ==="
    echo ""

    # Update snapshots
    if [ -d "$CACHE_DIR/update-snapshots" ]; then
        echo "  [1] Update snapshots: $CACHE_DIR/update-snapshots ($(du -sh "$CACHE_DIR/update-snapshots" 2>/dev/null | cut -f1))"
    fi

    # Cargo cache
    if [ -d "/var/lib/astrbot/.cargo" ]; then
        echo "  [2] Cargo cache: /var/lib/astrbot/.cargo ($(du -sh /var/lib/astrbot/.cargo 2>/dev/null | cut -f1))"
    fi

    # Rustup cache
    if [ -d "/var/lib/astrbot/.rustup" ]; then
        echo "  [3] Rustup cache: /var/lib/astrbot/.rustup ($(du -sh /var/lib/astrbot/.rustup 2>/dev/null | cut -f1))"
    fi

    # Instance virtualenvs
    total_venvs=0
    if [ -d "$SYSTEM_ROOT" ]; then
        total_venvs=$(find "$SYSTEM_ROOT" -mindepth 2 -maxdepth 2 -type d -name '.venv' | wc -l)
    fi
    if [ "$total_venvs" -gt 0 ]; then
        venv_total_size=$(find "$SYSTEM_ROOT" -mindepth 2 -maxdepth 2 -type d -name '.venv' -exec du -ch {} + 2>/dev/null | tail -1 | cut -f1)
        echo "  [4] Instance venvs: $SYSTEM_ROOT/*/.venv (total: ${venv_total_size:-unknown})"
    fi

    # UV cache
    if [ -d "$CACHE_DIR/uv" ]; then
        echo "  [5] UV cache: $CACHE_DIR/uv ($(du -sh "$CACHE_DIR/uv" 2>/dev/null | cut -f1))"
    fi

    echo ""
    echo "  [a] All of the above"
    echo "  [q] Quit (no action)"
    echo ""
    printf "Select items to clean (e.g. 1 3 5): "
    read -r choices

    [ "$choices" = "q" ] && exit 0

    for choice in $choices; do
        case "$choice" in
        1)
            echo ">>> Removing update snapshots..."
            rm -rf "$CACHE_DIR/update-snapshots"
            mkdir -p "$CACHE_DIR/update-snapshots"
            ;;
        2)
            echo ">>> Removing cargo cache..."
            rm -rf /var/lib/astrbot/.cargo
            ;;
        3)
            echo ">>> Removing rustup cache..."
            rm -rf /var/lib/astrbot/.rustup
            ;;
        4)
            echo ">>> Removing idle instance venvs..."
            clean_instance_venvs
            ;;
        5)
            echo ">>> Removing UV cache..."
            rm -rf "$CACHE_DIR/uv"
            ;;
        a)
            echo ">>> Removing idle instance venvs and all caches..."
            clean_instance_venvs
            rm -rf "$CACHE_DIR/update-snapshots"
            mkdir -p "$CACHE_DIR/update-snapshots"
            rm -rf /var/lib/astrbot/.cargo
            rm -rf /var/lib/astrbot/.rustup
            rm -rf "$CACHE_DIR/uv"
            ;;
        q) exit 0 ;;
        esac
    done
    echo ""
    echo "✅ Done. Note: venvs will be rebuilt on next run."
    ;;

# ── sync ──────────────────────────────────────────────────────────────────────
sync)
    instance="" all=0

    while [ "$#" -gt 0 ]; do
        case "$1" in
        --all)
            all=1
            shift
            ;;
        -h | --help)
            cat <<'USAGE'
Usage: sudo astrbotctl sync [instance|--all]

Refresh instance virtualenvs from the packaged AstrBot code in /opt/astrbot.
Use this if /opt/astrbot has been updated but an instance still appears to run old code.

Options:
  --all      Sync all instances
  -h, --help Show this help
USAGE
            exit 0
            ;;
        -*)
            echo "❌ Error: Unknown option: $1" >&2
            exit 1
            ;;
        *)
            [ -n "$instance" ] && {
                echo "❌ Error: Unexpected extra argument: $1" >&2
                exit 1
            }
            instance="$1"
            shift
            ;;
        esac
    done

    [ "$all" -eq 0 ] || [ -z "$instance" ] || {
        echo "❌ Error: Choose an instance or --all, not both." >&2
        exit 2
    }
    require_root

    if [ "$all" -eq 1 ]; then
        instances=$(iter_instances)
        [ -z "$instances" ] && {
            echo ">>> No instances found."
            exit 0
        }
        echo ">>> Syncing all instances: $instances"
    else
        [ -z "$instance" ] && {
            echo "❌ Error: Instance name or --all required." >&2
            exit 1
        }
        instances="$instance"
        require_instance
        echo ">>> Syncing instance: $instance"
    fi

    _sync_instance() {
        local inst="$1" was_active=0
        local venv_dir_path venv_backup_path had_backup=0 sync_status rollback_ok=0
        instance="$inst"
        validate_instance_name "$instance" || return 1
        load_instance_config || return $?

        if [ ! -d "$ASTRBOT_ROOT" ] || [ -L "$ASTRBOT_ROOT" ]; then
            echo "❌ Error: Instance $inst directory is missing or symlinked." >&2
            return 1
        fi

        venv_dir_path="$(venv_dir)"
        venv_backup_path="${UPDATE_SNAPSHOT_DIR}/${inst}-venv-backup"

        if systemctl is-active --quiet "astrbot@$inst" 2>/dev/null; then
            was_active=1
            echo ">>> Stopping active service: $inst"
            systemctl stop "astrbot@$inst" || return 1
            if systemctl is-active --quiet "astrbot@$inst" 2>/dev/null; then
                echo "❌ Error: Instance '$inst' remained active; no venv changes made." >&2
                return 1
            fi
        fi

        if acquire_venv_maintenance_lock; then
            :
        else
            sync_status=$?
            return "$sync_status"
        fi
        if systemctl is-active --quiet "astrbot@$inst" 2>/dev/null; then
            release_venv_maintenance_lock
            echo "❌ Error: Instance '$inst' started concurrently; no venv changes made." >&2
            return 75
        fi

        if [ "$UPDATE_AUTO_ROLLBACK" = "1" ] && [ -d "$venv_dir_path" ]; then
            echo ">>> Backing up current venv..."
            if ! create_venv_backup "$venv_dir_path" "$venv_backup_path"; then
                release_venv_maintenance_lock
                return 1
            fi
            had_backup=1
        fi

        if ensure_instance_env_synced --force 2>&1; then
            :
        else
            sync_status=$?
            echo "⚠️  Failed to sync environment for $inst"
            if [ "$had_backup" -eq 1 ] && [ -d "$venv_backup_path" ]; then
                echo ">>> Restoring previous venv from backup..."
                if restore_venv_backup_atomically "$venv_dir_path" "$venv_backup_path" sync_failure; then
                    rollback_ok=1
                else
                    echo "⚠️  Failed to restore the previous venv for $inst" >&2
                fi
            fi
            release_venv_maintenance_lock
            if [ "$was_active" -eq 1 ] && [ "$rollback_ok" -eq 1 ]; then
                echo ">>> Restarting restored service: $inst"
                if restart_restored_instance_healthy "$inst"; then
                    cleanup_atomic_restore_after_healthy "$venv_backup_path"
                else
                    echo "⚠️  Failed to restart $inst after rollback" >&2
                    report_atomic_restore_preserved "$venv_backup_path"
                fi
            elif [ "$was_active" -eq 1 ]; then
                echo "⚠️  Keeping $inst stopped because no valid venv rollback is available." >&2
            elif [ "$rollback_ok" -eq 1 ]; then
                report_atomic_restore_preserved "$venv_backup_path"
            fi
            return "$sync_status"
        fi

        # Sync succeeded — discard backup
        rm -rf "$venv_backup_path" 2>/dev/null || true
        release_venv_maintenance_lock

        if [ "$was_active" -eq 1 ]; then
            echo ">>> Restarting service: $inst"
            if ! systemctl start "astrbot@$inst"; then
                echo "⚠️  Failed to restart $inst"
                return 1
            fi
        fi

        echo "✅ Synced instance: $inst"
        return 0
    }

    FAILED_INSTANCES=""
    failed_status=0
    for inst in $instances; do
        if _sync_instance "$inst"; then
            :
        else
            sync_status=$?
            FAILED_INSTANCES="$FAILED_INSTANCES $inst"
            [ "$failed_status" -ne 0 ] || failed_status="$sync_status"
        fi
    done

    echo ""
    if [ -n "$FAILED_INSTANCES" ]; then
        echo "=== ❌ Sync failed for some instances ==="
        echo "    Failed instances:$FAILED_INSTANCES"
        exit "$failed_status"
    else
        echo "=== ✅ Sync complete ==="
    fi
    ;;

# ── update ───────────────────────────────────────────────────────────────────
update)
    instance="" all=0 stability_secs="${UPDATE_STABILITY_SECS:-60}"

    while [ "$#" -gt 0 ]; do
        case "$1" in
        --all)
            all=1
            shift
            ;;
        --stability-secs)
            [ -n "${2:-}" ] || {
                echo "❌ Error: Missing value after --stability-secs" >&2
                exit 2
            }
            stability_secs="$2"
            shift 2
            ;;
        -h | --help)
            cat <<'USAGE'
Usage: sudo astrbotctl update [instance|--all] [options]

Sync the currently installed astrbot-git package into instance virtualenvs.
Restart instance(s) and monitor stability.

Options:
  --all                  Sync and restart all instances
  --stability-secs N     Seconds to monitor for stability (default: 60)
  -h, --help             Show this help
USAGE
            exit 0
            ;;
        -*)
            echo "❌ Error: Unknown option: $1" >&2
            exit 1
            ;;
        *)
            [ -n "$instance" ] && {
                echo "❌ Error: Unexpected extra argument: $1" >&2
                exit 1
            }
            instance="$1"
            shift
            ;;
        esac
    done

    [ "$all" -eq 0 ] || [ -z "$instance" ] || {
        echo "❌ Error: Choose an instance or --all, not both." >&2
        exit 2
    }
    [[ "$stability_secs" =~ ^[0-9]{1,6}$ ]] || {
        echo "❌ Error: --stability-secs must be an integer from 0 to 999999." >&2
        exit 2
    }
    stability_secs=$((10#$stability_secs))
    require_root

    if [ "$all" -eq 1 ]; then
        instances=$(iter_instances)
        [ -z "$instances" ] && {
            echo ">>> No instances found."
            exit 0
        }
        echo ">>> Syncing and restarting all instances: $instances"
    else
        [ -z "$instance" ] && {
            echo "❌ Error: Instance name or --all required." >&2
            exit 1
        }
        instances="$instance"
        require_instance
        echo ">>> Syncing and restarting instance: $instance"
    fi

    echo ""
    echo "[1/3] Checking installed package..."
    if [ -f "$APP_DIR/.version" ]; then
        echo ">>> Using packaged AstrBot version: $(cat "$APP_DIR/.version")"
    else
        echo "⚠️  $APP_DIR/.version not found. Sync will use the current $APP_DIR contents."
    fi

    echo ""
    echo "[2/3] Rebuilding venv and restarting instances..."
    _update_instance() {
        local inst="$1" was_active=0 update_status rollback_ok=0
        local venv_dir_path venv_backup_path had_backup=0
        instance="$inst"
        validate_instance_name "$instance" || return 1
        load_instance_config || return $?
        if [ ! -d "$ASTRBOT_ROOT" ] || [ -L "$ASTRBOT_ROOT" ]; then
            echo "❌ Error: Instance $inst directory is missing or symlinked." >&2
            return 1
        fi

        venv_dir_path="$(venv_dir)"
        venv_backup_path="${UPDATE_SNAPSHOT_DIR}/${inst}-venv-backup"

        echo ">>> Rebuilding venv for: $inst"

        if systemctl is-active --quiet "astrbot@$inst" 2>/dev/null; then
            was_active=1
            echo ">>> Stopping active service: $inst"
            systemctl stop "astrbot@$inst" || return 1
            if systemctl is-active --quiet "astrbot@$inst" 2>/dev/null; then
                echo "❌ Error: Instance '$inst' remained active; no venv changes made." >&2
                return 1
            fi
        fi
        if acquire_venv_maintenance_lock; then
            :
        else
            update_status=$?
            return "$update_status"
        fi
        if systemctl is-active --quiet "astrbot@$inst" 2>/dev/null; then
            release_venv_maintenance_lock
            echo "❌ Error: Instance '$inst' started concurrently; no venv changes made." >&2
            return 75
        fi

        if [ "$UPDATE_AUTO_ROLLBACK" = "1" ] && [ -d "$venv_dir_path" ]; then
            echo ">>> Backing up current venv..."
            if ! create_venv_backup "$venv_dir_path" "$venv_backup_path"; then
                release_venv_maintenance_lock
                return 1
            fi
            had_backup=1
        fi

        if ! rm -rf -- "$venv_dir_path"; then
            release_venv_maintenance_lock
            echo "❌ Error: Failed to remove the old venv for $inst; backup retained." >&2
            return 1
        fi

        if [ -L "$APP_DIR/astrbot/dashboard/dist" ] && [ ! -e "$APP_DIR/astrbot/dashboard/dist" ]; then
            if ! rm -f -- "$APP_DIR/astrbot/dashboard/dist" || ! mkdir -p -- "$APP_DIR/astrbot/dashboard/dist"; then
                release_venv_maintenance_lock
                echo "❌ Error: Failed to repair dashboard assets for $inst; backup retained." >&2
                return 1
            fi
        fi

        if ensure_instance_env_synced --force 2>&1; then
            :
        else
            update_status=$?
            echo "⚠️  Failed to sync environment for $inst"
            if [ "$had_backup" -eq 1 ] && restore_venv_backup_atomically "$venv_dir_path" "$venv_backup_path" update_failure; then
                rollback_ok=1
            fi
            release_venv_maintenance_lock
            if [ "$was_active" -eq 1 ] && [ "$rollback_ok" -eq 1 ]; then
                if restart_restored_instance_healthy "$inst"; then
                    cleanup_atomic_restore_after_healthy "$venv_backup_path"
                else
                    report_atomic_restore_preserved "$venv_backup_path"
                fi
            elif [ "$rollback_ok" -eq 1 ]; then
                report_atomic_restore_preserved "$venv_backup_path"
            fi
            return "$update_status"
        fi

        release_venv_maintenance_lock
        if [ "$was_active" -eq 0 ]; then
            rm -rf -- "$venv_backup_path"
            return 0
        fi

        echo ">>> Starting: $inst"
        if systemctl start "astrbot@$inst"; then
            UPDATED_ACTIVE_INSTANCES="$UPDATED_ACTIVE_INSTANCES $inst"
            return 0
        else
            update_status=$?
            echo "⚠️  Failed to start $inst"
            # Cancel Restart=always before restoring, even when start failed.
            if systemctl stop "astrbot@$inst" && acquire_venv_maintenance_lock &&
                ! systemctl is-active --quiet "astrbot@$inst" 2>/dev/null &&
                restore_venv_backup_atomically "$venv_dir_path" "$venv_backup_path" update_failure; then
                rollback_ok=1
            fi
            release_venv_maintenance_lock
            if [ "$rollback_ok" -eq 1 ] && restart_restored_instance_healthy "$inst"; then
                cleanup_atomic_restore_after_healthy "$venv_backup_path"
            else
                report_atomic_restore_preserved "$venv_backup_path"
            fi
            return "$update_status"
        fi
    }

    _rollback_after_stability_failure() {
        local inst="$1" venv_dir_path venv_backup_path
        instance="$inst"
        validate_instance_name "$instance" || return 1
        load_instance_config || return $?
        venv_dir_path="$(venv_dir)"
        venv_backup_path="${UPDATE_SNAPSHOT_DIR}/${inst}-venv-backup"
        # A failed service may have an automatic restart pending. Cancel it
        # before acquiring the maintenance lock and exchanging its environment.
        systemctl stop "astrbot@$inst" || return $?
        acquire_venv_maintenance_lock || return $?
        if systemctl is-active --quiet "astrbot@$inst" 2>/dev/null; then
            release_venv_maintenance_lock
            echo "❌ Error: Instance '$inst' is still active; rollback was not attempted." >&2
            return 75
        fi
        if ! restore_venv_backup_atomically "$venv_dir_path" "$venv_backup_path" stability_failure; then
            release_venv_maintenance_lock
            return 1
        fi
        release_venv_maintenance_lock
        if restart_restored_instance_healthy "$inst"; then
            cleanup_atomic_restore_after_healthy "$venv_backup_path"
            return 0
        fi
        report_atomic_restore_preserved "$venv_backup_path"
        return 1
    }

    _cleanup_venv_backup() {
        local inst
        for inst in "$@"; do
            rm -rf -- "${UPDATE_SNAPSHOT_DIR}/${inst}-venv-backup"
        done
    }

    FAILED_INSTANCES=""
    UPDATED_ACTIVE_INSTANCES=""
    failed_status=0
    for inst in $instances; do
        if _update_instance "$inst"; then
            :
        else
            update_status=$?
            FAILED_INSTANCES="$FAILED_INSTANCES $inst"
            [ "$failed_status" -ne 0 ] || failed_status="$update_status"
        fi
    done

    echo ""
    echo "[3/3] Monitoring stability..."
    if [ "$stability_secs" -gt 0 ] && [ -n "$UPDATED_ACTIVE_INSTANCES" ]; then
        echo ">>> Waiting ${stability_secs}s to ensure instances stay active..."
        for ((i = 1; i <= stability_secs; i++)); do
            sleep 1
            for inst in $UPDATED_ACTIVE_INSTANCES; do
                if [[ " $FAILED_INSTANCES " == *" $inst "* ]]; then
                    continue
                fi
                if ! systemctl is-active --quiet "astrbot@$inst" 2>/dev/null; then
                    echo "⚠️  Instance $inst crashed at ${i}s."
                    [ "$failed_status" -ne 0 ] || failed_status=1
                    if ! _rollback_after_stability_failure "$inst"; then
                        echo "⚠️  Rollback also failed for $inst — manual intervention needed."
                    fi
                    FAILED_INSTANCES="$FAILED_INSTANCES $inst"
                fi
            done
        done
    fi

    # A successfully monitored active instance has no remaining recovery use.
    for inst in $UPDATED_ACTIVE_INSTANCES; do
        if [[ " $FAILED_INSTANCES " != *" $inst "* ]]; then
            _cleanup_venv_backup "$inst"
        fi
    done

    echo ""
    if [ -n "$FAILED_INSTANCES" ]; then
        echo "=== ❌ Update failed for some instances ==="
        echo "    Failed instances:$FAILED_INSTANCES"
        exit "${failed_status:-1}"
    else
        echo "=== ✅ Update complete ==="
    fi
    ;;

# ── help / unknown ─────────────────────────────────────────────────────────────
-h | --help | "")
    print_help
    exit 0
    ;;
*)
    print_help
    exit 1
    ;;
esac