-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtagarr_migrate.sh
More file actions
executable file
·622 lines (561 loc) · 22.8 KB
/
tagarr_migrate.sh
File metadata and controls
executable file
·622 lines (561 loc) · 22.8 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
#!/usr/bin/env bash
# -----------------------------------------------------------------------------
# Tagarr — Config Migration Tool
#
# Migrates any tagarr config file to the latest format.
#
# What it does:
# - Detects which config type from the filename (tagarr.conf,
# tagarr_import.conf, tagarr_recover.conf, etc.)
# - Downloads the matching conf.sample from GitHub automatically
# - Creates a NEW config with all your values preserved:
# API keys, release groups (including discovered ones), webhooks,
# quality/audio filters, recovery settings, etc.
# - Adds any new settings with safe defaults
# - Lists which new settings were added so you can review them
#
# What it does NOT do:
# - Never modifies your original config file (backed up to tagarr_backups/)
# - Never enables new features automatically
#
# Requirements:
# - curl (for downloading from GitHub)
# - Your existing tagarr config file (any version)
#
# Usage:
# ./tagarr_migrate.sh /path/to/tagarr_import.conf
# ./tagarr_migrate.sh /path/to/tagarr.conf
# ./tagarr_migrate.sh /path/to/tagarr_recover.conf
# ./tagarr_migrate.sh --no-update /path/to/any_tagarr_config.conf
#
# --no-update Skip automatic self-update from GitHub
#
# Supported configs:
# tagarr.conf, tagarr_import.conf, tagarr_import_sonarr.conf,
# tagarr_recover.conf, tagarr_remove.conf, tagarr_rename.conf,
# tagarr_list.conf
#
# Output:
# Backs up your config to tagarr_backups/ with a date stamp, then
# replaces it with the migrated version. To review or roll back:
# diff tagarr_backups/tagarr_import.conf.2026-04-17 tagarr_import.conf
# cp tagarr_backups/tagarr_import.conf.2026-04-17 tagarr_import.conf
#
# Author: prophetSe7en
# -----------------------------------------------------------------------------
set -euo pipefail
SCRIPT_PATH="$(readlink -f "$0")"
SCRIPT_DIR=$(dirname "$SCRIPT_PATH")
GITHUB_BASE="https://raw.githubusercontent.com/ProphetSe7en/tagarr/main"
SELF_URL="${GITHUB_BASE}/tagarr_migrate.sh"
# --- Logging ---
# Writes timestamped events to logs/tagarr_migrate.log next to the script.
# Failure-tolerant: if the log dir isn't writable, log calls silently skip.
# Rotates at 2 MiB to keep one .old backup (matches tagarr.sh's pattern).
LOG_FILE="${SCRIPT_DIR}/logs/tagarr_migrate.log"
log() {
local msg="$1"
mkdir -p "$(dirname "$LOG_FILE")" 2>/dev/null || return 0
if [ -f "$LOG_FILE" ]; then
local size
size=$(stat -c%s "$LOG_FILE" 2>/dev/null || echo 0)
[ "$size" -gt 2097152 ] && mv "$LOG_FILE" "${LOG_FILE}.old" 2>/dev/null
fi
echo "$(date '+%Y-%m-%d %H:%M:%S') $msg" >> "$LOG_FILE" 2>/dev/null || true
}
# --- Parse flags ---
NO_UPDATE=false
ARGS=()
for arg in "$@"; do
case "$arg" in
--no-update) NO_UPDATE=true ;;
--all) RUN_ALL=true ;;
--help|-h)
echo "Usage: $0 [--no-update] [/path/to/tagarr_config.conf]"
echo ""
echo "Migrates tagarr configs to the latest format. Optionally"
echo "auto-updates tagarr scripts when enabled in tagarr_migrate.conf."
echo ""
echo "With no arguments, migrates every tagarr config found in:"
echo " - the same directory as tagarr_migrate.sh, AND"
echo " - every AUTOUPDATE_<SCRIPT>_DIR set in tagarr_migrate.conf"
echo ""
echo "Options:"
echo " --no-update Skip self-update of this migration script"
echo " --all No-op alias (kept for compatibility)"
echo ""
echo "Supported configs: tagarr.conf, tagarr_import.conf,"
echo " tagarr_import_sonarr.conf, tagarr_recover.conf,"
echo " tagarr_remove.conf, tagarr_rename.conf, tagarr_list.conf,"
echo " tagarr_migrate.conf"
echo ""
echo "To enable opt-in script auto-update, see:"
echo " https://raw.githubusercontent.com/ProphetSe7en/tagarr/main/tagarr_migrate.conf.sample"
exit 0
;;
*) ARGS+=("$arg") ;;
esac
done
OLD_CONFIG="${ARGS[0]:-}"
RUN_ALL="${RUN_ALL:-false}"
# --- Self-update: check for newer version of this script ---
# Runs BEFORE config detection so old scripts get auto-detect on re-exec
if [ "$NO_UPDATE" = "false" ] && [ "${TAGARR_MIGRATE_NO_UPDATE:-}" != "1" ]; then
latest=$(mktemp)
if curl -fsSL "$SELF_URL" -o "$latest" 2>/dev/null; then
if ! cmp -s "$SCRIPT_PATH" "$latest"; then
echo "Updating migration script to latest version..."
log "migrate script self-updated (re-exec to pick up new version)"
cp "$latest" "$SCRIPT_PATH"
chmod +x "$SCRIPT_PATH"
rm -f "$latest"
TAGARR_MIGRATE_NO_UPDATE=1 exec "$SCRIPT_PATH" "$@"
fi
fi
rm -f "$latest"
fi
# --- Shared: read tagarr_migrate.conf once into global scope. ---
# Variables like AUTOUPDATE_TAGARR_IMPORT / AUTOUPDATE_TAGARR_IMPORT_DIR
# become available to both auto_update_scripts and the config-scan logic.
MIGRATE_CONF="${SCRIPT_DIR}/tagarr_migrate.conf"
if [ -f "$MIGRATE_CONF" ]; then
# shellcheck disable=SC1090
source "$MIGRATE_CONF"
fi
# --- Shared: script → (flag_var, dir_var) mapping. Format: "<sh>|<flag>|<dir>" ---
SCRIPT_ENTRIES=(
"tagarr.sh|AUTOUPDATE_TAGARR|AUTOUPDATE_TAGARR_DIR"
"tagarr_import.sh|AUTOUPDATE_TAGARR_IMPORT|AUTOUPDATE_TAGARR_IMPORT_DIR"
"tagarr_import_sonarr.sh|AUTOUPDATE_TAGARR_IMPORT_SONARR|AUTOUPDATE_TAGARR_IMPORT_SONARR_DIR"
"tagarr_list.sh|AUTOUPDATE_TAGARR_LIST|AUTOUPDATE_TAGARR_LIST_DIR"
"tagarr_recover.sh|AUTOUPDATE_TAGARR_RECOVER|AUTOUPDATE_TAGARR_RECOVER_DIR"
"tagarr_remove.sh|AUTOUPDATE_TAGARR_REMOVE|AUTOUPDATE_TAGARR_REMOVE_DIR"
"tagarr_rename.sh|AUTOUPDATE_TAGARR_RENAME|AUTOUPDATE_TAGARR_RENAME_DIR"
)
# --- Shared: the only config filenames we recognize as tagarr configs. ---
# MUST stay in sync with the validator `case` block further down. Keeps
# the --all scan from accidentally picking up unrelated files that happen
# to match `tagarr*.conf` (e.g. a user's own tagarr_custom.conf) and
# failing the recursive migration call on the validator.
VALID_TAGARR_CONFS=(
tagarr.conf
tagarr_import.conf
tagarr_import_sonarr.conf
tagarr_recover.conf
tagarr_remove.conf
tagarr_rename.conf
tagarr_list.conf
tagarr_migrate.conf
)
# --- Auto-update tagarr scripts (opt-in via tagarr_migrate.conf) ---
# Reads AUTOUPDATE_<SCRIPT>=true flags; only runs when config exists.
# Guarded against --all recursion via TAGARR_MIGRATE_SKIP_AUTO_UPDATE.
auto_update_scripts() {
[ -f "$MIGRATE_CONF" ] || return 0
if ! command -v jq >/dev/null 2>&1; then
echo "WARN: auto-update skipped — jq is required but not installed"
log "WARN: auto-update skipped (jq not installed)"
return 0
fi
local versions_url="${GITHUB_BASE}/versions.json"
local remote_manifest
remote_manifest=$(curl -fsSL --max-time 10 "$versions_url" 2>/dev/null) || {
echo "WARN: auto-update skipped — failed to fetch versions.json"
log "WARN: auto-update skipped (failed to fetch versions.json)"
return 0
}
local -a updated=() skipped=() failed=()
local any_enabled=false
local entry script flag_var dir_var enabled target_dir script_path
local local_version remote_version tmp
for entry in "${SCRIPT_ENTRIES[@]}"; do
IFS='|' read -r script flag_var dir_var <<<"$entry"
enabled="${!flag_var:-false}"
[ "$enabled" = "true" ] || continue
any_enabled=true
target_dir="${!dir_var:-}"
[ -z "$target_dir" ] && target_dir="$SCRIPT_DIR"
script_path="${target_dir}/${script}"
if [ ! -f "$script_path" ]; then
skipped+=("$script (not found at $target_dir)")
continue
fi
local_version=$(grep -E '^SCRIPT_VERSION=' "$script_path" | head -1 | sed -E 's/.*"([^"]+)".*/\1/')
remote_version=$(echo "$remote_manifest" | jq -r --arg s "$script" '.[$s] // ""')
if [ -z "$remote_version" ]; then
skipped+=("$script (not listed in versions.json)")
continue
fi
if [ "$local_version" = "$remote_version" ]; then
skipped+=("$script (v$local_version — already current)")
continue
fi
# Only update when remote is strictly newer (sort -V version sort)
if [ "$(printf '%s\n%s\n' "$remote_version" "$local_version" | sort -V 2>/dev/null | tail -1)" != "$remote_version" ]; then
skipped+=("$script (local v$local_version ahead of remote v$remote_version)")
continue
fi
echo "Updating $script: v$local_version -> v$remote_version ($target_dir)"
tmp=$(mktemp)
if ! curl -fsSL "${GITHUB_BASE}/${script}" -o "$tmp" 2>/dev/null; then
failed+=("$script (download failed)")
log "script update FAILED: $script (download failed from ${GITHUB_BASE}/${script})"
rm -f "$tmp"
continue
fi
# Sanity 1: downloaded file must start with a shebang
if ! head -1 "$tmp" | grep -q '^#!'; then
failed+=("$script (downloaded file not a script)")
log "script update FAILED: $script (downloaded file not a script — no shebang)"
rm -f "$tmp"
continue
fi
# Sanity 2: must carry our SCRIPT_VERSION= signature. Every tagarr
# script listed in versions.json has this marker — absence means
# GitHub returned something else (hijacked mirror, wrong branch,
# partial download).
if ! grep -q '^SCRIPT_VERSION=' "$tmp"; then
failed+=("$script (downloaded file missing SCRIPT_VERSION marker)")
log "script update FAILED: $script (downloaded file missing SCRIPT_VERSION marker)"
rm -f "$tmp"
continue
fi
# Backup to tagarr_backups/ with datestamp before replacing
backup_dir="${target_dir}/tagarr_backups"
mkdir -p "$backup_dir" 2>/dev/null
cp "$script_path" "${backup_dir}/${script}.$(date '+%Y-%m-%d')"
# Overwrite in place to preserve existing permissions/ownership
cat "$tmp" > "$script_path"
rm -f "$tmp"
updated+=("$script: v$local_version -> v$remote_version")
log "script updated: $script v$local_version -> v$remote_version in $target_dir"
done
[ "$any_enabled" = "false" ] && return 0
log "scripts: ${#updated[@]} updated, ${#skipped[@]} current/skipped, ${#failed[@]} failed"
echo ""
echo "Script auto-update summary:"
if [ ${#updated[@]} -gt 0 ]; then
echo " Updated (${#updated[@]}):"
for x in "${updated[@]}"; do echo " - $x"; done
echo " Previous versions backed up to tagarr_backups/ with date stamp."
fi
if [ ${#skipped[@]} -gt 0 ]; then
echo " Skipped (${#skipped[@]}):"
for x in "${skipped[@]}"; do echo " - $x"; done
fi
if [ ${#failed[@]} -gt 0 ]; then
echo " Failed (${#failed[@]}):"
for x in "${failed[@]}"; do echo " - $x"; done
fi
echo ""
}
if [ "${TAGARR_MIGRATE_SKIP_AUTO_UPDATE:-}" != "1" ]; then
log "run start"
auto_update_scripts
# Discovery notice for the opt-in auto-update feature. Shown once per
# invocation when tagarr_migrate.conf does not exist. Silent once the
# user has opted in (or deliberately ignored by keeping a commented
# copy in place). Guarded from --all recursion by the outer check.
if [ ! -f "${SCRIPT_DIR}/tagarr_migrate.conf" ]; then
echo "Tip: opt-in auto-update of tagarr scripts is available."
echo "See: https://raw.githubusercontent.com/ProphetSe7en/tagarr/main/tagarr_migrate.conf.sample"
echo ""
fi
fi
# --- No config specified → default to "migrate everything found" ---
# Equivalent to the old --all flag. Scans SCRIPT_DIR plus every
# AUTOUPDATE_<SCRIPT>_DIR set in tagarr_migrate.conf, regardless of
# whether the corresponding AUTOUPDATE flag is true. A user who points
# a script to a custom dir usually keeps its config alongside it, so
# that dir is always a migration target.
if [ -z "$OLD_CONFIG" ] && [ "$RUN_ALL" != "true" ]; then
RUN_ALL=true
fi
if [ "$RUN_ALL" = "true" ]; then
# Collect dirs to scan: SCRIPT_DIR + every AUTOUPDATE_*_DIR set
scan_dirs=("$SCRIPT_DIR")
for entry in "${SCRIPT_ENTRIES[@]}"; do
IFS='|' read -r _sn _fl dir_var <<<"$entry"
val="${!dir_var:-}"
if [ -n "$val" ] && [ -d "$val" ]; then
already_in=false
for d in "${scan_dirs[@]}"; do
[ "$d" = "$val" ] && already_in=true && break
done
[ "$already_in" = "false" ] && scan_dirs+=("$val")
fi
done
# Only pick up files whose basenames match the VALID_TAGARR_CONFS list.
# Avoids --all choking if a user has unrelated `tagarr*.conf` files.
configs=()
for dir in "${scan_dirs[@]}"; do
for name in "${VALID_TAGARR_CONFS[@]}"; do
[ -f "$dir/$name" ] && configs+=("$dir/$name")
done
done
if [ ${#configs[@]} -eq 0 ]; then
echo "No tagarr configs found in:"
for dir in "${scan_dirs[@]}"; do echo " $dir"; done
exit 1
fi
if [ ${#scan_dirs[@]} -gt 1 ]; then
echo "Scanning ${#scan_dirs[@]} directories, found ${#configs[@]} configs..."
else
echo "Migrating ${#configs[@]} configs..."
fi
echo ""
update_flag=""
[ "$NO_UPDATE" = "true" ] && update_flag="--no-update"
for f in "${configs[@]}"; do
TAGARR_MIGRATE_NO_UPDATE=1 TAGARR_MIGRATE_SKIP_AUTO_UPDATE=1 "$SCRIPT_PATH" $update_flag "$f"
echo ""
done
log "configs: ${#configs[@]} scanned across ${#scan_dirs[@]} dir(s)"
log "run complete"
exit 0
fi
if [ ! -f "$OLD_CONFIG" ]; then
echo "ERROR: Config not found: $OLD_CONFIG"
echo ""
echo "Usage: $0 /path/to/tagarr_config.conf"
exit 1
fi
# --- Determine sample filename from config filename ---
config_basename=$(basename "$OLD_CONFIG")
sample_name="${config_basename%.conf}.conf.sample"
# Validate it's a known tagarr config
case "$config_basename" in
tagarr.conf|tagarr_import.conf|tagarr_import_sonarr.conf|\
tagarr_recover.conf|tagarr_remove.conf|tagarr_rename.conf|\
tagarr_list.conf|tagarr_migrate.conf)
;;
*)
echo "ERROR: Unrecognized config file: $config_basename"
echo ""
echo "Supported: tagarr.conf, tagarr_import.conf,"
echo " tagarr_import_sonarr.conf, tagarr_recover.conf,"
echo " tagarr_remove.conf, tagarr_rename.conf, tagarr_list.conf,"
echo " tagarr_migrate.conf"
exit 1
;;
esac
SAMPLE_URL="${GITHUB_BASE}/${sample_name}"
echo "Tagarr — Config Migration"
echo "=========================="
echo ""
# --- Check local config version before downloading ---
old_version=$(sed -n 's/^# Config version:[[:space:]]*\([0-9.][0-9.]*\).*/\1/p' "$OLD_CONFIG" 2>/dev/null | head -1)
[ -z "$old_version" ] && old_version="unknown"
echo "Checking for updates ($config_basename)..."
# Download just the header to read the version (fast)
remote_header=$(curl -fsSL "$SAMPLE_URL" 2>/dev/null | head -5 || true)
remote_version=$(echo "$remote_header" | sed -n 's/^# Config version:[[:space:]]*\([0-9.][0-9.]*\).*/\1/p' | head -1)
[ -z "$remote_version" ] && remote_version="unknown"
if [ "$old_version" = "$remote_version" ] && [ "$old_version" != "unknown" ]; then
echo ""
echo "Config is already up to date (version $old_version). Nothing to do."
log "config current: $config_basename (v$old_version) — $OLD_CONFIG"
exit 0
fi
# --- Download full sample from GitHub ---
echo "Downloading latest $sample_name (version $remote_version)..."
SAMPLE_FILE=$(mktemp)
trap 'rm -f "$SAMPLE_FILE"' EXIT
if ! curl -fsSL "$SAMPLE_URL" -o "$SAMPLE_FILE" 2>/dev/null; then
echo "ERROR: Failed to download sample config from:"
echo " $SAMPLE_URL"
echo ""
echo "Check your internet connection, or download manually from:"
echo " https://github.com/ProphetSe7en/tagarr/blob/main/${sample_name}"
log "config FAILED: $config_basename (sample download failed from $SAMPLE_URL)"
exit 1
fi
# Verify it looks like a valid config sample
if ! grep -q '# ========== CONFIGURATION ==========' "$SAMPLE_FILE"; then
echo "ERROR: Downloaded file doesn't look like a valid config sample"
log "config FAILED: $config_basename (downloaded sample missing CONFIGURATION header)"
exit 1
fi
config_dir=$(dirname "$OLD_CONFIG")
backup_dir="${config_dir}/tagarr_backups"
mkdir -p "$backup_dir" 2>/dev/null
BACKUP_FILE="${backup_dir}/${config_basename}.$(date '+%Y-%m-%d')"
OUTPUT_FILE="$OLD_CONFIG"
new_version="$remote_version"
echo "Done!"
echo ""
echo "Config: $OLD_CONFIG (version: $old_version)"
echo "Sample: $sample_name (version: $new_version)"
echo "Backup: $BACKUP_FILE"
echo ""
# --- Discover array variable names from sample ---
declare -A ARRAY_VARS
while IFS= read -r line; do
if [[ "$line" =~ ^[[:space:]]*([A-Z_]+)=\( ]]; then
ARRAY_VARS["${BASH_REMATCH[1]}"]=1
fi
done < "$SAMPLE_FILE"
# --- Extract array blocks from old config ---
declare -A old_arrays
for arr_name in "${!ARRAY_VARS[@]}"; do
block=""
in_block=false
while IFS= read -r line; do
if [[ "$line" =~ ^[[:space:]]*${arr_name}=\( ]]; then
in_block=true
block="${arr_name}=("$'\n'
continue
fi
if [ "$in_block" = "true" ]; then
block+="${line}"$'\n'
if [[ "$line" =~ ^[[:space:]]*\) ]]; then
in_block=false
fi
fi
done < "$OLD_CONFIG"
old_arrays[$arr_name]="$block"
done
# --- Discover scalar variable names from sample ---
# Catches both uncommented (VAR=default) and commented-out placeholders
# (#VAR=default). Commented-out placeholders are used by tagarr_migrate.conf
# to represent opt-in slots — users uncomment them to enable. Without catching
# commented forms here, migrating tagarr_migrate.conf would silently drop the
# user's uncommented AUTOUPDATE_* values.
SCALAR_VARS=()
in_array=false
while IFS= read -r line; do
# Track array blocks to skip them
if [[ "$line" =~ ^[[:space:]]*[A-Z_]+=\( ]]; then
in_array=true
continue
fi
if [ "$in_array" = "true" ]; then
[[ "$line" =~ ^[[:space:]]*\) ]] && in_array=false
continue
fi
# Scalar variable assignment — optionally preceded by a #, with optional
# whitespace between # and the var name.
if [[ "$line" =~ ^[[:space:]]*#?[[:space:]]?([A-Z_]+)= ]]; then
SCALAR_VARS+=("${BASH_REMATCH[1]}")
fi
done < "$SAMPLE_FILE"
# --- Read scalar values from old config as raw text ---
declare -A old_raw_values
declare -A old_has_var
_in_old_array=false
while IFS= read -r line; do
[[ "$line" =~ ^[[:space:]]*# ]] && continue
[[ "$line" =~ ^[[:space:]]*$ ]] && continue
# Track array blocks to skip their contents
if [[ "$line" =~ ^[[:space:]]*[A-Z_]+=\( ]]; then
_in_old_array=true
continue
fi
if [ "$_in_old_array" = "true" ]; then
[[ "$line" =~ ^[[:space:]]*\) ]] && _in_old_array=false
continue
fi
if [[ "$line" =~ ^[[:space:]]*([A-Z_]+)=(.*) ]]; then
var_name="${BASH_REMATCH[1]}"
var_value="${BASH_REMATCH[2]}"
# Strip inline comment (but not # inside quotes)
var_value=$(echo "$var_value" | sed 's/[[:space:]]*#[^"]*$//')
# Strip surrounding quotes
var_value="${var_value#\"}"
var_value="${var_value%\"}"
old_raw_values[$var_name]="$var_value"
old_has_var[$var_name]=1
fi
done < "$OLD_CONFIG"
# --- Build output: sample template with old values substituted ---
new_vars=()
output=""
skip_array=""
while IFS= read -r line; do
# Handle array blocks — replace with old values if they exist
if [ -n "$skip_array" ]; then
if [[ "$line" =~ ^[[:space:]]*\) ]]; then
[ -z "${old_arrays[$skip_array]:-}" ] && output+="${line}"$'\n'
skip_array=""
else
[ -z "${old_arrays[$skip_array]:-}" ] && output+="${line}"$'\n'
fi
continue
fi
# Detect start of array block
array_matched=false
for arr_name in "${!ARRAY_VARS[@]}"; do
if [[ "$line" =~ ^[[:space:]]*${arr_name}=\( ]]; then
array_matched=true
if [ -n "${old_arrays[$arr_name]:-}" ]; then
output+="${old_arrays[$arr_name]}"
else
output+="${line}"$'\n'
fi
skip_array="$arr_name"
break
fi
done
if [ "$array_matched" = "true" ]; then
continue
fi
# Replace scalar variable assignments with old values.
# Matches both uncommented and commented-out forms of the var. If the user
# had it uncommented (active), write uncommented. Otherwise keep the sample
# line exactly as-is (commented or not).
matched=false
for var in "${SCALAR_VARS[@]}"; do
if [[ "$line" =~ ^[[:space:]]*#?[[:space:]]?${var}= ]]; then
matched=true
if [ -n "${old_has_var[$var]:-}" ]; then
inline_comment=""
if [[ "$line" =~ [[:space:]]+(#.*)$ ]]; then
inline_comment=" ${BASH_REMATCH[1]}"
fi
old_value="${old_raw_values[$var]:-}"
if [[ "$old_value" =~ ^(true|false)$ ]]; then
output+="${var}=${old_value}${inline_comment}"$'\n'
else
output+="${var}=\"${old_value}\"${inline_comment}"$'\n'
fi
else
# Keep sample's line verbatim — preserves commented-out
# opt-in slots that the user hasn't enabled. Only report
# as "new setting" if sample had it uncommented (real default).
output+="${line}"$'\n'
if ! [[ "$line" =~ ^[[:space:]]*# ]]; then
new_vars+=("$var")
fi
fi
break
fi
done
# Pass through comments and blank lines unchanged
if [ "$matched" = "false" ]; then
output+="${line}"$'\n'
fi
done < "$SAMPLE_FILE"
# --- Write output ---
# Backup original, then overwrite in place to preserve permissions/ownership
# (mv from mktemp would drop perms to mktemp's 600 default)
cp "$OLD_CONFIG" "$BACKUP_FILE"
printf '%s' "$output" > "$OUTPUT_FILE"
log "config migrated: $config_basename version $old_version -> $new_version ($OLD_CONFIG)"
echo "Migration complete!"
echo ""
if [ ${#new_vars[@]} -gt 0 ]; then
echo "New settings added (using defaults):"
for var in "${new_vars[@]}"; do
sample_val=$(grep -E "^[[:space:]]*${var}=" "$SAMPLE_FILE" | head -1 | sed "s/^[[:space:]]*${var}=//; s/[[:space:]]*#.*//" | tr -d '"')
echo " $var = $sample_val"
done
echo ""
fi
echo "Your original config has been backed up to:"
echo " $BACKUP_FILE"
echo ""
echo "To review what changed:"
echo " diff \"$BACKUP_FILE\" \"$OLD_CONFIG\""
echo ""
echo "To roll back:"
echo " cp \"$BACKUP_FILE\" \"$OLD_CONFIG\""