-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_do.sh
More file actions
executable file
·6989 lines (6050 loc) · 266 KB
/
_do.sh
File metadata and controls
executable file
·6989 lines (6050 loc) · 266 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
#!/bin/bash
# ----------------------------------------------------
# Command: _do
# Description: A collection of useful command-line utilities for managing WordPress sites.
# Author: Austin Ginder
# License: MIT
# ----------------------------------------------------
# --- Global Variables ---
CAPTAINCORE_DO_VERSION="1.4"
GUM_VERSION="0.14.4"
CWEBP_VERSION="1.5.0"
RCLONE_VERSION="1.69.3"
GIT_VERSION="2.50.0"
GUM_CMD=""
CWEBP_CMD=""
IDENTIFY_CMD=""
WP_CLI_CMD=""
RESTIC_CMD=""
DISEMBARK_CMD=""
# --- Helper Functions ---
# ----------------------------------------------------
# Intelligently finds or creates a private directory.
# Sets a global variable CAPTAINCORE_PRIVATE_DIR and echoes the path.
# ----------------------------------------------------
function _get_private_dir() {
# Return immediately if already found
if [[ -n "$CAPTAINCORE_PRIVATE_DIR" ]]; then
echo "$CAPTAINCORE_PRIVATE_DIR"
return 0
fi
local wp_root=""
local parent_dir=""
# --- Tier 1: Preferred WP-CLI Method (if in a WP directory) ---
# Check if wp-cli is set up and if we are in a WP installation.
if setup_wp_cli && "$WP_CLI_CMD" core is-installed --quiet 2>/dev/null; then
local wp_config_path
wp_config_path=$("$WP_CLI_CMD" config path --quiet 2>/dev/null)
if [ -n "$wp_config_path" ] && [ -f "$wp_config_path" ]; then
wp_root=$(dirname "$wp_config_path")
parent_dir=$(dirname "$wp_root")
# --- WPE Specific Checks ---
# A. Check for _wpeprivate inside the WP root directory first (most common).
if [ -d "${wp_root}/_wpeprivate" ]; then
CAPTAINCORE_PRIVATE_DIR="${wp_root}/_wpeprivate"
echo "$CAPTAINCORE_PRIVATE_DIR"
return 0
fi
# B. Check for _wpeprivate in the parent directory.
if [ -d "${parent_dir}/_wpeprivate" ]; then
CAPTAINCORE_PRIVATE_DIR="${parent_dir}/_wpeprivate"
echo "$CAPTAINCORE_PRIVATE_DIR"
return 0
fi
# --- Standard Checks (relative to WP root's parent) ---
# Check for a standard ../private directory
if [ -d "${parent_dir}/private" ]; then
CAPTAINCORE_PRIVATE_DIR="${parent_dir}/private"
echo "$CAPTAINCORE_PRIVATE_DIR"
return 0
fi
# Try to create a ../private directory, suppressing errors
if mkdir -p "${parent_dir}/private" 2>/dev/null; then
CAPTAINCORE_PRIVATE_DIR="${parent_dir}/private"
echo "$CAPTAINCORE_PRIVATE_DIR"
return 0
fi
# Fallback to ../tmp if it exists
if [ -d "${parent_dir}/tmp" ]; then
CAPTAINCORE_PRIVATE_DIR="${parent_dir}/tmp"
echo "$CAPTAINCORE_PRIVATE_DIR"
return 0
fi
fi
fi
# --- Tier 2: Manual Fallback (if WP-CLI fails or not in a WP install) ---
local current_dir
current_dir=$(pwd)
# WPE check in current directory
if [ -d "${current_dir}/_wpeprivate" ]; then
CAPTAINCORE_PRIVATE_DIR="${current_dir}/_wpeprivate"
echo "$CAPTAINCORE_PRIVATE_DIR"
return 0
fi
# Relative private check
if [ -d "../private" ]; then
CAPTAINCORE_PRIVATE_DIR=$(cd ../private && pwd)
echo "$CAPTAINCORE_PRIVATE_DIR"
return 0
fi
# Attempt to create relative private, suppressing errors
if mkdir -p "../private" 2>/dev/null; then
CAPTAINCORE_PRIVATE_DIR=$(cd ../private && pwd)
echo "$CAPTAINCORE_PRIVATE_DIR"
return 0
fi
# Relative tmp check
if [ -d "../tmp" ]; then
CAPTAINCORE_PRIVATE_DIR=$(cd ../tmp && pwd)
echo "$CAPTAINCORE_PRIVATE_DIR"
return 0
fi
# --- Tier 3: Last Resort Fallback to Home Directory ---
# Suppress errors in case $HOME is not writable
if mkdir -p "$HOME/private" 2>/dev/null; then
CAPTAINCORE_PRIVATE_DIR="$HOME/private"
echo "$CAPTAINCORE_PRIVATE_DIR"
return 0
fi
echo "Error: Could not find or create a suitable private, writable directory." >&2
return 1
}
# ----------------------------------------------------
# Checks for and installs 'disembark' if not present.
# Prioritizes standard PATH, then a DISEMBARK_DEV_PATH env var.
# ----------------------------------------------------
function setup_disembark() {
# Return if already found
if [[ -n "$DISEMBARK_CMD" ]]; then
return 0
fi
# 1. Check if 'disembark' is in the standard PATH
if command -v disembark &> /dev/null; then
echo " - Found 'disembark' in system PATH." >&2
DISEMBARK_CMD="disembark"
return 0
fi
# 2. Check for a user-defined development path via environment variable
if [[ -n "$DISEMBARK_DEV_PATH" && -f "$DISEMBARK_DEV_PATH" && -x "$DISEMBARK_DEV_PATH" ]]; then
echo " - Found development version of 'disembark' via DISEMBARK_DEV_PATH." >&2
DISEMBARK_CMD="$DISEMBARK_DEV_PATH"
return 0
fi
# 3. If not found, attempt to install it system-wide
echo " Required tool 'disembark' not found. Attempting to install system-wide..." >&2
# Check for dependencies needed for the installation
if ! command -v wget &>/dev/null || ! command -v sudo &>/dev/null; then
echo " Error: 'wget' and 'sudo' are required to install disembark." >&2
return 1
fi
local temp_file
temp_file=$(mktemp)
echo " - Downloading disembark.phar..."
if ! wget -q "https://github.com/DisembarkHost/disembark-cli/raw/main/disembark.phar" -O "$temp_file"; then
echo " Error: Failed to download disembark.phar." >&2
rm -f "$temp_file"
return 1
fi
chmod +x "$temp_file"
echo " - Moving to /usr/local/bin/disembark. You may be prompted for your password." >&2
if ! sudo mv "$temp_file" /usr/local/bin/disembark; then
echo " Error: Failed to move disembark.phar to /usr/local/bin/." >&2
rm -f "$temp_file"
return 1
fi
echo " 'disembark' installed successfully." >&2
DISEMBARK_CMD="/usr/local/bin/disembark"
return 0
}
# ----------------------------------------------------
# Checks for and installs Playwright and its browser dependencies.
# Sets a global variable PLAYWRIGHT_READY on success.
# ----------------------------------------------------
function setup_playwright() {
# Return if already checked and ready
if [[ -n "$PLAYWRIGHT_READY" ]]; then
return 0
fi
# --- Pre-flight Checks ---
if ! command -v node &>/dev/null; then
echo "❌ Error: Node.js is required for Playwright." >&2
return 1
fi
if ! command -v npm &>/dev/null; then
echo "❌ Error: npm is required to install Playwright." >&2
return 1
fi
# --- Check for Browser Executable ---
# This is a more robust check. require('playwright') can succeed,
# but executablePath() will fail if browsers aren't installed.
if node -e "require('playwright').chromium.executablePath()" >/dev/null 2>&1; then
echo " - ✅ Playwright and required browsers are already installed."
PLAYWRIGHT_READY=true
return 0
fi
# --- Installation ---
echo " - ⚠️ Playwright or its browsers are missing. Attempting to install now..."
echo " This may take a few minutes as it downloads the browser binaries."
# Step 1: Install the NPM package
if ! npm install playwright; then
echo "❌ Error: Failed to install the Playwright npm package." >&2
echo " Please try running 'npm install playwright' manually in this directory." >&2
return 1
fi
# Step 2: Install the browser binaries (specifically chromium)
if ! npx playwright install chromium; then
echo "❌ Error: Failed to download Playwright's browser binaries." >&2
echo " Please try running 'npx playwright install chromium' manually." >&2
return 1
fi
echo " - ✅ Playwright and its browsers installed successfully."
PLAYWRIGHT_READY=true
return 0
}
# ----------------------------------------------------
# Checks for and installs 'gum' if not present. Sets GUM_CMD on success.
# ----------------------------------------------------
function setup_gum() {
# Return if already found
if [[ -n "$GUM_CMD" ]]; then return 0; fi
# If gum is already in the PATH, we're good to go.
if command -v gum &> /dev/null; then
GUM_CMD="gum"
return 0
fi
# Find the private directory for storing tools
local private_dir
if ! private_dir=$(_get_private_dir); then
echo "Error: Cannot find a writable directory to install gum." >&2
return 1
fi
# Find the executable inside the private directory if it's already installed
local existing_executable
existing_executable=$(find "$private_dir" -name gum -type f 2>/dev/null | head -n 1)
if [ -n "$existing_executable" ] && [ -x "$existing_executable" ] && "$existing_executable" --version &> /dev/null; then
GUM_CMD="$existing_executable"
return 0
fi
echo "Required tool 'gum' not found. Installing to '${private_dir}'..." >&2
local original_dir; original_dir=$(pwd)
cd "$private_dir" || { echo "Error: Could not enter private directory '${private_dir}'." >&2; return 1; }
local gum_dir_name="gum_${GUM_VERSION}_Linux_x86_64"
local gum_tarball="${gum_dir_name}.tar.gz"
if ! curl -sSL "https://github.com/charmbracelet/gum/releases/download/v${GUM_VERSION}/${gum_tarball}" -o "${gum_tarball}"; then
echo "Error: Failed to download gum." >&2; cd "$original_dir" > /dev/null 2>&1; return 1;
fi
# Find the path of the 'gum' binary WITHIN the tarball before extracting
local gum_path_in_tar
gum_path_in_tar=$(tar -tf "${gum_tarball}" | grep '/gum$' | head -n 1)
if [ -z "$gum_path_in_tar" ]; then
echo "Error: Could not find 'gum' executable within the downloaded tarball." >&2
rm -f "${gum_tarball}"; cd "$original_dir" > /dev/null 2>&1; return 1;
fi
# Now extract the tarball
if ! tar -xf "${gum_tarball}"; then
echo "Error: Failed to extract gum from tarball." >&2
rm -f "${gum_tarball}"; cd "$original_dir" > /dev/null 2>&1; return 1;
fi
rm -f "${gum_tarball}"
# The full path to the executable is the private dir + the path from the tarball
local gum_executable="${private_dir}/${gum_path_in_tar}"
if [ -f "$gum_executable" ]; then
chmod +x "$gum_executable"
else
echo "Error: gum executable not found at expected path after extraction: ${gum_executable}" >&2
cd "$original_dir" > /dev/null 2>&1; return 1;
fi
# Final check
if [ -x "$gum_executable" ] && "$gum_executable" --version &> /dev/null; then
echo "'gum' installed successfully." >&2
GUM_CMD="$gum_executable"
else
echo "Error: gum installation failed. The binary at ${gum_executable} might not be executable or compatible." >&2
cd "$original_dir" > /dev/null 2>&1; return 1;
fi
cd "$original_dir" > /dev/null 2>&1; return 0;
}
# ----------------------------------------------------
# Checks for and installs 'cwebp' if not present. Sets CWEBP_CMD on success.
# ----------------------------------------------------
function setup_cwebp() {
# Return if already found
if [[ -n "$CWEBP_CMD" ]]; then return 0; fi
if command -v cwebp &> /dev/null; then CWEBP_CMD="cwebp"; return 0; fi
local private_dir
if ! private_dir=$(_get_private_dir); then
echo "Error: Cannot find a writable directory to install cwebp." >&2; return 1;
fi
local existing_executable
existing_executable=$(find "$private_dir" -name cwebp -type f 2>/dev/null | head -n 1)
if [ -n "$existing_executable" ] && [ -x "$existing_executable" ] && "$existing_executable" -version &> /dev/null; then
CWEBP_CMD="$existing_executable"; return 0;
fi
echo "Required tool 'cwebp' not found. Installing to '${private_dir}'..." >&2
local original_dir; original_dir=$(pwd)
cd "$private_dir" || { echo "Error: Could not enter private directory '${private_dir}'." >&2; return 1; }
local cwebp_dir_name="libwebp-${CWEBP_VERSION}-linux-x86-64"
local cwebp_tarball="${cwebp_dir_name}.tar.gz"
if ! curl -sSL "https://storage.googleapis.com/downloads.webmproject.org/releases/webp/${cwebp_tarball}" -o "${cwebp_tarball}"; then
echo "Error: Failed to download cwebp." >&2; cd "$original_dir" > /dev/null 2>&1; return 1;
fi
local cwebp_path_in_tar
cwebp_path_in_tar=$(tar -tf "${cwebp_tarball}" | grep '/bin/cwebp$' | head -n 1)
if [ -z "$cwebp_path_in_tar" ]; then
echo "Error: Could not find 'cwebp' executable within the downloaded tarball." >&2
rm -f "${cwebp_tarball}"; cd "$original_dir" > /dev/null 2>&1; return 1;
fi
if ! tar -xzf "${cwebp_tarball}"; then
echo "Error: Failed to extract cwebp." >&2; rm -f "${cwebp_tarball}"; cd "$original_dir" > /dev/null 2>&1; return 1;
fi
rm -f "${cwebp_tarball}"
local cwebp_executable="${private_dir}/${cwebp_path_in_tar}"
if [ -f "$cwebp_executable" ]; then
chmod +x "$cwebp_executable";
else
echo "Error: cwebp executable not found at expected path: ${cwebp_executable}" >&2; cd "$original_dir" > /dev/null 2>&1; return 1;
fi
if [ -x "$cwebp_executable" ] && "$cwebp_executable" -version &> /dev/null; then
echo "'cwebp' installed successfully." >&2; CWEBP_CMD="$cwebp_executable";
else
echo "Error: cwebp installation failed." >&2; cd "$original_dir" > /dev/null 2>&1; return 1;
fi
cd "$original_dir" > /dev/null 2>&1; return 0;
}
# ----------------------------------------------------
# Checks for and installs ImageMagick if not present. Sets IDENTIFY_CMD on success.
# ----------------------------------------------------
function setup_imagemagick() {
# Return if already found
if [[ -n "$IDENTIFY_CMD" ]]; then
return 0
fi
# If identify is already in the PATH, we're good to go.
if command -v identify &> /dev/null; then
IDENTIFY_CMD="identify"
return 0
fi
local private_dir
if ! private_dir=$(_get_private_dir); then
# Error message is handled by the helper function
return 1
fi
# Define the path where the extracted binary should be
local identify_executable="${private_dir}/squashfs-root/usr/bin/identify"
# Check if we have already extracted it
if [ -f "$identify_executable" ] && "$identify_executable" -version &> /dev/null; then
IDENTIFY_CMD="$identify_executable"
return 0
fi
# If not found, download and extract the AppImage
echo "Required tool 'identify' not found. Sideloading via AppImage extraction..." >&2
local imagemagick_appimage_path="${private_dir}/ImageMagick.AppImage"
# Let's use the 'gcc' version as it's a common compiler toolchain for Linux
local appimage_url="https://github.com/ImageMagick/ImageMagick/releases/download/7.1.1-47/ImageMagick-82572af-gcc-x86_64.AppImage"
echo "Downloading from ${appimage_url}..." >&2
if ! wget --quiet "$appimage_url" -O "$imagemagick_appimage_path"; then
echo "Error: Failed to download the ImageMagick AppImage." >&2
rm -f "$imagemagick_appimage_path" # Clean up partial download
return 1
fi
chmod +x "$imagemagick_appimage_path"
# --- EXTRACTION STEP ---
# This is the key change to work around the FUSE error.
echo "Extracting AppImage..." >&2
# Change into the private directory to contain the extraction
cd "$private_dir" || { echo "Error: Could not enter private directory." >&2; return 1; }
# Run the extraction. This creates a 'squashfs-root' directory.
if ! ./ImageMagick.AppImage --appimage-extract >/dev/null; then
echo "Error: Failed to extract the ImageMagick AppImage." >&2
# Clean up on failure
rm -f "ImageMagick.AppImage"
rm -rf "squashfs-root"
cd - > /dev/null
return 1
fi
# We don't need the AppImage file anymore after extraction
rm -f "ImageMagick.AppImage"
# Return to the original directory
cd - > /dev/null
# Final check
if [ -f "$identify_executable" ] && "$identify_executable" -version &> /dev/null; then
echo "'identify' binary extracted successfully to ${private_dir}/squashfs-root/" >&2
IDENTIFY_CMD="$identify_executable"
else
echo "Error: ImageMagick extraction failed. Could not find the 'identify' executable." >&2
return 1
fi
}
# ----------------------------------------------------
# Checks for and installs 'rclone' if not present. Sets RCLONE_CMD on success.
# ----------------------------------------------------
function setup_rclone() {
# Return if already found
if [[ -n "$RCLONE_CMD" ]]; then return 0; fi
if command -v rclone &> /dev/null; then RCLONE_CMD="rclone"; return 0; fi
if ! command -v unzip &>/dev/null; then echo "Error: 'unzip' command is required for rclone installation." >&2; return 1; fi
local private_dir
if ! private_dir=$(_get_private_dir); then
echo "Error: Cannot find a writable directory to install rclone." >&2; return 1;
fi
local existing_executable
existing_executable=$(find "$private_dir" -name rclone -type f 2>/dev/null | head -n 1)
if [ -n "$existing_executable" ] && [ -x "$existing_executable" ] && "$existing_executable" --version &> /dev/null; then
RCLONE_CMD="$existing_executable"; return 0;
fi
echo "Required tool 'rclone' not found. Installing to '${private_dir}'..." >&2
local original_dir; original_dir=$(pwd)
cd "$private_dir" || { echo "Error: Could not enter private directory '${private_dir}'." >&2; return 1; }
local rclone_zip="rclone-v${RCLONE_VERSION}-linux-amd64.zip"
if ! curl -sSL "https://github.com/rclone/rclone/releases/download/v${RCLONE_VERSION}/${rclone_zip}" -o "${rclone_zip}"; then
echo "Error: Failed to download rclone." >&2; cd "$original_dir" > /dev/null 2>&1; return 1;
fi
local rclone_path_in_zip
rclone_path_in_zip=$(unzip -l "${rclone_zip}" | grep '/rclone$' | awk '{print $4}' | head -n 1)
if [ -z "$rclone_path_in_zip" ]; then
echo "Error: Could not find 'rclone' executable within the downloaded zip." >&2
rm -f "${rclone_zip}"; cd "$original_dir" > /dev/null 2>&1; return 1;
fi
if ! unzip -q -o "${rclone_zip}"; then
echo "Error: Failed to extract rclone." >&2; rm -f "${rclone_zip}"; cd "$original_dir" > /dev/null 2>&1; return 1;
fi
rm -f "${rclone_zip}"
local rclone_executable="${private_dir}/${rclone_path_in_zip}"
if [ -f "$rclone_executable" ]; then
chmod +x "$rclone_executable";
else
echo "Error: rclone executable not found at expected path: ${rclone_executable}" >&2; cd "$original_dir" > /dev/null 2>&1; return 1;
fi
if [ -x "$rclone_executable" ] && "$rclone_executable" --version &> /dev/null; then
echo "'rclone' installed successfully." >&2; RCLONE_CMD="$rclone_executable";
else
echo "Error: rclone installation failed." >&2; cd "$original_dir" > /dev/null 2>&1; return 1;
fi
cd "$original_dir" > /dev/null 2>&1; return 0;
}
# ----------------------------------------------------
# Checks for and installs 'restic' if not present.
# Sets RESTIC_CMD on success.
# ----------------------------------------------------
function setup_restic() {
# Return if already found
if [[ -n "$RESTIC_CMD" ]]; then return 0; fi
# If restic is already in the PATH, we're good.
if command -v restic &> /dev/null; then
RESTIC_CMD="restic"
return 0
fi
# Check for local installation in private dir
local restic_executable="$HOME/private/restic"
if [ -f "$restic_executable" ] && "$restic_executable" version &> /dev/null; then
RESTIC_CMD="$restic_executable"
return 0
fi
# If not found, download it
echo "Required tool 'restic' not found. Installing..." >&2
if ! command -v bunzip2 &>/dev/null; then echo "Error: 'bunzip2' command is required for installation." >&2; return 1; fi
mkdir -p "$HOME/private"
cd "$HOME/private" || { echo "Error: Could not enter ~/private." >&2; return 1; }
local restic_version="0.18.0"
local restic_archive="restic_${restic_version}_linux_amd64.bz2"
if ! curl -sL "https://github.com/restic/restic/releases/download/v${restic_version}/${restic_archive}" -o "${restic_archive}"; then
echo "Error: Failed to download restic." >&2
cd - > /dev/null
return 1
fi
# Decompress and extract the binary
bunzip2 -c "${restic_archive}" > restic_temp && mv restic_temp restic
rm -f "${restic_archive}"
chmod +x restic
# Final check
if [ -f "$restic_executable" ] && "$restic_executable" version &> /dev/null; then
echo "'restic' installed successfully." >&2
RESTIC_CMD="$restic_executable"
else
echo "Error: restic installation failed." >&2
cd - > /dev/null
return 1
fi
cd - > /dev/null
}
# ----------------------------------------------------
# Checks for and installs 'git' if not present. Sets GIT_CMD on success.
# ----------------------------------------------------
function setup_git() {
# Return if already found
if [[ -n "$GIT_CMD" ]]; then
return 0
fi
# If git is already in the PATH, we're good to go.
if command -v git &> /dev/null; then
GIT_CMD="git"
return 0
fi
# --- Sideloading Logic ---
echo "Required tool 'git' not found. Attempting to sideload..." >&2
local private_dir
if ! private_dir=$(_get_private_dir); then
return 1
fi
local git_executable="${private_dir}/git/usr/bin/git"
# Check if git has already been sideloaded
if [ -f "$git_executable" ] && "$git_executable" --version &> /dev/null; then
echo "'git' found in private directory." >&2
GIT_CMD="$git_executable"
return 0
fi
# Check for wget and dpkg-deb, which are required for sideloading
if ! command -v wget &> /dev/null || ! command -v dpkg-deb &> /dev/null; then
echo "❌ Error: 'wget' and 'dpkg-deb' are required to sideload git." >&2
return 1
fi
# Determine OS distribution and version
if [ -f /etc/os-release ]; then
. /etc/os-release
else
echo "❌ Error: Cannot determine OS distribution. /etc/os-release not found." >&2
return 1
fi
if [[ "$ID" != "ubuntu" ]]; then
echo "❌ Error: Sideloading git is currently only supported on Ubuntu." >&2
return 1
fi
# Construct the download URL for the git package
# This example uses a recent stable version. You may need to update the version number periodically.
local git_version="2.47.1-0ppa1~ubuntu16.04.1"
local git_deb_url="https://launchpad.net/~git-core/+archive/ubuntu/candidate/+build/29298725/+files/git_${git_version}_amd64.deb"
local git_deb_file="${private_dir}/git_latest.deb"
echo "Downloading git from ${git_deb_url}..." >&2
if ! wget -q -O "$git_deb_file" "$git_deb_url"; then
echo "❌ Error: Failed to download git .deb package." >&2
rm -f "$git_deb_file"
return 1
fi
echo "Extracting git package..." >&2
local extract_dir="${private_dir}/git"
mkdir -p "$extract_dir"
if ! dpkg-deb -x "$git_deb_file" "$extract_dir"; then
echo "❌ Error: Failed to extract git .deb package." >&2
rm -rf "$extract_dir"
rm -f "$git_deb_file"
return 1
fi
# Clean up the downloaded .deb file
rm -f "$git_deb_file"
# Final check
if [ -f "$git_executable" ] && "$git_executable" --version &> /dev/null; then
echo "'git' sideloaded successfully." >&2
GIT_CMD="$git_executable"
return 0
else
echo "❌ Error: git sideloading failed. The git binary is not available after extraction." >&2
return 1
fi
}
# ----------------------------------------------------
# Checks for and finds the 'wp' command. Sets WP_CLI_CMD on success.
# ----------------------------------------------------
function setup_wp_cli() {
# Return if already found
if [[ -n "$WP_CLI_CMD" ]]; then return 0; fi
# 1. Check if 'wp' is already in the PATH (covers interactive shells)
if command -v wp &> /dev/null; then
WP_CLI_CMD="wp"
return 0
fi
# 2. If not in PATH, check common absolute paths for cron environments
local common_paths=(
"/usr/local/bin/wp"
"$HOME/bin/wp"
"/opt/wp-cli/wp"
)
for path in "${common_paths[@]}"; do
if [ -x "$path" ]; then
WP_CLI_CMD="$path"
return 0
fi
done
# 3. If still not found, error out
echo "❌ Error: 'wp' command not found. Please ensure WP-CLI is installed and in your PATH." >&2
return 1
}
# ----------------------------------------------------
# (Helper) Uses PHP to check if a file is a WebP image.
# ----------------------------------------------------
function _is_webp_php() {
local file_path="$1"
if [ -z "$file_path" ]; then
return 1 # Return false if no file path is provided
fi
# IMAGETYPE_WEBP has a constant value of 18 in PHP.
# We will embed the file_path directly into the PHP string.
local php_code="
\$file_to_check = '${file_path}';
if (!file_exists(\$file_to_check)) {
// Silently exit if file doesn't exist, to avoid warnings.
exit(1);
}
if (function_exists('exif_imagetype')) {
// The @ suppresses warnings for unsupported file types.
\$image_type = @exif_imagetype(\$file_to_check);
if (\$image_type === 18) { // 18 is the constant for IMAGETYPE_WEBP
exit(0); // Exit with success code (true)
}
}
exit(1); // Exit with failure code (false)
"
if ! setup_wp_cli; then
if command -v php &> /dev/null; then
php -r "\$file_path='${file_path}'; ${php_code}"
return $?
fi
return 1
fi
# Execute 'wp eval' with the self-contained code. No extra arguments are needed.
"$WP_CLI_CMD" eval "$php_code"
return $?
}
# ----------------------------------------------------
# (Primary Checker) Checks if a file is WebP, using identify or PHP fallback.
# ----------------------------------------------------
function _is_webp() {
# Determine which method to use, but only do it once.
if [[ -z "$IDENTIFY_METHOD" ]]; then
if command -v identify &> /dev/null; then
export IDENTIFY_METHOD="identify"
else
export IDENTIFY_METHOD="php"
fi
fi
# Execute the chosen method
if [[ "$IDENTIFY_METHOD" == "identify" ]]; then
# Return false if the file doesn't exist to prevent errors.
if [ ! -f "$1" ]; then return 1; fi
if [[ "$(identify -format "%m" "$1")" == "WEBP" ]]; then
return 0 # It is a WebP file
else
return 1 # It is not a WebP file
fi
else # Fallback to PHP
if _is_webp_php "$1"; then
return 0 # It is a WebP file
else
return 1 # It is not a WebP file
fi
fi
}
# ----------------------------------------------------
# Displays detailed help for a specific command.
# ----------------------------------------------------
function show_command_help() {
local cmd="$1"
# If no command is specified, show the general usage.
if [ -z "$cmd" ]; then
show_usage
return
fi
# Display help text based on the command provided.
case "$cmd" in
backup)
echo "Creates a full backup (files + DB) of a WordPress site."
echo
echo "Usage: _do backup <folder> [--quiet]"
echo
echo "Flags:"
echo " --exclude=<pattern> A file or folder pattern to exclude, relative to the backup folder."
echo " Can be used multiple times (e.g., --exclude=\"wp-content/uploads/\")."
echo " --quiet Suppress all informational output and print only the final backup URL."
;;
checkpoint)
echo "Manages versioned checkpoints of a WordPress installation's manifest."
echo
echo "Usage: _do checkpoint <subcommand> [arguments]"
echo
echo "Subcommands:"
echo " create Creates a new checkpoint of the current plugin/theme/core manifest."
echo " list Lists available checkpoints from the generated list to inspect."
echo " list-generate Generates a detailed list of all checkpoints for fast viewing."
echo " revert [<hash>] Reverts the site to the specified checkpoint hash."
echo " show <hash> Retrieves the details for a specific checkpoint hash."
echo " latest Gets the hash of the most recent checkpoint."
;;
clean)
echo "Cleans up unused WordPress components or analyzes disk usage."
echo
echo "Usage: _do clean <subcommand>"
echo
echo "Subcommands:"
echo " plugins Deletes all inactive plugins."
echo " themes Deletes all inactive themes except for the latest default WordPress theme."
echo " disk Provides an interactive disk usage analysis for the current directory."
;;
cron)
echo "Manages scheduled tasks (cron jobs) for this script."
echo
echo "Usage: _do cron <subcommand> [arguments]"
echo
echo "Subcommands:"
echo " enable Adds a job to the system crontab to run '_do cron run' every 10 minutes."
echo " list Lists all scheduled commands."
echo " run Executes any scheduled commands that are due."
echo " add \"<cmd>\" \"<time>\" \"<freq>\" Adds a new command to the schedule."
echo " delete <id> Deletes a command from the schedule."
echo
echo "Arguments for 'add':"
echo " <cmd> (Required) The _do command to run, in quotes (e.g., \"update all\")."
echo " <time> (Required) The next run time, in quotes (e.g., \"4am\", \"tomorrow 2pm\", \"+2 hours\")."
echo " <freq> (Required) The frequency, in quotes (e.g., \"1 day\", \"1 week\", \"12 hours\")."
echo
echo "Example:"
echo " _do cron add \"update all\" \"4am\" \"1 day\""
;;
db)
echo "Performs various database operations."
echo
echo "Usage: _do db <subcommand>"
echo
echo "Subcommands:"
echo " backup Performs a DB-only backup to a secure private directory."
echo " check-autoload Checks the size and top 25 largest autoloaded options in the DB."
echo " optimize Converts tables to InnoDB, reports large tables, and cleans transients."
echo " change-prefix Changes the database table prefix."
;;
disembark)
echo "Remotely installs the Disembark plugin, connects, and initiates a backup."
echo
echo "Usage: _do disembark <url> [--debug]"
echo
echo "Arguments:"
echo " <url> (Required) The full URL to the WordPress site."
echo
echo "Flags:"
echo " --debug Runs the browser automation in headed mode (not headless) for debugging."
echo
echo "You will be interactively prompted for an administrator username and password."
;;
dump)
echo "Dumps the content of files matching a pattern into a single text file."
echo
echo "Usage: _do dump \"<pattern>\" [-x <exclude_pattern_1>] [-x <exclude_pattern_2>]..."
echo
echo "Arguments:"
echo " <pattern> (Required) The path and file pattern to search for, enclosed in quotes."
echo
echo "Flags:"
echo " -x <pattern> (Optional) A file or directory pattern to exclude. Can be used multiple times."
echo " To exclude a directory, the pattern MUST end with a forward slash (e.g., 'my-dir/')."
echo
echo "Examples:"
echo " _do dump \"wp-content/plugins/my-plugin/**/*.php\""
echo " _do dump \"*\" -x \"*.log\" -x \"node_modules/\""
;;
email)
echo "Sends an email using wp_mail via WP-CLI."
echo
echo "Usage: _do email"
echo
echo "This command will interactively prompt for the recipient, subject, and content."
;;
find)
echo "Finds files or WordPress components based on specific criteria."
echo
echo "Usage: _do find <subcommand> [arguments]"
echo
echo "Subcommands:"
echo " recent-files [days] Finds files modified within the last <days>. Defaults to 1 day."
echo " slow-plugins [path] Identifies plugins slowing down WP-CLI. Optionally check a specific page path (e.g., \"/contact\")."
echo " hidden-plugins Detects active plugins that may be hidden from the standard list."
echo " malware Scans for malware and verifies core/plugin file integrity."
echo " php-tags [dir] Finds outdated PHP short tags ('<?'). Defaults to 'wp-content/'."
;;
https)
echo "Applies HTTPS to all site URLs."
echo
echo "Usage: _do https"
echo
echo "This command will interactively ask whether to use 'www.' or not in the final URL"
echo "and then perform a search-and-replace across the entire database."
;;
convert-to-webp)
echo "Finds and converts large images (JPG, PNG) to WebP format."
echo
echo "Usage: _do convert-to-webp [folder] [--all]"
echo
echo "Arguments:"
echo " [folder] (Optional) The folder to convert. Defaults to 'wp-content/uploads'."
echo
echo "Flags:"
echo " --all Convert all images, regardless of size. Defaults to images > 1MB."
;;
install)
echo "Installs helper or premium plugins."
echo
echo "Usage: _do install <subcommand> [--flags]"
echo
echo "Subcommands:"
echo " kinsta-mu Installs the Kinsta MU plugin. Use --force to install outside a Kinsta environment."
echo " helper Installs the CaptainCore Helper plugin."
echo " events-calendar-pro Installs The Events Calendar and its Pro version after prompting for a license."
;;
launch)
echo "Launches a site: updates URL from dev to live, enables search engines, and clears cache."
echo
echo "Usage: _do launch [--domain=<domain>]"
echo
echo "Flags:"
echo " --domain=<domain> (Optional) The new domain name. If omitted, you will be prompted interactively."
;;
migrate)
echo "Migrates a site from a backup snapshot."
echo
echo "Usage: _do migrate --url=<backup-url> [--update-urls]"
echo
echo " --update-urls Update urls to destination WordPress site. Default will keep source urls."
;;
monitor)
echo "Monitors server access logs or errors in real-time."
echo
echo "Usage: _do monitor <subcommand> [--flags]"
echo
echo "Subcommands:"
echo " traffic Analyzes and monitors top hits from access logs."
echo " errors Monitors logs for HTTP 500 and PHP fatal errors."
echo " access.log Provides a real-time stream of the access log."
echo " error.log Provides a real-time stream of the error log."
echo
echo "Flags for 'traffic':"
echo " --top=<number> The number of top IP/Status combinations to show. Default is 25."
echo " --now Start processing from the end of the log file instead of the beginning."
;;
php-tags)
echo "Finds outdated or invalid PHP opening tags in PHP files."
echo
echo "Usage: _do php-tags [directory]"
echo
echo "Arguments:"
echo " [directory] (Optional) The directory to search in. Defaults to 'wp-content/'."
;;
reset)
echo "Resets WordPress components or permissions."
echo
echo "Usage: _do reset <subcommand> [arguments]"
echo
echo "Subcommands:"
echo " wp Resets the WordPress installation to a default state."
echo " permissions Resets file and folder permissions to defaults (755 for dirs, 644 for files)."
;;
suspend)
echo "Activates or deactivates a suspend message shown to visitors."
echo
echo "Usage: _do suspend <subcommand> [flags]"
echo
echo "Subcommands:"
echo " activate Activates the suspend message. Requires --name and --link flags."
echo " deactivate Deactivates the suspend message."
echo
echo "Flags for 'activate':"
echo " --name=<business-name> (Required) The name of the business to display."
echo " --link=<business-link> (Required) The contact link for the business."
echo " --wp-content=<path> (Optional) Path to wp-content directory. Defaults to 'wp-content'."
echo
echo "Flags for 'deactivate':"
echo " --wp-content=<path> (Optional) Path to wp-content directory. Defaults to 'wp-content'."
;;
update)
echo "Handles WordPress core, theme, and plugin updates."
echo
echo "Usage: _do update <subcommand>"
echo
echo "Subcommands:"
echo " all Creates a 'before' checkpoint, runs all updates, creates an"
echo " 'after' checkpoint, and logs the changes."
echo " list Shows a list of past updates to inspect from the generated list."
echo " list-generate Generates a detailed list of all updates for fast viewing."
;;
upgrade)
echo "Upgrades the _do script to the latest version."
echo
echo "Usage: _do upgrade"
;;
vault)
echo "Manages secure, full site snapshots in a remote Restic repository."
echo
echo "Usage: _do vault <subcommand> [arguments]"
echo
echo "Subcommands:"
echo " create Creates a new snapshot of the current site."
echo " snapshots [--output] Lists available snapshots. Use --output for a non-interactive list."
echo " snapshot-info <id> Displays detailed information for a single snapshot."
echo " delete <id> Deletes a specific snapshot by its ID."
echo " mount Mounts the entire repository to a local folder for Browse."
echo " info Displays statistics about the repository."
echo " prune Removes unnecessary data from the repository."
echo
echo "Authentication:"
echo " This command requires B2 and Restic credentials, provided either by"
echo " environment variables (B2_ACCOUNT_ID, B2_ACCOUNT_KEY, RESTIC_PASSWORD,"
echo " B2_BUCKET, B2_PATH) or by piping a 5-line secrets file via stdin."