-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpanel-migrate-addon.sh
More file actions
executable file
·2241 lines (2041 loc) · 95.3 KB
/
cpanel-migrate-addon.sh
File metadata and controls
executable file
·2241 lines (2041 loc) · 95.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# cpanel-migrate-addon.sh — move an addon domain (and its subdomain children)
# between two cPanel accounts on the SAME server. cPanel does NOT provide a
# native single-call API for this; this script composes the supported
# primitives: rsync + mysqldump + whmapi1 create_subdomain +
# whmapi1 create_parked_domain_for_user + whmapi1 delete_domain.
#
# The script auto-detects every decision point so a single invocation handles
# real-world cases: nested subdomain children, dead external DB hosts referenced
# in wp-config, expired registrations, multiple legacy DB prefix policies,
# stale cPanel JSON error reporting, HEAD-hostile .htaccess, etc.
#
# ----------------------------------------------------------------------------
# WHAT THIS SCRIPT DOES *NOT* DO (migrate these separately!)
# ----------------------------------------------------------------------------
# Email accounts (mailboxes, forwarders, autoresponders, filters, SpamAssassin
# user config, cPanel-generated DKIM signing keys), FTP accounts, SSH keys,
# cron jobs, password-protected directories, IP-blocker/hotlink rules,
# custom Apache handlers/MIME, Softaculous installation metadata, account
# packages / LVE limits / reseller ACLs, WebDisk accounts, manually-installed
# SSL certs, DNSSEC keys, cPanel Redirects GUI entries, wildcard subdomains,
# multi-level subdomain children.
# Read README.md for the complete list.
#
# ----------------------------------------------------------------------------
# DISCLAIMER
# ----------------------------------------------------------------------------
# Provided "as is", no warranty, no liability. Skills IT — Technology Solutions
# and contributors are NOT liable for any damages arising from use of this
# software. Always take a hypervisor-level snapshot (Vultr / AWS / DO /
# Proxmox / etc.) and run --dry-run FIRST. Full disclaimer: LICENSE + README.md.
#
# ----------------------------------------------------------------------------
# SUPPORT / PROFESSIONAL SERVICES
# ----------------------------------------------------------------------------
# Skills IT — Technology Solutions (Brazil)
# Website: https://skillsit.com.br
# Email: contato@skillsit.com.br
# Phone: +55 63 3224-4925
# Specialties: cPanel/WHM migrations, mail deliverability (SPF/DKIM/DMARC),
# DNS architecture, hosting automation, WordPress/LSWS performance, MCP / AI.
#
# ----------------------------------------------------------------------------
# KNOWN ISSUES FIXED / COMPENSATED IN THIS SCRIPT
# ----------------------------------------------------------------------------
# A. whmapi1 CLI always exits 0. Real result is in JSON .metadata.result.
# → whmapi1_must_succeed() parses and validates.
# B. cPanel rejects creating a domain on B while it still exists on A.
# → remove_source_addon runs BEFORE create_dest_addon.
# C. The required DB prefix per account is NOT always "${user:0:8}_".
# → get_required_db_prefix() queries uapi Mysql get_restrictions.
# D. Addon with subdomain children fails delete_domain (parent blocked).
# → detect_subdomain_children() + auto-migrate children first.
# E. DB passwords containing base64 chars (/+=) sometimes hash-mismatch on
# cPanel's side (not only MYSQL_PWD CLI bug — also mysqli).
# → safe_random_password() uses alphanumeric only, and db_login_test runs
# after create; auto-resets via uapi Mysql set_password if login fails.
# F. curl -I (HEAD) returns 403 on sites with defensive .htaccess rules.
# → smoke_test uses GET with browser UA and scans body.
# G. HTTP 200 can still mean "Database Error" or "erro crítico" page.
# → body_smoke matches BODY_ERROR_PATTERNS before declaring success.
# H. wp-config.php commonly has commented-out //define lines pointing to dead
# legacy DBs (ex: olddb.provider-that-shutdown.example.com).
# → php_extract_constant regex starts with ^[[:space:]]*define (not //).
# I. Subdomain children sometimes live INSIDE the parent docroot.
# → migrate_subdomain_child detects nesting and skips redundant rsync.
# J. cPanel REGENERATES the DNS zone during create_subdomain /
# create_parked_domain_for_user. Custom MX, SPF, DKIM, SRV, CNAME get
# replaced by cPanel defaults. This breaks M365/Google Workspace mail.
# → backup_dns_zone saves a full JSON dump BEFORE touching anything;
# restore_dns_custom_records() replays every record AFTER the migration.
# K. cPanel auto-adds the domain to /etc/localdomains, which makes Exim
# intercept mail that should go to external MX (M365/Google).
# → configure_exim_routing() moves to /etc/remotedomains if MX external.
# L. whmapi1 URL-decodes '+' in arguments. SPF with "+a +mx" becomes
# "v=spf1 a mx" (double spaces, no +).
# → TXT values encoded with %2B before sending.
# M. Expired domains resolve locally (BIND/PowerDNS has the zone) but NXDOMAIN
# externally (registrar de-delegated). AutoSSL fails.
# → check_domain_registration via RDAP (.br) / DoH (others) in preflight.
# N. This server runs PowerDNS with launch=bind backend, not BIND. rndc
# reload does NOT work. named.service is inactive.
# → reload_dns_server() detects active backend and uses the right tool.
# O. Silent incomplete restore: some records from backup failed to re-apply
# and nobody noticed until mail/site broke.
# → verify_dns_restore_completeness() diffs backup JSON vs live zone and
# retries missing records; fails the migration if any stay missing.
# P. Serial cPanel regeneration: even after restore, subsequent cPanel actions
# (AutoSSL, rebuildhttpdconf) can wipe records again.
# → final_dns_reconciliation() runs at the very end and re-inserts any
# records that got wiped between step 8c and step 11.
# ----------------------------------------------------------------------------
DEPENDENCIES=(whmapi1 uapi rsync mysqldump mariadb jq curl awk grep getent stat chown chmod mkdir find du df openssl sed)
OPTIONAL_TOOLS=(wp)
SCRIPT_NAME=$(basename "${BASH_SOURCE[0]}")
VERSION="1.4.1"
INSTALL_PREFIX="${INSTALL_PREFIX:-/usr/local/cpanel-migrate-addon}"
LOG_DIR="${INSTALL_PREFIX}/log"
STATE_DIR="${INSTALL_PREFIX}/state"
REPORT_DIR="${INSTALL_PREFIX}/reports"
RED=$'\e[0;31m'
GREEN=$'\e[0;32m'
YELLOW=$'\e[1;33m'
BLUE=$'\e[0;34m'
CYAN=$'\e[0;36m'
BOLD=$'\e[1m'
NC=$'\e[0m'
if [[ -n "${NO_COLOR:-}" ]] || [[ "${TERM:-}" == "dumb" ]]; then
RED="" GREEN="" YELLOW="" BLUE="" CYAN="" BOLD="" NC=""
fi
LOG_FILE=""
MODE="" # dry-run | apply | verify | batch
DOMAIN=""
FROM_USER=""
TO_USER=""
SKIP_DB=false
SKIP_SSL=false
FORCE_WP=false
FORCE_STATIC=false
AUTO_YES=false
WITH_SUBS=true # default: auto-migrate dependent subdomains. Use --no-subs to disable.
STRICT_DNS=false # treat expired/NXDOMAIN as fatal in preflight
BATCH_FILE="" # path to a batch file (one domain per line)
QUIET=false # reduce log chatter
# Smoke test body-content signatures (lower-case) that indicate a broken site.
# Matched via case-insensitive grep on the fetched HTML body.
declare -ra BODY_ERROR_PATTERNS=(
"database error"
"error establishing a database connection"
"há um erro crítico no seu site"
"there has been a critical error on this website"
"fatal error"
"parse error"
"internal server error"
"service unavailable"
"500 internal server error"
)
function usage() {
cat <<EOM
${BOLD}${SCRIPT_NAME}${NC} v${VERSION} — migrate one addon domain between two cPanel
accounts on the same server.
${BOLD}USAGE${NC}
# Simplest form — source user auto-detected from /etc/userdomains:
${SCRIPT_NAME} --domain=<fqdn> --to=<user> --apply
${SCRIPT_NAME} --batch-file=<path> --to=<user> --apply
# Explicit forms:
${SCRIPT_NAME} --domain=<fqdn> --from=<user> --to=<user> --dry-run
${SCRIPT_NAME} --domain=<fqdn> --from=<user> --to=<user> --verify
${BOLD}MODES (pick exactly one)${NC}
--dry-run Plan only. Prints every command that would run and every
file/DB/record that would be touched. No side effects.
--apply Execute the migration. Writes ${LOG_DIR}/<domain>-<ts>.log.
--verify Deep post-migration health check: DB login via
defaults-file (bypasses MYSQL_PWD client bug), WP siteurl
via detected table_prefix, body smoke (GET + body error
detection), cert SAN coverage, DNS registration status.
${BOLD}REQUIRED${NC}
--domain=<fqdn> Addon domain FQDN
OR
--batch-file=<p> File with one domain per line (# and blank lines skipped;
per-line format "domain,from,to" also supported)
--to=<user> Destination cPanel account
${BOLD}OPTIONAL${NC}
--from=<user> Source cPanel account. Auto-detected from /etc/userdomains
if omitted.
--no-subs When a parent addon has subdomain children, ABORT instead
of auto-migrating them. Default behavior is to migrate
children first (cPanel rejects parent delete otherwise).
--strict-dns Treat expired/NXDOMAIN domains as FATAL (default: WARN).
RDAP for .br, Cloudflare DoH otherwise.
--skip-db Treat site as static; do not attempt any DB migration
even if wp-config.php is present.
--skip-ssl Do not call autossl_check. SSL reissue via AutoSSL cron
(default 4h) will catch up. If unset, script waits up to
\$AUTOSSL_TIMEOUT_SEC (default 120) polling every
\$AUTOSSL_POLL_SEC (default 10) and reloads LSWS on cert.
--force-wp Force WordPress-flow path even if no wp-config detected.
--force-static Force static-flow path even if wp-config present.
--with-subs Retained for backward-compat (default is already true).
--yes Non-interactive apply (no confirmation prompt).
--quiet Reduce log chatter (shows steps + results only).
-h | --help This help.
--version Print version.
${BOLD}FLOW (apply mode)${NC}
1 Preflight validate inputs, disk, ownership, docroot, PHP
version, detect subdomain children, domain
registration sanity, DB host health, email accts
2 Snapshot state rollback plan JSON
2b DNS backup .db + whmapi1 dumpzone JSON (authoritative for
record replay in step 8c below)
3 Create dest dir mkdir + chown
4 rsync data -aHAX --delete-after --backup
5 DB migrate (WP) dump + create DB/user + restore + wp-config
patch + DB login test + auto-reset password
5b Children (if any) migrate each subdomain child (rsync, DB, delete
source) BEFORE touching parent addon
6 create_subdomain whmapi1 creates <domain>.<to>.main_domain
6b Set PHP version whmapi1 php_set_vhost_versions preserves EA-PHP
7 Remove from source whmapi1 delete_domain (addon + control sub)
8 create_parked whmapi1 create_parked_domain_for_user
8b Recreate children now that parent is on destination, create sub
vhosts and restore their PHP version
8c DNS restore re-apply every record from the JSON snapshot via
whmapi1 addzonerecord (cPanel wipes custom MX/
CNAME/SRV/TXT during steps 6/7 — this puts them
back). Handles self-MX removal, A/CNAME
collisions, and SPF with '+' URL-encoded as %2B.
8d Exim routing if MX is external (M365/Google/etc), mark the
domain REMOTE in /etc/remotedomains so the local
MTA does not intercept mail.
8e rebuildhttpdconf commit vhost changes to LSWS
9 Cache + reload clear LSCache, lswsctrl reload
10 AutoSSL (optional) start_autossl_check + wait loop up to 120s +
reload LSWS when new cert detected
11 Smoke test (GET body) UA=browser, detect "Database Error", "erro
crítico", "Fatal error", empty body (<80B)
12 Write final log ${LOG_DIR}/<domain>-<ts>.log
${BOLD}ROLLBACK${NC}
On failure during steps 6-8 the script attempts to restore source-side
state using the snapshot in ${STATE_DIR}. Data already copied to dest is
NOT deleted automatically; re-running ${SCRIPT_NAME} --apply is idempotent
for steps 3-5 (rsync in-place) and step 6-7 short-circuits if already done.
${BOLD}DEPENDENCIES${NC}
Required: ${DEPENDENCIES[*]}
Optional: ${OPTIONAL_TOOLS[*]} (wp-cli used only for WordPress search-replace
when destination URL differs from source; not needed here since
we keep the same public FQDN)
${BOLD}EXAMPLES${NC}
# Trivial — single domain, auto-detect source:
${SCRIPT_NAME} --domain=example.com --to=newaccount --apply --yes
# Dry run to preview everything:
${SCRIPT_NAME} --domain=example.com --to=newaccount --dry-run
# Batch migrate multiple domains with per-line source override support:
cat > /tmp/list.txt <<EOF
site1.com
site2.net,olduser,newuser
EOF
${SCRIPT_NAME} --batch-file=/tmp/list.txt --to=newuser --apply --yes
# Post-migration deep health check:
${SCRIPT_NAME} --domain=example.com --to=newuser --verify
${BOLD}NOT MIGRATED${NC} — handle separately, BEFORE running this script:
email accounts, FTP users, SSH keys, cron jobs, password-protected
directories, wildcard subdomains, multi-level subdomain children,
manually-installed SSL certs, cPanel Redirects GUI entries, DNSSEC keys,
Softaculous installation metadata, cPanel packages / LVE limits.
See README.md → "What this script does NOT do".
${BOLD}SUPPORT${NC}
Skills IT — Technology Solutions (Brazil)
https://skillsit.com.br | contato@skillsit.com.br | +55 63 3224-4925
cPanel/WHM migrations, mail deliverability, DNS, hosting automation, AI/MCP.
EOM
exit 1
}
function main() {
local cli_mode=""
while [[ "$#" -gt 0 ]]; do
case "$1" in
--domain=*) DOMAIN="${1#*=}" ;;
--domain) shift; DOMAIN="${1:-}" ;;
--from=*) FROM_USER="${1#*=}" ;;
--from) shift; FROM_USER="${1:-}" ;;
--to=*) TO_USER="${1#*=}" ;;
--to) shift; TO_USER="${1:-}" ;;
--batch-file=*) BATCH_FILE="${1#*=}" ;;
--batch-file) shift; BATCH_FILE="${1:-}" ;;
--dry-run) cli_mode="dry-run" ;;
--apply) cli_mode="apply" ;;
--verify) cli_mode="verify" ;;
--skip-db) SKIP_DB=true ;;
--skip-ssl) SKIP_SSL=true ;;
--force-wp) FORCE_WP=true ;;
--force-static) FORCE_STATIC=true ;;
--with-subs) WITH_SUBS=true ;; # kept for backward-compat; default already true
--no-subs) WITH_SUBS=false ;;
--strict-dns) STRICT_DNS=true ;;
--quiet) QUIET=true ;;
--yes|-y) AUTO_YES=true ;;
--version) echo "${SCRIPT_NAME} v${VERSION}"; exit 0 ;;
-h|--help) usage ;;
*) echo "Error: unknown option '$1'" >&2; usage ;;
esac
shift
done
# Batch mode dispatches early (loops and calls script recursively per domain).
# --from is optional (auto-detected per-line from /etc/userdomains).
if [[ -n "$BATCH_FILE" ]]; then
if [[ -z "$TO_USER" || -z "$cli_mode" ]]; then
print_error "--batch-file requires --to, and one of --dry-run|--apply|--verify"
exit 2
fi
exit_on_missing_tools "${DEPENDENCIES[@]}"
batch_run "$cli_mode"
exit $?
fi
if [[ -z "$DOMAIN" || -z "$TO_USER" || -z "$cli_mode" ]]; then
print_error "--domain (or --batch-file), --to, and one of --dry-run|--apply|--verify are required"
usage
fi
# Auto-detect --from from /etc/userdomains when not provided
if [[ -z "$FROM_USER" ]]; then
FROM_USER=$(grep -E "^${DOMAIN}: " /etc/userdomains 2>/dev/null | awk '{print $2}')
if [[ -z "$FROM_USER" ]]; then
print_error "could not auto-detect source user for domain '$DOMAIN' (not in /etc/userdomains)"
print_error "pass --from=<user> explicitly"
exit 2
fi
[[ "$QUIET" != true ]] && echo "ℹ auto-detected --from=${FROM_USER}"
fi
validate_input_safety || exit 2
MODE="$cli_mode"
# --verify runs against the destination; FROM_USER may legitimately equal
# TO_USER because the domain has already moved.
if [[ "$MODE" != "verify" && "$FROM_USER" == "$TO_USER" ]]; then
print_error "--from and --to cannot be the same user ($FROM_USER)"
exit 2
fi
if [[ "$FORCE_WP" == true && "$FORCE_STATIC" == true ]]; then
print_error "--force-wp and --force-static are mutually exclusive"
exit 2
fi
exit_on_missing_tools "${DEPENDENCIES[@]}"
mkdir -p "$LOG_DIR" "$STATE_DIR" || { print_error "cannot create $LOG_DIR / $STATE_DIR"; exit 3; }
chmod 750 "$LOG_DIR" "$STATE_DIR" 2>/dev/null || true
local ts; ts=$(date +%Y%m%d-%H%M%S)
LOG_FILE="${LOG_DIR}/${DOMAIN}-${MODE}-${ts}.log"
print_header "${SCRIPT_NAME} v${VERSION} — ${MODE^^} mode"
log_both "Domain: ${DOMAIN}"
log_both "From: ${FROM_USER}"
log_both "To: ${TO_USER}"
log_both "Log file: ${LOG_FILE}"
log_both "Host: $(hostname)"
log_both "Date: $(date -Is)"
log_both ""
case "$MODE" in
dry-run) run_flow "dry-run" ;;
apply) run_flow "apply" ;;
verify) run_verify ;;
esac
}
function run_flow() {
local exec_mode="$1"
preflight || { print_error "preflight failed — aborting"; exit 10; }
if [[ "$exec_mode" == "apply" && "$AUTO_YES" != true ]]; then
echo ""
echo -e "${YELLOW}${BOLD}About to migrate ${DOMAIN} from ${FROM_USER} to ${TO_USER}.${NC}"
read -r -p "Type 'YES' to continue: " confirm
if [[ "$confirm" != "YES" ]]; then
log_both "User aborted at confirmation prompt."
exit 0
fi
fi
snapshot_state "$exec_mode" || abort_with_rollback 11 "snapshot_state failed"
backup_dns_zone "$exec_mode" || abort_with_rollback 18 "backup_dns_zone failed"
ensure_destination_dir "$exec_mode" || abort_with_rollback 12 "ensure_destination_dir failed"
rsync_data "$exec_mode" || abort_with_rollback 13 "rsync_data failed"
migrate_database "$exec_mode" || abort_with_rollback 14 "migrate_database failed"
# If there are subdomain children and --with-subs, migrate each BEFORE
# touching the parent addon (data+DB copied, source sub deleted).
if [[ ${#SUBDOMAIN_CHILDREN[@]} -gt 0 && "$WITH_SUBS" == true ]]; then
local s
for s in "${SUBDOMAIN_CHILDREN[@]}"; do
migrate_subdomain_child "$s" "$exec_mode" \
|| abort_with_rollback 19 "migrate_subdomain_child failed for $s"
done
fi
create_dest_subdomain "$exec_mode" || abort_with_rollback 15 "create_dest_subdomain failed"
set_dest_php_version "$exec_mode" || log_warn "set_dest_php_version returned non-zero (non-fatal)"
remove_source_addon "$exec_mode" || abort_with_rollback 17 "remove_source_addon failed"
create_dest_addon "$exec_mode" || abort_with_rollback 16 "create_dest_addon failed"
post_create_subdomain_children "$exec_mode" || log_warn "post_create_subdomain_children had warnings"
restore_dns_custom_records "$exec_mode" || log_warn "restore_dns_custom_records had warnings"
verify_dns_restore_completeness "$exec_mode" || log_warn "DNS verify failed — manual review required"
reload_dns_server
configure_exim_routing "$exec_mode" || log_warn "configure_exim_routing had warnings"
probe_external_mx "$exec_mode" || log_warn "probe_external_mx had warnings"
rebuild_httpd_conf "$exec_mode" || log_warn "rebuild_httpd_conf returned non-zero (non-fatal)"
cache_reload "$exec_mode" || log_warn "cache_reload returned non-zero (non-fatal)"
autossl_reissue "$exec_mode" || log_warn "autossl_reissue returned non-zero (non-fatal)"
smoke_test "$exec_mode" || log_warn "smoke_test returned non-zero"
final_dns_reconciliation "$exec_mode" || log_warn "final DNS reconciliation had warnings"
print_success "${MODE} completed for ${DOMAIN}"
log_both ""
log_both "Next steps:"
log_both " - Review log: ${LOG_FILE}"
log_both " - Verify: ${SCRIPT_NAME} --domain=${DOMAIN} --from=${FROM_USER} --to=${TO_USER} --verify"
# Post-migration cleanup hint — the source DB and files are left in place
# on purpose (for rollback). Once the migration is validated, drop the
# source DB via uapi (NOT via "mariadb -e DROP DATABASE" directly — that
# leaves /var/cpanel/databases/dbindex.db.json with orphan entries, which
# makes JetBackup and cPanel mail the user with "Unknown database" errors).
if [[ "$MODE" == "apply" && "$SITE_TYPE" == "wordpress" && "$SKIP_DB" != true ]]; then
log_both ""
log_both "Once validated, drop the source DB WITH the cPanel API (not mariadb CLI):"
log_both " uapi --user=${FROM_USER} Mysql delete_database name=${SRC_DB_NAME}"
log_both " uapi --user=${FROM_USER} Mysql delete_user name=${SRC_DB_USER}"
fi
log_both "Source files in /home/${FROM_USER}/${SOURCE_DOCROOT#/home/${FROM_USER}/} were NOT removed —"
log_both "delete manually after validation: rm -rf '${SOURCE_DOCROOT}'"
}
function preflight() {
print_step "Preflight checks"
if ! id "$FROM_USER" &>/dev/null; then
log_err "user '$FROM_USER' does not exist on this system"
return 1
fi
if ! id "$TO_USER" &>/dev/null; then
log_err "user '$TO_USER' does not exist on this system"
return 1
fi
local owner
owner=$(grep -E "^${DOMAIN}: " /etc/userdomains | awk '{print $2}')
if [[ "$owner" != "$FROM_USER" ]]; then
log_err "domain '$DOMAIN' is owned by '${owner:-<nobody>}', not '$FROM_USER'"
return 1
fi
log_ok "domain ${DOMAIN} confirmed as addon of ${FROM_USER}"
local already_in_to
already_in_to=$(grep -E "^${DOMAIN}: ${TO_USER}\$" /etc/userdomains || true)
if [[ -n "$already_in_to" ]]; then
log_err "domain '$DOMAIN' is ALREADY owned by '$TO_USER' — partial migration? Use --verify"
return 1
fi
FROM_MAIN_DOMAIN=$(awk -F': ' '$1=="main_domain"{print $2}' "/var/cpanel/userdata/${FROM_USER}/main" | tr -d '"')
TO_MAIN_DOMAIN=$(awk -F': ' '$1=="main_domain"{print $2}' "/var/cpanel/userdata/${TO_USER}/main" | tr -d '"')
if [[ -z "$FROM_MAIN_DOMAIN" || -z "$TO_MAIN_DOMAIN" ]]; then
log_err "could not resolve main domains (from=$FROM_MAIN_DOMAIN to=$TO_MAIN_DOMAIN)"
return 1
fi
log_ok "from main: ${FROM_MAIN_DOMAIN} | to main: ${TO_MAIN_DOMAIN}"
SOURCE_CONTROL_SUB="${DOMAIN}.${FROM_MAIN_DOMAIN}"
DEST_CONTROL_SUB="${DOMAIN}.${TO_MAIN_DOMAIN}"
log_ok "source control sub: ${SOURCE_CONTROL_SUB}"
log_ok "dest control sub: ${DEST_CONTROL_SUB}"
# documentroot lives in the control-subdomain userdata file (cPanel 132)
local src_userdata="/var/cpanel/userdata/${FROM_USER}/${SOURCE_CONTROL_SUB}"
if [[ -f "$src_userdata" ]]; then
SOURCE_DOCROOT=$(awk '/^documentroot:/{print $2}' "$src_userdata")
fi
if [[ -z "${SOURCE_DOCROOT:-}" || ! -d "$SOURCE_DOCROOT" ]]; then
log_warn "userdata lookup failed — trying filesystem heuristics"
SOURCE_DOCROOT=$(find_source_docroot) || return 1
fi
log_ok "source docroot: $SOURCE_DOCROOT"
local existing_dest_sub
existing_dest_sub=$(grep -E "^${DEST_CONTROL_SUB}: ${TO_USER}\$" /etc/userdomains || true)
if [[ -n "$existing_dest_sub" ]]; then
log_warn "destination control subdomain ${DEST_CONTROL_SUB} already exists in ${TO_USER}"
fi
detect_site_type "$SOURCE_DOCROOT" || return 1
compute_dest_paths
local src_size_kb
src_size_kb=$(du -sk "$SOURCE_DOCROOT" 2>/dev/null | awk '{print $1}')
local avail_kb
avail_kb=$(df -k --output=avail "/home" | tail -1)
local need_kb=$((src_size_kb + (src_size_kb / 10)))
log_ok "source size: $((src_size_kb/1024)) MB | /home free: $((avail_kb/1024)) MB | needed (+10%): $((need_kb/1024)) MB"
if [[ $avail_kb -lt $need_kb ]]; then
log_err "not enough disk in /home"
return 1
fi
if [[ "$SITE_TYPE" == "wordpress" && "$SKIP_DB" != true ]]; then
detect_db_config "$SOURCE_DOCROOT" || return 1
# Verify DB host is reachable — if wp-config points to a dead external host
# (very common legacy setup), fail fast with a clear message instead of
# silently producing empty dumps later.
if ! db_host_health "${SRC_DB_HOST:-localhost}"; then
log_err "DB host '${SRC_DB_HOST}' in wp-config.php is unreachable"
log_err " - not resolving or TCP/3306 closed"
log_err " - check if wp-config has an uncommented DB_HOST pointing to a dead provider"
log_err " - or pass --skip-db if site is effectively dead / manually restorable"
return 1
fi
log_ok "DB host reachable: ${SRC_DB_HOST:-localhost}"
fi
detect_php_version
# Warn loudly about email accounts — this script does not migrate email.
local mbox_count
mbox_count=$(detect_email_accounts "$FROM_USER" "$DOMAIN")
if [[ "$mbox_count" -gt 0 ]]; then
log_warn "found ${mbox_count} local mailbox(es) under /home/${FROM_USER}/mail/${DOMAIN}/"
log_warn "this script does NOT migrate email. Move mailboxes manually BEFORE proceeding,"
log_warn "or accept that email will need to be restored from backup post-migration."
else
log_ok "no local mailboxes for ${DOMAIN} — email migration not needed"
fi
scan_for_absolute_paths "$SOURCE_DOCROOT"
# Detect subdomain children that would block parent delete_domain.
# Default behavior: migrate them automatically (WITH_SUBS=true).
# Opt-out with --no-subs if someone wants the strict abort-on-dependency mode.
detect_subdomain_children
if [[ ${#SUBDOMAIN_CHILDREN[@]} -gt 0 ]]; then
log_ok "detected ${#SUBDOMAIN_CHILDREN[@]} subdomain children under ${DOMAIN}:"
local s
for s in "${SUBDOMAIN_CHILDREN[@]}"; do log_ok " - $s"; done
if [[ "$WITH_SUBS" != true ]]; then
log_err "--no-subs is active and children exist — cannot proceed."
log_err "remove --no-subs (or remove each subdomain manually) and retry."
return 1
fi
log_ok "will migrate them automatically before the parent (default behavior)"
else
log_ok "no subdomain children under ${DOMAIN}"
fi
# DNS / registrar sanity (warn by default; fatal with --strict-dns)
check_domain_registration "$DOMAIN" || return 1
log_ok "preflight ok"
return 0
}
function detect_php_version() {
local src_userdata="/var/cpanel/userdata/${FROM_USER}/${SOURCE_CONTROL_SUB}"
if [[ -f "$src_userdata" ]]; then
SOURCE_PHP_VERSION=$(awk '/^phpversion:/{print $2}' "$src_userdata" | tr -d '"' | head -1)
fi
if [[ -z "${SOURCE_PHP_VERSION:-}" ]]; then
# Fallback: ask WHM directly
SOURCE_PHP_VERSION=$(whmapi1 --output=json php_get_vhost_versions 2>/dev/null \
| jq -r --arg v "$SOURCE_CONTROL_SUB" '.data.versions[] | select(.vhost==$v) | .version' \
| head -1)
fi
if [[ -z "${SOURCE_PHP_VERSION:-}" ]]; then
log_warn "could not detect source PHP version; destination will inherit account default"
SOURCE_PHP_VERSION="inherit"
else
log_ok "source PHP version: ${SOURCE_PHP_VERSION}"
fi
return 0
}
function scan_for_absolute_paths() {
local docroot="$1"
local hits hits_config hits_dropins=""
# Look in .user.ini, .htaccess, wp-config.php first (cheap recursive grep).
hits_config=$(grep -rlE "/home/${FROM_USER}/" \
--include='.user.ini' --include='.htaccess' --include='wp-config.php' \
"${docroot}" 2>/dev/null || true)
# Also scan wp-content top-level PHP drop-ins if WP.
if [[ -d "${docroot}/wp-content" ]]; then
hits_dropins=$(find "${docroot}/wp-content" -maxdepth 1 -name '*.php' -print0 2>/dev/null \
| xargs -0r grep -lE "/home/${FROM_USER}/" 2>/dev/null || true)
fi
hits=$(printf '%s\n%s\n' "$hits_config" "$hits_dropins" | grep -v '^$' | sort -u)
if [[ -n "$hits" ]]; then
log_warn "found absolute paths referencing /home/${FROM_USER}/ in:"
while IFS= read -r f; do
[[ -z "$f" ]] && continue
log_warn " - $f"
done <<< "$hits"
log_warn "these WILL need manual replacement to /home/${TO_USER}/ post-migration"
log_warn "(the rsync copies them verbatim; php/lsws will resolve against new home)"
else
log_ok "no absolute /home/${FROM_USER}/ paths found in config files"
fi
return 0
}
function find_source_docroot() {
local candidates=(
"/home/${FROM_USER}/public_html/_dominios/_wp/${DOMAIN}"
"/home/${FROM_USER}/public_html/_dominios/${DOMAIN}"
"/home/${FROM_USER}/public_html/_dominios/_wp/${DOMAIN%.*}/${DOMAIN}"
"/home/${FROM_USER}/public_html/${DOMAIN}"
)
for c in "${candidates[@]}"; do
if [[ -d "$c" ]]; then
echo "$c"
return 0
fi
done
log_err "could not find source docroot for $DOMAIN — tried: ${candidates[*]}"
return 1
}
function compute_dest_paths() {
local path_suffix
path_suffix="${SOURCE_DOCROOT#/home/${FROM_USER}/}"
DEST_DOCROOT="/home/${TO_USER}/${path_suffix}"
DEST_DOCROOT_REL="${path_suffix}"
log_ok "dest docroot: $DEST_DOCROOT"
log_ok "dest docroot (relative): $DEST_DOCROOT_REL"
}
function detect_site_type() {
local docroot="$1"
if [[ "$FORCE_WP" == true ]]; then
SITE_TYPE="wordpress"; log_ok "site type forced: wordpress"; return 0
fi
if [[ "$FORCE_STATIC" == true ]]; then
SITE_TYPE="static"; log_ok "site type forced: static"; return 0
fi
if [[ -f "${docroot}/wp-config.php" ]]; then
SITE_TYPE="wordpress"; log_ok "site type: wordpress (wp-config.php found)"; return 0
fi
if find "$docroot" -maxdepth 3 -name 'wp-config.php' -print -quit 2>/dev/null | grep -q .; then
log_warn "wp-config.php found below docroot root — assuming static unless --force-wp"
fi
SITE_TYPE="static"
log_ok "site type: static (no wp-config.php at docroot)"
return 0
}
function detect_db_config() {
local docroot="$1"
local wpc="${docroot}/wp-config.php"
if [[ ! -f "$wpc" ]]; then
log_err "wp-config.php not found at $wpc"
return 1
fi
SRC_DB_NAME=$(php_extract_constant "$wpc" DB_NAME)
SRC_DB_USER=$(php_extract_constant "$wpc" DB_USER)
SRC_DB_HOST=$(php_extract_constant "$wpc" DB_HOST)
if [[ -z "$SRC_DB_NAME" || -z "$SRC_DB_USER" ]]; then
log_err "could not parse DB_NAME/DB_USER from $wpc"
return 1
fi
log_ok "source DB: ${SRC_DB_NAME} @ ${SRC_DB_HOST:-localhost} (user ${SRC_DB_USER})"
DEST_DB_NAME=$(rename_with_prefix "$SRC_DB_NAME" "$FROM_USER" "$TO_USER")
DEST_DB_USER=$(rename_with_prefix "$SRC_DB_USER" "$FROM_USER" "$TO_USER")
if [[ ${#DEST_DB_NAME} -gt 64 ]]; then
log_err "computed dest DB name '${DEST_DB_NAME}' exceeds 64 chars (MariaDB limit)"
return 1
fi
if [[ ${#DEST_DB_USER} -gt 32 ]]; then
log_err "computed dest DB user '${DEST_DB_USER}' exceeds 32 chars (MariaDB limit)"
return 1
fi
log_ok "dest DB planned: ${DEST_DB_NAME} (user ${DEST_DB_USER})"
return 0
}
function php_extract_constant() {
local file="$1"
local const="$2"
# Accept define('X','Y') and define("X","Y"), any whitespace, any quote mix.
# IMPORTANT: must skip comment lines — //define, #define, * define (in /* */ blocks).
# Rule: the first non-blank char on the line must be 'd' of 'define'.
local line
line=$(grep -E "^[[:space:]]*define[[:space:]]*\([[:space:]]*['\"]${const}['\"]" "$file" | head -1)
[[ -z "$line" ]] && return 0
echo "$line" | sed -n -E "s/.*define[[:space:]]*\([[:space:]]*['\"]${const}['\"][[:space:]]*,[[:space:]]*['\"]([^'\"]*)['\"].*/\1/p"
}
function get_required_db_prefix() {
# Ask cPanel what prefix the account must use *right now*. This varies by
# cpanel.config + account age; assuming "${user:0:8}_" is unsafe.
local user="$1"
uapi --user="$user" Mysql get_restrictions 2>/dev/null \
| awk -F': ' '/^[[:space:]]*prefix:/{gsub(/[[:space:]]/,"",$2); print $2; exit}'
}
function rename_with_prefix() {
# Args: name from_user to_user [from_prefix] [to_prefix]
# If the prefixes are not passed explicitly, query them via the API.
local name="$1"
local from="$2"
local to="$3"
local from_pref="${4:-$(get_required_db_prefix "$from")}"
local to_pref="${5:-$(get_required_db_prefix "$to")}"
if [[ -z "$from_pref" || -z "$to_pref" ]]; then
# API failed — fall back to conservative "prepend to_pref" behavior.
echo "${to:0:8}_${name}"
return 1
fi
# Case 1 — name uses the source account's CURRENT prefix (e.g. legacyuser_wpsite).
if [[ "$name" == "${from_pref}"* ]]; then
echo "${to_pref}${name#"${from_pref}"}"
return 0
fi
# Case 2 — name uses the 8-char LEGACY prefix (e.g. leguser_sitename).
local from_legacy="${from:0:8}_"
if [[ "$name" == "${from_legacy}"* && "${from_legacy}" != "${from_pref}" ]]; then
echo "${to_pref}${name#"${from_legacy}"}"
return 0
fi
# Fallback — prepend dest prefix verbatim.
echo "${to_pref}${name}"
}
function snapshot_state() {
local exec_mode="$1"
local state_file="${STATE_DIR}/${DOMAIN}.snapshot.json"
print_step "Snapshot source state"
local payload
payload=$(jq -n \
--arg domain "$DOMAIN" \
--arg from "$FROM_USER" \
--arg to "$TO_USER" \
--arg source_docroot "$SOURCE_DOCROOT" \
--arg dest_docroot "$DEST_DOCROOT" \
--arg source_control_sub "$SOURCE_CONTROL_SUB" \
--arg dest_control_sub "$DEST_CONTROL_SUB" \
--arg site_type "$SITE_TYPE" \
--arg src_db "${SRC_DB_NAME:-}" \
--arg dest_db "${DEST_DB_NAME:-}" \
--arg ts "$(date -Is)" \
'{domain:$domain, from:$from, to:$to, source_docroot:$source_docroot,
dest_docroot:$dest_docroot, source_control_sub:$source_control_sub,
dest_control_sub:$dest_control_sub, site_type:$site_type,
source_db:$src_db, dest_db:$dest_db, snapshot_at:$ts}')
if [[ "$exec_mode" == "dry-run" ]]; then
log_both "[DRY] would write: $state_file"
log_both "[DRY] payload:"
echo "$payload" | sed 's/^/[DRY] /' | tee -a "$LOG_FILE"
else
echo "$payload" > "$state_file"
log_ok "wrote snapshot: $state_file"
fi
return 0
}
function ensure_destination_dir() {
local exec_mode="$1"
print_step "Destination directory"
local parent
parent="$(dirname "$DEST_DOCROOT")"
if run_or_echo "$exec_mode" "mkdir -p '$parent'" && \
run_or_echo "$exec_mode" "mkdir -p '$DEST_DOCROOT'" && \
run_or_echo "$exec_mode" "chown -R ${TO_USER}:${TO_USER} '$parent'" && \
run_or_echo "$exec_mode" "chmod 755 '$DEST_DOCROOT'"; then
log_ok "destination dir prepared"
return 0
fi
return 1
}
function rsync_data() {
local exec_mode="$1"
print_step "rsync data (source -> destination)"
local excludes=(
"--exclude=wp-content/cache"
"--exclude=wp-content/updraft"
"--exclude=wp-content/backup-*"
"--exclude=wp-content/uploads/backwpup-*"
"--exclude=.well-known/acme-challenge"
)
local backup_dir
backup_dir="${STATE_DIR}/rsync-backup-${DOMAIN}-$(date +%s)"
local cmd="rsync -aHAX --delete-after --backup --backup-dir='${backup_dir}' --info=stats2,progress2 ${excludes[*]} --chown=${TO_USER}:${TO_USER} '${SOURCE_DOCROOT}/' '${DEST_DOCROOT}/'"
if [[ "$exec_mode" == "dry-run" ]]; then
log_both "[DRY] would run: $cmd"
# Use --dry-run of rsync to get the real file count report:
local real_cmd="rsync -aHAX --delete-after --dry-run --stats ${excludes[*]} '${SOURCE_DOCROOT}/' '${DEST_DOCROOT}/'"
log_both "[DRY] rsync --dry-run report:"
eval "$real_cmd" 2>&1 | tee -a "$LOG_FILE" | tail -20
return 0
fi
if eval "$cmd" 2>&1 | tee -a "$LOG_FILE"; then
log_ok "rsync completed"
chown -R "${TO_USER}:${TO_USER}" "$DEST_DOCROOT" || log_warn "post-rsync chown -R returned non-zero"
return 0
fi
return 1
}
function migrate_database() {
local exec_mode="$1"
if [[ "$SITE_TYPE" != "wordpress" || "$SKIP_DB" == true ]]; then
print_step "Database migration — SKIPPED (site is ${SITE_TYPE} / skip-db=${SKIP_DB})"
return 0
fi
print_step "Database migration"
local dump_file="${STATE_DIR}/${DOMAIN}.dump.sql"
local tmp_pass
tmp_pass=$(safe_random_password)
if [[ ${#tmp_pass} -lt 16 ]]; then
log_err "failed to generate dest DB password"
return 1
fi
local cmds=(
"mysqldump --single-transaction --quick --routines --triggers --events '${SRC_DB_NAME}' > '${dump_file}'"
"uapi --user=${TO_USER} Mysql create_database name=${DEST_DB_NAME}"
"uapi --user=${TO_USER} Mysql create_user name=${DEST_DB_USER} password='<redacted>'"
"uapi --user=${TO_USER} Mysql set_privileges_on_database user=${DEST_DB_USER} database=${DEST_DB_NAME} privileges=ALL%20PRIVILEGES"
"mariadb '${DEST_DB_NAME}' < '${dump_file}'"
"patch wp-config.php in ${DEST_DOCROOT} (DB_NAME/USER/PASSWORD/HOST)"
)
if [[ "$exec_mode" == "dry-run" ]]; then
log_both "[DRY] DB migration plan:"
for c in "${cmds[@]}"; do log_both "[DRY] $c"; done
return 0
fi
if ! mysqldump --single-transaction --quick --routines --triggers --events "$SRC_DB_NAME" > "$dump_file" 2>>"$LOG_FILE"; then
log_err "mysqldump failed for $SRC_DB_NAME"
return 1
fi
log_ok "dumped $SRC_DB_NAME -> $dump_file ($(du -sh "$dump_file" | awk '{print $1}'))"
if ! uapi --user="$TO_USER" Mysql create_database name="$DEST_DB_NAME" >>"$LOG_FILE" 2>&1; then
log_err "create_database $DEST_DB_NAME failed (see log)"; return 1
fi
if ! uapi --user="$TO_USER" Mysql create_user name="$DEST_DB_USER" password="$tmp_pass" >>"$LOG_FILE" 2>&1; then
log_err "create_user $DEST_DB_USER failed"; return 1
fi
if ! uapi --user="$TO_USER" Mysql set_privileges_on_database user="$DEST_DB_USER" database="$DEST_DB_NAME" privileges="ALL PRIVILEGES" >>"$LOG_FILE" 2>&1; then
log_err "grant privileges failed"; return 1
fi
# Confirm the generated password actually works — if cPanel stored a
# different hash (the silent corruption we hit in v1.0.0), reset it now.
if ! db_login_test "$DEST_DB_USER" "$tmp_pass" "localhost" "$DEST_DB_NAME"; then
log_warn "DB login with generated password failed — resetting via set_password"
if ! uapi --user="$TO_USER" Mysql set_password user="$DEST_DB_USER" password="$tmp_pass" >>"$LOG_FILE" 2>&1; then
log_err "set_password also failed — check log"; return 1
fi
if ! db_login_test "$DEST_DB_USER" "$tmp_pass" "localhost" "$DEST_DB_NAME"; then
log_err "DB login still fails after set_password"; return 1
fi
log_ok "DB login confirmed after password reset"
else
log_ok "DB login confirmed with generated password"
fi
if ! mariadb "$DEST_DB_NAME" < "$dump_file" 2>>"$LOG_FILE"; then
log_err "import to $DEST_DB_NAME failed"; return 1
fi
log_ok "DB imported: $DEST_DB_NAME"
local wpc="${DEST_DOCROOT}/wp-config.php"
cp -a "$wpc" "${wpc}.bak.cpanel-migrate-addon" || { log_err "backup wp-config failed"; return 1; }
# Match define('K', ...) AND define("K", ...), any whitespace, any quote mix.
# The replacement normalizes to single quotes.
sed -i -E \
-e "s/define[[:space:]]*\([[:space:]]*['\"]DB_NAME['\"][[:space:]]*,[[:space:]]*['\"][^'\"]*['\"][[:space:]]*\)[[:space:]]*;/define('DB_NAME', '${DEST_DB_NAME}');/" \
-e "s/define[[:space:]]*\([[:space:]]*['\"]DB_USER['\"][[:space:]]*,[[:space:]]*['\"][^'\"]*['\"][[:space:]]*\)[[:space:]]*;/define('DB_USER', '${DEST_DB_USER}');/" \
-e "s|define[[:space:]]*\([[:space:]]*['\"]DB_PASSWORD['\"][[:space:]]*,[[:space:]]*['\"][^'\"]*['\"][[:space:]]*\)[[:space:]]*;|define('DB_PASSWORD', '${tmp_pass}');|" \
"$wpc" || { log_err "sed on wp-config failed"; return 1; }
# Sanity check: re-extract values and confirm they match
local verify_name verify_user
verify_name=$(php_extract_constant "$wpc" DB_NAME)
verify_user=$(php_extract_constant "$wpc" DB_USER)
if [[ "$verify_name" != "$DEST_DB_NAME" || "$verify_user" != "$DEST_DB_USER" ]]; then
log_err "wp-config patch verification failed (got DB_NAME='$verify_name' DB_USER='$verify_user')"
cp -a "${wpc}.bak.cpanel-migrate-addon" "$wpc"
return 1
fi
log_ok "wp-config.php patched and verified (backup: ${wpc}.bak.cpanel-migrate-addon)"
return 0
}
function create_dest_subdomain() {
local exec_mode="$1"
print_step "Create control subdomain on destination (${DEST_CONTROL_SUB})"
if grep -qE "^${DEST_CONTROL_SUB}: ${TO_USER}\$" /etc/userdomains 2>/dev/null; then
log_ok "subdomain ${DEST_CONTROL_SUB} already exists in ${TO_USER} — skipping (idempotent)"
return 0
fi
local cmd="whmapi1 create_subdomain domain=${DEST_CONTROL_SUB} document_root=${DEST_DOCROOT_REL}"
if [[ "$exec_mode" == "dry-run" ]]; then
log_both "[DRY] $cmd"
return 0
fi
whmapi1_must_succeed create_subdomain \
domain="$DEST_CONTROL_SUB" \
document_root="$DEST_DOCROOT_REL" \
|| { log_err "create_subdomain failed — check log"; return 1; }
log_ok "subdomain ${DEST_CONTROL_SUB} created in ${TO_USER}"
return 0
}
function create_dest_addon() {
local exec_mode="$1"
print_step "Park domain on destination vhost (${DOMAIN} -> ${DEST_CONTROL_SUB})"
if grep -qE "^${DOMAIN}: ${TO_USER}\$" /etc/userdomains 2>/dev/null; then
log_ok "addon ${DOMAIN} already registered on ${TO_USER} — skipping (idempotent)"
return 0
fi
local cmd="whmapi1 create_parked_domain_for_user username=${TO_USER} domain=${DOMAIN} web_vhost_domain=${DEST_CONTROL_SUB}"
if [[ "$exec_mode" == "dry-run" ]]; then
log_both "[DRY] $cmd"
return 0
fi
whmapi1_must_succeed create_parked_domain_for_user \
username="$TO_USER" \
domain="$DOMAIN" \
web_vhost_domain="$DEST_CONTROL_SUB" \
|| { log_err "create_parked_domain_for_user failed — check log"; return 1; }
log_ok "addon ${DOMAIN} registered on ${TO_USER}"
return 0
}
function remove_source_addon() {
local exec_mode="$1"
print_step "Remove from source (${FROM_USER})"
local c1="whmapi1 delete_domain domain=${DOMAIN}"
local c2="whmapi1 delete_domain domain=${SOURCE_CONTROL_SUB}"
if [[ "$exec_mode" == "dry-run" ]]; then
log_both "[DRY] $c1"
log_both "[DRY] $c2"
return 0
fi
# Check that domain is still on source before attempting delete (idempotent)
if grep -qE "^${DOMAIN}: ${FROM_USER}\$" /etc/userdomains 2>/dev/null; then
whmapi1_must_succeed delete_domain domain="$DOMAIN" \
|| { log_err "delete_domain ${DOMAIN} failed"; return 1; }
log_ok "removed addon ${DOMAIN} from ${FROM_USER}"
else
log_ok "${DOMAIN} already absent from source — skipping (idempotent)"
fi
if grep -qE "^${SOURCE_CONTROL_SUB}: ${FROM_USER}\$" /etc/userdomains 2>/dev/null; then
if whmapi1_must_succeed delete_domain domain="$SOURCE_CONTROL_SUB"; then
log_ok "removed control sub ${SOURCE_CONTROL_SUB}"
else
log_warn "delete_domain ${SOURCE_CONTROL_SUB} failed (non-fatal)"
fi
else
log_ok "source control sub ${SOURCE_CONTROL_SUB} already gone"
fi
return 0
}