aboutsummarylogtreecommitdiffstats
path: root/astrbotctl
blob: 9e8591bceefd64cec8d2f6813a4900565db9a7d5 (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
#!/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_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
    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)
    backup_file="" instance=""

    while [ "$#" -gt 0 ]; do
        case "$1" in
        -f | --backup)
            [ -z "${2:-}" ] && {
                echo "❌ Error: Missing backup file after $1" >&2
                exit 1
            }
            backup_file="$2"
            shift 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}"

    [ -n "$backup_file" ] && [ ! -f "$backup_file" ] &&
        {
            echo "❌ Error: Backup file not found: $backup_file" >&2
            exit 1
        }
    [ -d "$astrbot_root" ] && {
        echo "⚠️  Instance data directory already exists: $astrbot_root" >&2
        exit 1
    }

    echo ">>> Initializing instance: $instance"

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

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

    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 bash -c 'printf "Y\nY\n" | "$1" init' bash "$venv_astrbot"
    if [ -n "$backup_file" ]; then
        run_astrbot_env_cmd "$venv_astrbot" bk import -y "$backup_file"
    fi

    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 "To start the instance:"
    echo "   systemctl start astrbot@$instance"
    ;;

# ── cp ───────────────────────────────────────────────────────────────────────
cp)
    require_root
    src="${2?Usage: astrbotctl cp <source_instance> <dest_instance>}"
    dst="${3?Usage: astrbotctl cp <source_instance> <dest_instance>}"

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

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

    echo ">>> Copying instance: $src -> $dst"
    echo "    Copying data directory..."
    cp -r "$src_root" "$dst_root"
    chown -R astrbot:astrbot "$dst_root"

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

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

    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

    conf_file="$(conf_file)"
    venv_dir="$(venv_dir)"

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

    [ ! -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"

    # Build -d arguments
    domain_args=""
    for domain in $domains; do
        domain_args="$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..."
    # shellcheck disable=SC2086
    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"
    ;;

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

    while [ "$#" -gt 0 ]; do
        case "$1" in
        -u | --username)
            [ -z "${2:-}" ] && {
                echo "❌ Error: Missing value after $1" >&2
                exit 1
            }
            username="$2"
            shift 2
            ;;
        -p | --password)
            [ -z "${2:-}" ] && {
                echo "❌ Error: Missing value after $1" >&2
                exit 1
            }
            password="$2"
            shift 2
            ;;
        -h | --help)
            echo "Usage: astrbotctl admin [-u username] [-p password] <name>"
            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
    load_instance_config
    [ ! -d "$ASTRBOT_ROOT" ] && {
        echo "❌ Error: Instance directory $ASTRBOT_ROOT does not exist." >&2
        exit 1
    }

    # conf is a top-level astrbot subcommand, not a subcommand of 'run'.
    # We bypass run_astrbot and invoke astrbot directly.
    setup_runtime_env
    cd "$ASTRBOT_ROOT" || exit
    if [ -n "$username" ]; then
        "$UV_PROJECT_ENVIRONMENT/bin/astrbot" conf set dashboard.username "$username"
    fi
    if [ -n "$password" ]; then
        "$UV_PROJECT_ENVIRONMENT/bin/astrbot" conf set dashboard.password "$password"
    fi
    if [ -z "$username" ] && [ -z "$password" ]; then
        echo "❌ Error: Must provide at least one of -u/--username or -p/--password" >&2
        exit 1
    fi
    ;;

# ── export ─────────────────────────────────────────────────────────────────────
export)
    output_dir="" sign=0 encrypt="" symmetric=0 digest="" instance=""

    while [ "$#" -gt 0 ]; do
        case "$1" in
        -o | --output)
            [ -z "${2:-}" ] && {
                echo "❌ Error: Missing output dir after $1" >&2
                exit 1
            }
            output_dir="$2"
            shift 2
            ;;
        -E | --gpg-encrypt)
            [ -z "${2:-}" ] && {
                echo "❌ Error: Missing recipient after $1" >&2
                exit 1
            }
            encrypt="$2"
            shift 2
            ;;
        -d | --digest)
            [ -z "${2:-}" ] && {
                echo "❌ Error: Missing algorithm after $1" >&2
                exit 1
            }
            digest="$2"
            shift 2
            ;;
        -S | --gpg-sign)
            sign=1
            shift
            ;;
        -C | --gpg-symmetric)
            symmetric=1
            shift
            ;;
        -h | --help)
            echo "Usage: astrbotctl export [options] <name>"
            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
    load_instance_config
    [ ! -d "$ASTRBOT_ROOT" ] && {
        echo "❌ Error: Instance directory $ASTRBOT_ROOT does not exist." >&2
        exit 1
    }

    # shellcheck disable=SC2206
    cmd_args=(bk export)
    [ -n "$output_dir" ] && cmd_args+=(-o "$output_dir")
    [ "$sign" -eq 1 ] && cmd_args+=(-S)
    [ -n "$encrypt" ] && cmd_args+=(-E "$encrypt")
    [ "$symmetric" -eq 1 ] && cmd_args+=(-C)
    [ -n "$digest" ] && cmd_args+=(-d "$digest")
    run_astrbot "${cmd_args[@]}"
    ;;

# ── import ─────────────────────────────────────────────────────────────────────
import)
    backup_file="" yes=0 instance=""

    while [ "$#" -gt 0 ]; do
        case "$1" in
        -y | --yes)
            yes=1
            shift
            ;;
        -h | --help)
            echo "Usage: astrbotctl import [-y] <name> <backup_file>"
            exit 0
            ;;
        -*)
            echo "❌ Error: Unknown option: $1" >&2
            exit 1
            ;;
        *)
            [ -z "$instance" ] && {
                instance="$backup_file"
                shift
                continue
            }
            [ -z "$backup_file" ] && {
                backup_file="$1"
                shift
                continue
            }
            echo "❌ Error: Unexpected extra argument: $1" >&2
            exit 1
            ;;
        esac
    done

    require_instance
    [ -z "$backup_file" ] && {
        echo "❌ Error: Missing backup file." >&2
        exit 1
    }
    [ ! -f "$backup_file" ] && {
        echo "❌ Error: Backup file not found: $backup_file" >&2
        exit 1
    }
    load_instance_config
    [ ! -d "$ASTRBOT_ROOT" ] && {
        echo "❌ Error: Instance directory $ASTRBOT_ROOT does not exist." >&2
        exit 1
    }

    run_astrbot bk import ${yes:+-y} "$backup_file"
    ;;

# ── 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=$(find "$SYSTEM_ROOT" -mindepth 2 -maxdepth 2 -type d -name '.venv' 2>/dev/null | wc -l)
    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 all instance venvs..."
            find "$SYSTEM_ROOT" -mindepth 2 -maxdepth 2 -type d -name '.venv' -exec rm -rf {} +
            ;;
        5)
            echo ">>> Removing UV cache..."
            rm -rf "$CACHE_DIR/uv"
            ;;
        a)
            echo ">>> Removing all caches..."
            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

    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
        instance="$inst"
        load_instance_config

        if [ ! -d "$ASTRBOT_ROOT" ]; then
            echo "⚠️  Instance $inst directory missing, skipping."
            return 0
        fi

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

        # Backup current venv before sync
        if [ "$UPDATE_AUTO_ROLLBACK" = "1" ] && [ -d "$venv_dir_path" ]; then
            echo ">>> Backing up current venv..."
            rm -rf "$venv_backup_path" 2>/dev/null || true
            mkdir -p "$(dirname "$venv_backup_path")"
            cp -a "$venv_dir_path" "$venv_backup_path"
            had_backup=1
        fi

        if systemctl is-active --quiet "astrbot@$inst" 2>/dev/null; then
            was_active=1
            echo ">>> Stopping active service: $inst"
            systemctl stop "astrbot@$inst"
        fi

        if ! ensure_instance_env_synced 2>&1; then
            echo "⚠️  Failed to sync environment for $inst"
            if [ "$had_backup" -eq 1 ]; then
                echo ">>> Restoring previous venv from backup..."
                rm -rf "$venv_dir_path" 2>/dev/null || true
                cp -a "$venv_backup_path" "$venv_dir_path"
            fi
            rm -rf "$venv_backup_path" 2>/dev/null || true
            return 1
        fi

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

        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=""
    for inst in $instances; do
        if ! _sync_instance "$inst"; then
            FAILED_INSTANCES="$FAILED_INSTANCES $inst"
        fi
    done

    echo ""
    if [ -n "$FAILED_INSTANCES" ]; then
        echo "=== ❌ Sync failed for some instances ==="
        echo "    Failed instances:$FAILED_INSTANCES"
        exit 1
    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)
            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

    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 /opt/astrbot/.version ]; then
        echo ">>> Using packaged AstrBot version: $(cat /opt/astrbot/.version)"
    else
        echo "⚠️  /opt/astrbot/.version not found. Sync will use the current /opt/astrbot contents."
    fi

    echo ""
    echo "[2/3] Rebuilding venv and restarting instances..."
    _update_instance() {
        local inst="$1"
        local venv_dir_path venv_backup_path had_backup=0
        instance="$inst"
        load_instance_config
        if [ ! -d "$ASTRBOT_ROOT" ]; then
            echo "⚠️  Instance $inst directory missing, skipping."
            return 0
        fi

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

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

        # Backup current venv before nuking it
        if [ "$UPDATE_AUTO_ROLLBACK" = "1" ] && [ -d "$venv_dir_path" ]; then
            echo ">>> Backing up current venv..."
            rm -rf "$venv_backup_path" 2>/dev/null || true
            mkdir -p "$(dirname "$venv_backup_path")"
            cp -a "$venv_dir_path" "$venv_backup_path"
            had_backup=1
        fi

        rm -rf "$venv_dir_path"

        if [ -L "/opt/astrbot/astrbot/dashboard/dist" ] && [ ! -e "/opt/astrbot/astrbot/dashboard/dist" ]; then
            rm -f "/opt/astrbot/astrbot/dashboard/dist"
            mkdir -p "/opt/astrbot/astrbot/dashboard/dist"
        fi

        if ! ensure_instance_env_synced 2>&1; then
            echo "⚠️  Failed to sync environment for $inst"
            _restore_venv_backup "$venv_dir_path" "$venv_backup_path"
            return 1
        fi

        echo ">>> Stopping: $inst"
        systemctl stop "astrbot@$inst" 2>/dev/null || true

        echo ">>> Starting: $inst"
        if ! systemctl start "astrbot@$inst"; then
            echo "⚠️  Failed to start $inst"
            _restore_venv_backup "$venv_dir_path" "$venv_backup_path"
            return 1
        fi

        # Keep backup around for stability monitoring; cleaned up after
        return 0
    }

    _restore_venv_backup() {
        local dst="$1" src="$2"
        if [ -d "$src" ]; then
            echo ">>> Restoring previous venv from backup..."
            rm -rf "$dst" 2>/dev/null || true
            cp -a "$src" "$dst"
        fi
        rm -rf "$src" 2>/dev/null || true
    }

    _cleanup_venv_backup() {
        local inst
        for inst in "$@"; do
            rm -rf "${UPDATE_SNAPSHOT_DIR}/${inst}-venv-backup" 2>/dev/null || true
        done
    }

    FAILED_INSTANCES=""
    for inst in $instances; do
        if ! _update_instance "$inst"; then
            FAILED_INSTANCES="$FAILED_INSTANCES $inst"
        fi
    done

    echo ""
    echo "[3/3] Monitoring stability..."
    if [ "$stability_secs" -gt 0 ]; then
        echo ">>> Waiting ${stability_secs}s to ensure instances stay active..."
        for i in $(seq 1 "$stability_secs"); do
            sleep 1
            for inst in $instances; do
                if echo "$FAILED_INSTANCES" | grep -qw "$inst"; then
                    continue
                fi
                if ! systemctl is-active --quiet "astrbot@$inst" 2>/dev/null; then
                    echo "⚠️  Instance $inst crashed at ${i}s."
                    # Rollback if backup exists
                    bk_path="${UPDATE_SNAPSHOT_DIR}/${inst}-venv-backup"
                    if [ "$UPDATE_AUTO_ROLLBACK" = "1" ] && [ -d "$bk_path" ]; then
                        echo ">>> Rolling back venv for $inst..."
                        vp="${SYSTEM_ROOT}/${inst}/.venv"
                        rm -rf "$vp" 2>/dev/null || true
                        cp -a "$bk_path" "$vp"
                        rm -rf "$bk_path"
                        echo ">>> Restarting $inst with previous venv..."
                        systemctl start "astrbot@$inst" 2>/dev/null || true
                        sleep 5
                        if systemctl is-active --quiet "astrbot@$inst" 2>/dev/null; then
                            echo ">>> Rollback succeeded — $inst is running on previous version."
                            continue
                        else
                            echo "⚠️  Rollback also failed for $inst — manual intervention needed."
                        fi
                    fi
                    FAILED_INSTANCES="$FAILED_INSTANCES $inst"
                fi
            done
            if [ -n "$FAILED_INSTANCES" ]; then
                break
            fi
        done
    fi

    # Clean up remaining backups for successful instances
    _cleanup_venv_backup $instances

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

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