-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathvhost-import.sh
More file actions
717 lines (613 loc) · 29 KB
/
vhost-import.sh
File metadata and controls
717 lines (613 loc) · 29 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
#!/usr/bin/env bash
#----------------------------------------------------------------------------------
# EngineScript - A High-Performance WordPress Server Built on Ubuntu and Cloudflare
#----------------------------------------------------------------------------------
# Website: https://EngineScript.com
# GitHub: https://github.com/Enginescript/EngineScript
# License: GPL v3.0
#----------------------------------------------------------------------------------
# EngineScript Variables
source /usr/local/bin/enginescript/enginescript-variables.txt || { echo "Error: Failed to source /usr/local/bin/enginescript/enginescript-variables.txt" >&2; exit 1; }
source /home/EngineScript/enginescript-install-options.txt || { echo "Error: Failed to source /home/EngineScript/enginescript-install-options.txt" >&2; exit 1; }
# Source shared functions library
source /usr/local/bin/enginescript/scripts/functions/shared/enginescript-common.sh || { echo "Error: Failed to source /usr/local/bin/enginescript/scripts/functions/shared/enginescript-common.sh" >&2; exit 1; }
# Source shared vhost functions library
source /usr/local/bin/enginescript/scripts/functions/shared/enginescript-shared-vhost.sh || { echo "Error: Failed to source /usr/local/bin/enginescript/scripts/functions/shared/enginescript-shared-vhost.sh" >&2; exit 1; }
# Source shared database credential functions
source /usr/local/bin/enginescript/scripts/functions/shared/enginescript-db-credentials.sh || { echo "Error: Failed to source /usr/local/bin/enginescript/scripts/functions/shared/enginescript-db-credentials.sh" >&2; exit 1; }
#----------------------------------------------------------------------------------
# Start Main Script
# --- Define Fixed Import Paths ---
IMPORT_BASE_DIR="/home/EngineScript/temp/site-import"
WP_ARCHIVE_DIR="${IMPORT_BASE_DIR}/root-directory" # Directory containing the archive
DB_IMPORT_DIR="${IMPORT_BASE_DIR}/database-file"
WP_EXTRACTED_PATH="${IMPORT_BASE_DIR}/extracted-root" # Temporary path for extracted files
# Note: ALLOWED_DB_CHARSETS is now defined in enginescript-db-credentials.sh
# Build the default URL validation regex from documented components.
# Pattern intent:
# - scheme: http:// or https://
# - host: one or more DNS labels separated by dots
# - port: optional :<1-5 digits>
# - suffix: optional path/query/fragment beginning with /, ?, or #
build_default_url_validation_regex() {
local scheme='https?://'
local host_label='[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?'
local host="(${host_label}\\.)*${host_label}"
local port='(:[0-9]{1,5})?'
local suffix='([/?#].*)?'
echo "^${scheme}${host}${port}${suffix}$"
return 0
}
readonly DEFAULT_URL_VALIDATION_REGEX="$(build_default_url_validation_regex)"
URL_VALIDATION_REGEX="${URL_VALIDATION_REGEX:-$DEFAULT_URL_VALIDATION_REGEX}"
# Validate ZIP archive entries to prevent path traversal (Zip Slip)
validate_zip_archive_paths() {
local archive_file="$1"
local entry=""
while IFS= read -r entry; do
# Reject absolute paths and parent-directory traversal segments
if [[ "$entry" == /* ]] || [[ "$entry" =~ (^|/)\.\.(\/|$) ]]; then
echo "FAILED: Unsafe path detected in archive ${archive_file}: ${entry}"
return 1
fi
done < <(unzip -Z -1 "$archive_file")
return 0
}
# Returns true (0) when a directory is absent or contains no files/subdirs
is_directory_absent_or_empty() {
local dir="$1"
[[ ! -d "$dir" ]] || [[ -z "$(find "$dir" -mindepth 1 -print -quit)" ]]
return $?
}
# --- Instructions for Preparing Files ---
echo ""
echo "${BOLD}Preparing Files for Import:${NORMAL}"
echo "---------------------------------------------------------------------"
echo "You can use one of the following methods:"
echo ""
echo "${BOLD}Method 1: Single Export File (Recommended - using EngineScript Site Exporter plugin)${NORMAL}"
echo " - This method uses the 'EngineScript Site Exporter' plugin to create a single .zip file"
echo " containing both WordPress files and the database (.sql)."
echo " - ${YELLOW}If you don't have the plugin on your source site:${NORMAL}"
echo " 1. Download the plugin zip from: ${UNDERLINE}https://github.com/EngineScript/enginescript-site-exporter/releases/latest${NORMAL}"
echo " 2. In your source WordPress admin area, go to 'Plugins' -> 'Add New' -> 'Upload Plugin'."
echo " 3. Upload the downloaded .zip file and activate the 'EngineScript Site Exporter' plugin."
echo " - Once the plugin is active on your source site:"
echo " 1. Go to 'Tools' -> 'Site Exporter' in your WordPress admin."
echo " 2. Click the 'Export Site' button."
echo " 3. Download the generated .zip file (e.g., site_export_es_se_... .zip)."
echo " - Place this single downloaded .zip file directly inside the following directory on the EngineScript server:"
echo " \`${IMPORT_BASE_DIR}\`"
echo " (Ensure only this one .zip file is present in ${IMPORT_BASE_DIR})"
echo ""
echo "${BOLD}Method 2: Separate Files (Manual Export)${NORMAL}"
echo " 1. ${BOLD}WordPress Root Directory Archive:${NORMAL}"
echo " - Compress your WordPress root directory content (.tar.gz or .zip)."
echo " - Place the archive file inside:"
echo " \`${WP_ARCHIVE_DIR}\`"
echo " 2. ${BOLD}WordPress Database Dump:${NORMAL}"
echo " - Export your database (.sql or .sql.gz)."
echo " - Place the database file inside:"
echo " \`${DB_IMPORT_DIR}\`"
echo "---------------------------------------------------------------------"
prompt_continue "Press [Enter] when your files are prepared and ready" 600
# --- End Instructions ---
# Check if services are running
check_required_services
# Intro Warning
echo ""
echo "-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-"
echo "| Domain Import |"
echo "-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-"
echo ""
echo "This script will import an existing WordPress site."
echo "Please ensure the following:"
echo " 1. The compressed WordPress site root directory (.zip or .tar.gz) is placed in:"
echo " ${WP_ARCHIVE_DIR}"
echo " 2. The database dump file (.sql or .sql.gz) is placed in:"
echo " ${DB_IMPORT_DIR}"
echo ""
sleep 1
# --- Function Definitions ---
# Escape a string so it can be safely embedded as a literal inside a sed/grep -E pattern.
# Escaped characters:
# [](){}.^$*+?|\\/-
# These are ERE metacharacters or delimiter-sensitive characters in this sed usage.
escape_ere_literal_for_sed() {
local raw="$1"
printf '%s' "$raw" | sed -E 's#[][(){}.^$*+?|\\/-]#\\&#g'
return 0
}
# Function to extract define values (Handles single/double quotes)
extract_define() {
local key="$1"
local escaped_key
escaped_key=$(escape_ere_literal_for_sed "$key")
# Find the line defining the key
local line
line=$(grep -E "^\s*define\(\s*['\"]${escaped_key}['\"]\s*," "$WP_CONFIG_PATH")
# Extract the value between single or double quotes after the comma
local value
value=$(echo "$line" | sed -E "s/.*,\s*['\"]([^'\"]*)['\"].*/\1/")
echo "$value"
}
# Function to extract table prefix from the database dump file
extract_prefix_from_db() {
local db_file="$1"
local prefix=""
local grep_cmd="grep"
# Look for CREATE TABLE or INSERT INTO lines with common tables (_options or _users)
# Capture the table name between backticks/quotes, then strip _options/_users to derive prefix
local search_pattern="(CREATE TABLE|INSERT INTO)[[:space:]]+(\`|\")[^\`\"]+_(options|users)(\`|\")"
# NOTE: [^\`\"]+ intentionally allows hyphens and other characters valid in MySQL table names,
# broadening the previous [a-zA-Z0-9_]+ which would miss prefixes like "my-site_".
local table_name=""
# Use zgrep for .gz, grep for .sql.
if [[ "$db_file" == *.gz ]]; then
grep_cmd="zgrep"
fi
table_name=$("$grep_cmd" -m 1 -oE "${search_pattern}" "$db_file" | head -n 1)
if [[ -n "$table_name" ]]; then
# Keep only the quoted/backticked table identifier token (last whitespace-delimited field)
table_name="${table_name##* }"
# Remove surrounding quote/backtick and known suffix
table_name="${table_name%\`}"
table_name="${table_name%\"}"
table_name="${table_name#\`}"
table_name="${table_name#\"}"
prefix="${table_name%_options}"
prefix="${prefix%_users}"
fi
if [[ -n "$prefix" ]]; then
# Ensure it ends with an underscore if it doesn't already
if [[ "${prefix: -1}" != "_" ]]; then
prefix="${prefix}_"
fi
else
echo "Warning: Could not find common table pattern (like 'prefix_options') in the DB file." >&2 # Output warning to stderr
fi
# Return the extracted prefix (might be empty if not found)
echo "$prefix" # This is the only echo that should output the final prefix
}
# --- Validate Import Paths and Files ---
echo "Validating import directories and files..."
IMPORT_FORMAT="" # "single_zip" or "two_file"
SINGLE_ZIP_FILE=""
WP_ARCHIVE_FILE="" # Path to WP files archive (for two_file method)
DB_SOURCE_PATH="" # Path to the DB file (set differently for each method)
# Try detecting Single Zip format first
mapfile -d '' -t SINGLE_ZIP_CANDIDATES < <(find "${IMPORT_BASE_DIR}" -maxdepth 1 -type f -name "*.zip" -print0)
SINGLE_ZIP_COUNT=${#SINGLE_ZIP_CANDIDATES[@]}
if [[ "$SINGLE_ZIP_COUNT" -eq 1 ]] && is_directory_absent_or_empty "${WP_ARCHIVE_DIR}" && is_directory_absent_or_empty "${DB_IMPORT_DIR}"; then
# Found exactly one zip file in the base dir, and the two-file dirs are absent or empty
IMPORT_FORMAT="single_zip"
SINGLE_ZIP_FILE="${SINGLE_ZIP_CANDIDATES[0]}"
echo "PASSED: Detected Single Export Zip format: ${SINGLE_ZIP_FILE}"
elif [[ -d "${WP_ARCHIVE_DIR}" && -d "${DB_IMPORT_DIR}" ]]; then
# Check the original two-file method
# Find WP archive file
mapfile -d '' -t WP_ARCHIVE_FILE_CANDIDATES < <(find "${WP_ARCHIVE_DIR}" -maxdepth 1 -type f \( -name "*.zip" -o -name "*.tar.gz" -o -name "*.tgz" \) -print0)
WP_ARCHIVE_COUNT=${#WP_ARCHIVE_FILE_CANDIDATES[@]}
# Find DB file
mapfile -d '' -t DB_SOURCE_FILE_CANDIDATES < <(find "${DB_IMPORT_DIR}" -maxdepth 1 -type f \( -name "*.sql" -o -name "*.sql.gz" \) -print0)
DB_SOURCE_COUNT=${#DB_SOURCE_FILE_CANDIDATES[@]}
if [[ "$WP_ARCHIVE_COUNT" -eq 1 && "$DB_SOURCE_COUNT" -eq 1 ]]; then
IMPORT_FORMAT="two_file"
WP_ARCHIVE_FILE="${WP_ARCHIVE_FILE_CANDIDATES[0]}"
DB_SOURCE_PATH="${DB_SOURCE_FILE_CANDIDATES[0]}" # Set DB path directly for this format
echo "PASSED: Detected Two-File format."
echo " WordPress archive: ${WP_ARCHIVE_FILE}"
echo " Database file: ${DB_SOURCE_PATH}"
fi
fi
# Validation Failure
if [[ -z "$IMPORT_FORMAT" ]]; then
echo "FAILED: Could not detect a valid import format."
echo "Please ensure you have either:"
echo " - Exactly one .zip file in ${IMPORT_BASE_DIR} (and no subdirectories like 'root-directory' or 'database-file')."
echo " - OR Exactly one archive (.zip, .tar.gz, .tgz) in ${WP_ARCHIVE_DIR} AND exactly one database file (.sql, .sql.gz) in ${DB_IMPORT_DIR}."
exit 1
fi
# --- Extraction Step (Conditional) ---
echo "Extracting content..."
# Clean up any previous extraction attempt
rm -rf "${WP_EXTRACTED_PATH}"
mkdir -p "${WP_EXTRACTED_PATH}"
EXTRACT_STATUS=1 # Default to failure
if [[ "$IMPORT_FORMAT" == "single_zip" ]]; then
echo "Extracting single zip file: ${SINGLE_ZIP_FILE}"
if validate_zip_archive_paths "${SINGLE_ZIP_FILE}"; then
unzip -q "${SINGLE_ZIP_FILE}" -d "${WP_EXTRACTED_PATH}"
EXTRACT_STATUS=$?
else
EXTRACT_STATUS=1
fi
if [[ $EXTRACT_STATUS -eq 0 ]]; then
# Find exactly one database dump file (.sql or .sql.gz) within the extracted content (deterministic order)
mapfile -d '' -t DB_SOURCE_CANDIDATES < <(find "${WP_EXTRACTED_PATH}" -maxdepth 1 -type f \( -name "*.sql" -o -name "*.sql.gz" \) -print0 | sort -z)
if [[ ${#DB_SOURCE_CANDIDATES[@]} -ne 1 ]]; then
echo "FAILED: Could not find exactly one database file (.sql or .sql.gz) within the extracted single zip content in ${WP_EXTRACTED_PATH}"
EXTRACT_STATUS=1 # Mark as failure
else
DB_SOURCE_PATH="${DB_SOURCE_CANDIDATES[0]}" # Set DB path for single_zip format
echo "PASSED: Found database file within extracted content: ${DB_SOURCE_PATH}"
fi
fi
elif [[ "$IMPORT_FORMAT" == "two_file" ]]; then
echo "Extracting WordPress archive file: ${WP_ARCHIVE_FILE}"
if [[ "${WP_ARCHIVE_FILE}" == *.zip ]]; then
if validate_zip_archive_paths "${WP_ARCHIVE_FILE}"; then
unzip -q "${WP_ARCHIVE_FILE}" -d "${WP_EXTRACTED_PATH}"
EXTRACT_STATUS=$?
else
EXTRACT_STATUS=1
fi
elif [[ "${WP_ARCHIVE_FILE}" == *.tar.gz || "${WP_ARCHIVE_FILE}" == *.tgz ]]; then
tar -zxf "${WP_ARCHIVE_FILE}" -C "${WP_EXTRACTED_PATH}"
EXTRACT_STATUS=$?
else
echo "FAILED: Unrecognized archive format for ${WP_ARCHIVE_FILE}"
EXTRACT_STATUS=1
fi
# DB_SOURCE_PATH is already set for two_file format
fi
# Check Extraction Status
if [[ $EXTRACT_STATUS -ne 0 ]]; then
echo "FAILED: Extraction process failed."
rm -rf "${WP_EXTRACTED_PATH}" # Clean up failed extraction
exit 1
fi
# --- Locate wp-config.php and Determine Source Path (Common Logic) ---
# This logic should work for both formats as wp-config.php will be inside WP_EXTRACTED_PATH
WP_CONFIG_REL_PATH=$(find "${WP_EXTRACTED_PATH}" -name "wp-config.php" -printf "%P\n" | head -n 1)
if [[ -z "$WP_CONFIG_REL_PATH" ]]; then
echo "FAILED: wp-config.php not found within the extracted content in ${WP_EXTRACTED_PATH}"
rm -rf "${WP_EXTRACTED_PATH}" # Clean up
exit 1
fi
# Determine the actual source path for WP files
if [[ "$WP_CONFIG_REL_PATH" == "wp-config.php" ]]; then
WP_FILES_SOURCE_PATH="${WP_EXTRACTED_PATH}"
else
SUBDIR=$(dirname "$WP_CONFIG_REL_PATH")
WP_FILES_SOURCE_PATH="${WP_EXTRACTED_PATH}/${SUBDIR}"
fi
echo "PASSED: Archive extracted. WordPress source path set to: ${WP_FILES_SOURCE_PATH}"
# --- Extract Table Prefix from Database File ---
# DB_SOURCE_PATH is now set correctly for both formats
echo "Extracting table prefix from database file: ${DB_SOURCE_PATH}"
PREFIX=$(extract_prefix_from_db "$DB_SOURCE_PATH")
if [[ -z "$PREFIX" ]]; then
echo "FAILED: Could not automatically determine table prefix from database file: ${DB_SOURCE_PATH}"
echo "Please ensure the database dump contains standard WordPress tables like 'wp_options'/'yourprefix_options' or 'wp_users'/'yourprefix_users'."
rm -rf "${WP_EXTRACTED_PATH}" # Clean up
exit 1 # Exit if DB extraction fails
fi
echo "PASSED: Determined table prefix from database: ${PREFIX}"
# --- End Prefix Extraction ---
# --- Extract Information from wp-config.php ---
echo "Extracting site information from wp-config.php..."
WP_CONFIG_PATH="${WP_FILES_SOURCE_PATH}/wp-config.php" # Use the determined source path
# Extract WP_HOME or WP_SITEURL
SITE_URL_RAW=$(extract_define 'WP_HOME')
if [[ -z "$SITE_URL_RAW" ]]; then
SITE_URL_RAW=$(extract_define 'WP_SITEURL')
fi
if [[ -z "$SITE_URL_RAW" ]]; then
echo "FAILED: Could not extract WP_HOME or WP_SITEURL from wp-config.php."
exit 1
fi
# Extract domain from URL (remove http(s):// and potential trailing slash)
SITE_URL=$(echo "$SITE_URL_RAW" | sed -E 's#^https?://##; s#/$##') # Use the clean domain extracted from URL
# Extract DB Charset (optional, for reference)
DB_CHARSET=$(extract_define 'DB_CHARSET')
if [[ -z "$DB_CHARSET" ]]; then
echo "Warning: Could not extract DB_CHARSET from wp-config.php. Using default utf8mb4."
DB_CHARSET="utf8mb4" # Default if not found
fi
echo "Extracted Information:"
echo " Domain (SITE_URL): ${SITE_URL}"
echo " Table Prefix (PREFIX): ${PREFIX}" # Already extracted from DB
echo " DB Charset: ${DB_CHARSET}"
sleep 1 # Short pause
# --- Confirmation and Correction Step ---
while true; do
echo ""
echo "-------------------------------------------------------"
echo "${BOLD}Extracted Site Information:${NORMAL}"
echo "-------------------------------------------------------"
echo " Site URL: ${SITE_URL}"
echo " DB Prefix: ${PREFIX}"
echo " DB Charset: ${DB_CHARSET}"
echo "-------------------------------------------------------"
echo ""
read -p "Are these details correct? ([Y]es/[C]hange/[E]xit): " confirm_details
case $confirm_details in
[Yy]* )
echo "Details confirmed."
sleep 1
break # Exit the confirmation loop and proceed
;;
[Cc]* )
echo "Please enter the correct values:"
# Site URL input with validation
while true; do
new_site_url=$(prompt_input "Enter correct Site URL" "${SITE_URL}" 300)
if [[ -n "$new_site_url" ]]; then
if validate_url "$new_site_url"; then
SITE_URL="$new_site_url"
break
else
echo "Invalid URL format. Please use format: https://example.com or http://example.com"
fi
else
break # Keep existing value
fi
done
# DB Prefix input with validation
new_prefix=$(prompt_input "Enter correct DB Prefix" "${PREFIX}" 300 "^[a-zA-Z0-9_]+$" true)
if [[ -n "$new_prefix" ]]; then
# Ensure prefix ends with _ if not empty
if [[ "${new_prefix: -1}" != "_" ]]; then
new_prefix="${new_prefix}_"
echo " (Appended '_' to prefix)"
fi
PREFIX="$new_prefix"
fi
# DB Charset input with validation
new_db_charset=$(prompt_input "Enter correct DB Charset" "${DB_CHARSET}" 300 "^[a-zA-Z0-9_]+$" true)
if [[ -n "$new_db_charset" ]]; then
DB_CHARSET="$new_db_charset"
fi
echo "Values updated. Please review again."
sleep 1
;; # Loop back to show updated values
[Ee]* )
echo "Exiting script as requested."
# Clean up extracted files before exiting
rm -rf "${WP_EXTRACTED_PATH}"
exit 0
;;
* )
echo "Invalid input. Please enter 'y', 'c', or 'e'."
;;
esac
done
# --- End Confirmation and Correction Step ---
# Derive DOMAIN from the final SITE_URL (after any user corrections)
DOMAIN="${SITE_URL}"
# Cloudflare API Settings
# Set Cloudflare settings for the domain using the Cloudflare API
configure_cloudflare_settings "${DOMAIN}"
# Verify if the extracted domain is already configured
if grep -Fxq "\"${DOMAIN}\"" /home/EngineScript/sites-list/sites.sh; then
echo -e "\n\n${BOLD}Pre-import Check: Failed${NORMAL}\n\nDomain ${DOMAIN} (extracted from wp-config.php) is already configured in EngineScript.\n\nIf you want to replace it, please remove the existing domain first using the ${BOLD}es.menu${NORMAL} command.\n\n"
exit 1
else
echo "${BOLD}Pre-import Check: Passed${NORMAL}"
fi
# Canonical URL used for import/search-replace workflows.
# Currently source and target are the same during import.
NEW_URL="https://${SITE_URL}" # Assume https for consistency
# Logging
LOG_FILE="/var/log/EngineScript/vhost-import.log"
exec > >(tee -a "${LOG_FILE}") 2>&1
if [ "${IMPORT_FORMAT}" = "single_zip" ]; then
echo "Starting domain import for ${DOMAIN} from single ZIP ${SINGLE_ZIP_FILE} at $(date)"
elif [ "${IMPORT_FORMAT}" = "two_file" ]; then
echo "Starting domain import for ${DOMAIN} from archive ${WP_ARCHIVE_FILE} and DB ${DB_SOURCE_PATH} at $(date)"
else
echo "Starting domain import for ${DOMAIN} (format: ${IMPORT_FORMAT}) with inputs ZIP=${SINGLE_ZIP_FILE}, archive=${WP_ARCHIVE_FILE}, DB=${DB_SOURCE_PATH} at $(date)"
fi
# Continue the installation
# Create nginx vhost configuration files
create_nginx_vhost "${DOMAIN}"
# Create and install SSL certificates
create_ssl_certificate "${DOMAIN}"
# Print date for logs
echo "System Date: $(date)"
# --- Database and File Handling ---
# Table Prefix is already extracted and stored in $PREFIX
# Domain Creation Variables (Generate *new* secure credentials for this server)
source /usr/local/bin/enginescript/enginescript-variables.txt
generate_import_db_name "${DOMAIN}" || exit 1
SDB="${ES_DB_NAME}"
SUSR="${RAND_CHAR16}"
SPS="${RAND_CHAR32}"
# Domain Database Credentials (Store the *new* credentials)
write_credentials_file "/home/EngineScript/mysql-credentials" "${DOMAIN}" "${SDB}" "${SUSR}" "${SPS}"
echo "Generated new MySQL database credentials for ${SITE_URL}."
# Create *new* database and user (Use extracted charset if needed, though default is usually fine)
# Validate SQL inputs before interpolation to prevent SQL injection/syntax issues.
DB_CHARSET="${DB_CHARSET:-utf8mb4}"
validate_import_credentials "${DB}" "${USR}" "${PSWD}" "${DB_CHARSET}" || exit 1
DB_CHARSET="${ES_DB_CHARSET_VALIDATED}"
DB_COLLATION="${ES_DB_COLLATION}"
execute_import_sql "${DB}" "${USR}" "${PSWD}" "${DB_CHARSET}" "${DB_COLLATION}"
# Create backup directories
create_backup_directories "${SITE_URL}"
# Site Root
mkdir -p "/var/www/sites/${SITE_URL}/html"
TARGET_WP_PATH="/var/www/sites/${SITE_URL}/html"
# Create domain log directories and files
create_domain_logs "${SITE_URL}"
# --- Import WordPress Files ---
echo "Copying WordPress files from ${WP_FILES_SOURCE_PATH} to ${TARGET_WP_PATH}..." # Use the determined source path
# Use rsync for efficiency and better handling of permissions/ownership later
rsync -av --exclude 'wp-config.php' "${WP_FILES_SOURCE_PATH}/" "${TARGET_WP_PATH}/"
# Ensure correct ownership before proceeding with WP-CLI
chown -R www-data:www-data "${TARGET_WP_PATH}"
echo "WordPress files copied."
# Create Extra WordPress Directories
# WordPress often doesn't include these directories by default, despite them being used or checked in the Health Check plugin.
create_extra_wp_dirs "${SITE_URL}"
# --- Create wp-config.php ---
echo "Creating new wp-config.php with EngineScript settings..."
cp -rf "/usr/local/bin/enginescript/config/var/www/wordpress/wp-config.php" "${TARGET_WP_PATH}/wp-config.php"
# Use *new* DB credentials and *original* prefix
sed -i \
-e "s|SEDWPDB|${DB}|g" \
-e "s|SEDWPUSER|${USR}|g" \
-e "s|SEDWPPASS|${PSWD}|g" \
-e "s|SEDPREFIX_|${PREFIX}|g" \
-e "s|SEDURL|${SITE_URL}|g" \
-e "s|define( 'DB_CHARSET', 'utf8mb4' );|define( 'DB_CHARSET', '${DB_CHARSET}' );|g" \
"${TARGET_WP_PATH}/wp-config.php" # Use original prefix and extracted DB Charset
# Configure Redis for WordPress
configure_redis "${SITE_URL}" "${TARGET_WP_PATH}/wp-config.php"
# WP Salt Creation (Generate new salts)
fetch_wp_salts "${TARGET_WP_PATH}/wp-config.php"
# Configure wp-config.php settings
configure_wpconfig_settings "${SITE_URL}" "${TARGET_WP_PATH}/wp-config.php"
# Create robots.txt file
create_robots_txt "${SITE_URL}" "${TARGET_WP_PATH}"
# --- Import Database ---
echo "Importing database from ${DB_SOURCE_PATH}..." # DB_SOURCE_PATH is already set
cd "${TARGET_WP_PATH}" # WP-CLI needs to be in the WP root
# Handle compressed DB (using DB_SOURCE_PATH)
IMPORT_FILE_PATH="${DB_SOURCE_PATH}"
if [[ "${DB_SOURCE_PATH}" == *.gz ]]; then
echo "Decompressing database..."
IMPORT_FILE_PATH="/tmp/${DOMAIN}_db_import.sql"
gunzip -c "${DB_SOURCE_PATH}" > "${IMPORT_FILE_PATH}"
if [[ $? -ne 0 ]]; then
echo "Failed to decompress database file. Exiting."
exit 1
fi
fi
# Import the database using WP-CLI
wp db import "${IMPORT_FILE_PATH}" --allow-root
if [[ $? -ne 0 ]]; then
echo "Failed to import database. Please check the database file and credentials. Exiting."
# Clean up temp file if created
if [[ "${DB_SOURCE_PATH}" == *.gz ]]; then
rm -f "${IMPORT_FILE_PATH}"
fi
exit 1
fi
echo "Database imported successfully."
# Clean up temp file if created
if [[ "${DB_SOURCE_PATH}" == *.gz ]]; then
rm -f "${IMPORT_FILE_PATH}"
fi
# --- Post Import Tasks ---
# Search and Replace URLs
echo "Running search-replace for URL consistency in the database..."
echo "Ensuring URL is '${NEW_URL}'"
HTTPS_ORIGINAL_URL="${NEW_URL}"
HTTP_ORIGINAL_URL="${HTTPS_ORIGINAL_URL/#https:\/\//http://}"
run_url_search_replace_if_present() {
local original_url="$1"
# Run search-replace directly; --report-changed-only will emit output only for changed rows.
wp search-replace "${original_url}" "${NEW_URL}" --all-tables --report-changed-only --allow-root
return
}
run_url_search_replace_if_present "${HTTP_ORIGINAL_URL}"
run_url_search_replace_if_present "${HTTPS_ORIGINAL_URL}"
# Flush Cache and Rewrite Rules
clear_wordpress_caches
# Install and activate required WordPress plugins
install_required_wp_plugins
# Install extra WordPress plugins if enabled
if [[ "${INSTALL_EXTRA_WP_PLUGINS}" == "1" ]]; then
install_extra_wp_plugins
else
echo "Skipping extra WordPress plugins installation (disabled in config)..."
fi
# Install EngineScript custom plugins if enabled
install_enginescript_custom_plugins "${SITE_URL}"
# Clear WordPress caches, transients, and rewrite rules
clear_wordpress_caches
# Enable Redis Cache via WP-CLI
if wp plugin is-active redis-cache --allow-root; then
echo "Enabling Redis object cache..."
wp redis enable --allow-root
else
echo "Warning: Redis Cache plugin not active. Skipping 'wp redis enable'."
fi
# Set permalink structure for FastCGI Cache (Good practice)
# Changing the permalink structure would probably catastrophically break existing sites and their SEO if they use a different structure, so this is commented out by default.
#echo "Setting permalink structure to /%category%/%postname%/..."
#wp option update permalink_structure '/%category%/%postname%/' --allow-root
#flush_wordpress_rewrites
# Final File Permissions
echo "Setting final file permissions..."
# Set ownership first
chown -R www-data:www-data "${TARGET_WP_PATH}"
# Set directory and file permissions
find "${TARGET_WP_PATH}" -type d -print0 | sudo xargs -0 chmod 0755
find "${TARGET_WP_PATH}" -type f -print0 | sudo xargs -0 chmod 0644
# Secure specific files
chmod 600 "${TARGET_WP_PATH}/wp-config.php"
# Ensure wp-cron is executable if it exists
if [[ -f "${TARGET_WP_PATH}/wp-cron.php" ]]; then
chmod +x "${TARGET_WP_PATH}/wp-cron.php"
fi
clear
# Perform site backup
perform_site_backup "${SITE_URL}" "${TARGET_WP_PATH}"
# Display final credentials summary
display_credentials_summary "${SITE_URL}" "${DB}" "${PREFIX}" "${USR}" "${PSWD}"
# Restart Services
/usr/local/bin/enginescript/scripts/functions/alias/alias-restart.sh
echo ""
echo "============================================================="
echo ""
echo " Domain import completed for ${SITE_URL}."
echo ""
echo " Your domain should be available now at:"
echo " https://${SITE_URL}"
echo ""
echo " ${BOLD}ACTION REQUIRED:${NORMAL}"
echo " Please open your web browser and thoroughly verify the site functionality."
echo " Check pages, posts, images, forms, and plugin features."
echo ""
echo " If the site is NOT working correctly:"
echo " - Answer 'n' to the prompt below."
echo " - The script will exit WITHOUT removing temporary import files."
echo " - You can then investigate the issue."
echo " - Afterwards, use the main EngineScript menu (es.menu) -> Domain Configuration -> Remove Domain"
echo " to clean up the partially imported site."
echo ""
echo "============================================================="
echo ""
# --- Site Verification Step ---
echo ""
if prompt_yes_no "Is the imported site at https://${SITE_URL} working correctly?" "n" 600; then
echo "Great! Proceeding with cleanup..."
# Move import files to completed-backups directory
BACKUP_DIR="/home/EngineScript/temp/site-import-completed-backups"
mkdir -p "${BACKUP_DIR}"
if [[ "${IMPORT_FORMAT}" == "two_file" ]] && [[ -n "${WP_ARCHIVE_FILE}" ]] && [[ -f "${WP_ARCHIVE_FILE}" ]]; then
mv "${WP_ARCHIVE_FILE}" "${BACKUP_DIR}/"
echo "Moved ${WP_ARCHIVE_FILE} to ${BACKUP_DIR}/"
fi
if [[ "${IMPORT_FORMAT}" == "single_zip" ]] && [[ -n "${SINGLE_ZIP_FILE}" ]] && [[ -f "${SINGLE_ZIP_FILE}" ]]; then
mv "${SINGLE_ZIP_FILE}" "${BACKUP_DIR}/"
echo "Moved ${SINGLE_ZIP_FILE} to ${BACKUP_DIR}/"
fi
if [[ -n "${DB_SOURCE_PATH}" ]] && [[ -f "${DB_SOURCE_PATH}" ]]; then
mv "${DB_SOURCE_PATH}" "${BACKUP_DIR}/"
echo "Moved ${DB_SOURCE_PATH} to ${BACKUP_DIR}/"
fi
rm -rf "${WP_EXTRACTED_PATH}" # Remove the temporary extracted directory
echo "Cleanup complete. Import files moved to ${BACKUP_DIR}."
sleep 2 # Short pause after cleanup message
else
echo "Site verification failed by user."
echo "Removing temporary extracted files directory: ${WP_EXTRACTED_PATH}"
rm -rf "${WP_EXTRACTED_PATH}" # Remove only the extracted directory
if [[ "${IMPORT_FORMAT}" == "two_file" ]]; then
echo "Original archive file (${WP_ARCHIVE_FILE}) in ${WP_ARCHIVE_DIR} and database file (${DB_SOURCE_PATH}) in ${DB_IMPORT_DIR} will NOT be removed."
else
echo "Original import file (${SINGLE_ZIP_FILE}) in ${IMPORT_BASE_DIR} will NOT be removed."
fi
echo "Please investigate the issue and use 'es.menu' to remove the domain '${SITE_URL}' when ready."
echo "Exiting script now."
exit 1 # Exit without full cleanup
fi
# --- End Site Verification Step ---
echo "Returning to main menu..." # Message if 'y' was chosen
sleep 5
# Exit cleanly (only reached if 'y' was chosen)
exit 0