MediaImporter / media-importer.sh
Newer Older
1534 lines | 51.859kb
Bogdan Timofte authored 9 months ago
1
#!/bin/bash
2

            
3
# Standalone Media Importer
4
# Version: 1.0
5
# A comprehensive media file organizer that sorts photos and videos by date
6
# with various organization patterns and timezone handling
7

            
8
VERSION="1.0"
9
SCRIPT_NAME="Standalone Media Importer"
10

            
11
# Default values
Bogdan Timofte authored 9 months ago
12
# Default organization: 'ymd' (single folder per day yyyy-mm-dd). Override with -o/--organization.
13
ORGANIZATION="ymd"
14
FILENAME_MODE="full"  # options: auto, full, orig
Bogdan Timofte authored 9 months ago
15
COLLECT_UNSORTABLE=0
16
SOURCE_PATTERNS=()
17
DESTINATION=""
18
KEEP_ORIGINALS=0
Bogdan Timofte authored 3 weeks ago
19
VERIFY_MODE="size"  # options: size, strict, none
Bogdan Timofte authored 2 weeks ago
20
DATE_SOURCE="auto"  # options: auto, exif, filesystem
21
SYNC_METADATA=0     # when 1, write reconstructed date into destination metadata
22
UNATTENDED=0        # when 1, never prompt; destination conflicts get numeric suffixes
Bogdan Timofte authored 9 months ago
23
DRY_RUN=0
24
VERBOSE=0
Bogdan Timofte authored 8 months ago
25
CLEANUP_EMPTY_DIRS=1
Bogdan Timofte authored 2 weeks ago
26
CLEANUP_GOPRO_SIDECARS=1  # when 1, delete THM/LRV sidecars after successful MP4 import
Bogdan Timofte authored 2 weeks ago
27
CONFLICT_APPLY_ALL=""  # suffix|skip after an interactive "all similar" choice
28
RESOLVED_DESTINATION_PATH=""
29
RESERVED_DESTINATION_PATHS=()
Bogdan Timofte authored 9 months ago
30

            
31
# Counters and statistics
32
TOTAL_FILES=0
33
PROCESSED_FILES=0
34
SKIPPED_FILES=0
35
ERROR_FILES=0
36
TOTAL_SIZE=0
37
PROCESSED_SIZE=0
38
START_TIME=$(date +%s)
Bogdan Timofte authored 2 weeks ago
39
CURRENT_FILE_INDEX=0
Bogdan Timofte authored 9 months ago
40

            
41
# Colors for output
42
RED='\033[0;31m'
43
GREEN='\033[0;32m'
44
YELLOW='\033[1;33m'
Bogdan Timofte authored 9 months ago
45
# BLUE is used for informational/verbose messages. Dark terminal themes may render the
46
# default blue hard to read, so use a brighter cyan by default and allow users to
47
# override via the VERBOSE_COLOR environment variable (must be a terminal escape seq).
48
if [[ -n "${VERBOSE_COLOR:-}" ]]; then
49
    BLUE="$VERBOSE_COLOR"
50
else
51
    BLUE=$'\033[1;36m'  # bright cyan
52
fi
Bogdan Timofte authored 9 months ago
53
NC='\033[0m' # No Color
54

            
55
# Function to print colored output
56
print_color() {
57
    local color="$1"
58
    local message="$2"
59
    echo -e "${color}${message}${NC}"
60
}
61

            
62
# Function to log messages with timestamp
63
log_message() {
64
    local message="$1"
65
    local level="${2:-INFO}"
66
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
67

            
68
    case "$level" in
69
        "ERROR")
70
            print_color "$RED" "[$timestamp] ERROR: $message" >&2
71
            ;;
72
        "WARNING")
73
            print_color "$YELLOW" "[$timestamp] WARNING: $message"
74
            ;;
75
        "SUCCESS")
76
            print_color "$GREEN" "[$timestamp] SUCCESS: $message"
77
            ;;
78
        "INFO")
79
            if [[ $VERBOSE -eq 1 ]]; then
80
                print_color "$BLUE" "[$timestamp] INFO: $message"
81
            fi
82
            ;;
83
        *)
84
            echo "[$timestamp] $message"
85
            ;;
86
    esac
87
}
88

            
89
# Function to display help
90
show_help() {
Bogdan Timofte authored 9 months ago
91
        cat << EOF
92
    $SCRIPT_NAME v$VERSION
Bogdan Timofte authored 9 months ago
93

            
Bogdan Timofte authored 9 months ago
94
Usage:
Bogdan Timofte authored 9 months ago
95
    $0 [OPTIONS]
96

            
Bogdan Timofte authored 9 months ago
97
What it does:
98
    Sorts photos and videos into dated folders (by year/month/day/hour) and
99
    generates filenames from the file's creation timestamp or preserves the
100
    original name.
101

            
102
Options:
103
    -o, --organization PATTERN   y|m|d|h|ym|ymd   (default: ymd)
104
    -F, --filename-mode MODE     auto|full|orig    (default: full)
105
    -s, --source PATH            File or directory to process (repeatable). Default: cwd
106
    -d, --destination PATH       Destination folder. Required when multiple -s are given.
Bogdan Timofte authored 8 months ago
107
    -k, --keep-originals         Copy files instead of moving
Bogdan Timofte authored 3 weeks ago
108
    --verify-mode MODE           size|strict|none (default: size)
Bogdan Timofte authored 2 weeks ago
109
    --date-source SOURCE         auto|exif|filesystem (default: auto)
110
    --sync-metadata              Write chosen date into destination metadata (automatic for GoPro filesystem dates)
111
    --unattended                 Never prompt; resolve destination conflicts with numeric suffixes
Bogdan Timofte authored 9 months ago
112
    --collect-unsortable         Put files without dates into DEST/unsortable
Bogdan Timofte authored 2 weeks ago
113
    --keep-gopro-sidecars        Keep GoPro THM and LRV sidecar files (default: delete after import)
Bogdan Timofte authored 8 months ago
114
    --keep-empty-dirs            Keep empty directories after processing
115
    --dry-run                    Show actions without changing files
Bogdan Timofte authored 9 months ago
116
    -v, --verbose                Verbose output
117
    -h, --help                   Show this help
118
    --version                    Show version
119

            
120
Examples:
121
    $0 -s /path/to/photos
122
    $0 -s /path/to/DCIM -d /mnt/sorted --dry-run
123

            
124
Dependencies:
125
    exiftool (required). mediainfo and file are optional.
Bogdan Timofte authored 9 months ago
126
EOF
127
}
128

            
Bogdan Timofte authored 9 months ago
129
# Central media extensions list (used by find functions)
130
MEDIA_EXTENSIONS=("*.jpg" "*.jpeg" "*.png" "*.tiff" "*.tif" "*.cr2" "*.nef" "*.arw" "*.dng" "*.raw" "*.mp4" "*.mov" "*.avi" "*.mts" "*.m2ts" "*.mkv" "*.wmv" "*.3gp" "*.m4v")
131

            
Bogdan Timofte authored 9 months ago
132
# Function to show version
133
show_version() {
134
    echo "$SCRIPT_NAME v$VERSION"
135
    echo "A comprehensive media file organizer with timezone support"
136
}
137

            
138
# Function to check dependencies
139
check_dependencies() {
140
    local missing_deps=()
141

            
142
    # Check for required dependencies
143
    if ! command -v exiftool &> /dev/null; then
144
        missing_deps+=("exiftool")
145
    fi
146

            
147
    # Check for optional dependencies
148
    local optional_missing=()
149
    if ! command -v mediainfo &> /dev/null; then
150
        optional_missing+=("mediainfo")
151
    fi
152

            
153
    if ! command -v file &> /dev/null; then
154
        optional_missing+=("file")
155
    fi
156

            
157
    if [[ ${#missing_deps[@]} -gt 0 ]]; then
158
        print_color "$RED" "ERROR: Missing required dependencies:"
159
        for dep in "${missing_deps[@]}"; do
160
            echo "  - $dep"
161
        done
162
        echo ""
163
        echo "Installation instructions:"
164
        echo "  macOS: brew install exiftool"
165
        echo "  Ubuntu/Debian: sudo apt-get install libimage-exiftool-perl"
166
        echo "  CentOS/RHEL: sudo yum install perl-Image-ExifTool"
167
        echo "  Arch: sudo pacman -S perl-image-exiftool"
168
        exit 1
169
    fi
170

            
171
    if [[ ${#optional_missing[@]} -gt 0 && $VERBOSE -eq 1 ]]; then
172
        log_message "Optional dependencies not found (functionality may be limited): ${optional_missing[*]}" "WARNING"
173
    fi
174

            
175
    log_message "All required dependencies found" "SUCCESS"
176
}
177

            
Bogdan Timofte authored 9 months ago
178
# Determine filesystem/device ID for a path (portable between Linux and macOS)
179
get_dev() {
180
    local path="$1"
181
    if [[ -z "$path" ]]; then
182
        path="."
183
    fi
184

            
185
    # Prefer GNU stat if available
186
    if stat --version >/dev/null 2>&1; then
187
        stat -c %d "$path" 2>/dev/null || stat -c %i "$path" 2>/dev/null || echo ""
188
    else
189
        # BSD/macOS stat
190
        stat -f %d "$path" 2>/dev/null || stat -f %i "$path" 2>/dev/null || echo ""
191
    fi
192
}
193

            
194
# Function to get file size in bytes (portable between Linux and macOS)
Bogdan Timofte authored 9 months ago
195
get_file_size() {
196
    local file="$1"
197
    if [[ -f "$file" ]]; then
Bogdan Timofte authored 9 months ago
198
        # Try GNU stat
199
        if stat -c%s "$file" >/dev/null 2>&1; then
Bogdan Timofte authored 9 months ago
200
            stat -c%s "$file" 2>/dev/null || stat -f%z "$file" 2>/dev/null
Bogdan Timofte authored 9 months ago
201
        elif stat -f%z "$file" >/dev/null 2>&1; then
202
            stat -f%z "$file" 2>/dev/null
Bogdan Timofte authored 9 months ago
203
        else
204
            # Fallback to ls
Bogdan Timofte authored 9 months ago
205
            ls -ln "$file" | awk '{print $5}'
Bogdan Timofte authored 9 months ago
206
        fi
207
    else
208
        echo "0"
209
    fi
210
}
211

            
Bogdan Timofte authored 9 months ago
212
# Safe move/copy helpers: filter out benign "set flags (was: ...): Operation not supported"
213
# which appears when moving files onto filesystems that don't support BSD file flags
214
# (macOS mv may try to preserve flags and print this warning while still succeeding).
215
safe_mv() {
216
    local src="$1" dst="$2"
Bogdan Timofte authored 2 weeks ago
217
    if [[ -e "$dst" ]]; then
218
        log_message "Refusing to overwrite existing destination: $dst" "ERROR"
219
        return 1
220
    fi
Bogdan Timofte authored 9 months ago
221
    # Redirect stderr through a filter that removes the known benign message
222
    mv "$src" "$dst" 2> >(grep -v "set flags (was:" >&2)
223
    return $?
224
}
225

            
Bogdan Timofte authored 2 weeks ago
226
safe_cp() {
227
    local src="$1" dst="$2"
228
    if [[ -e "$dst" ]]; then
229
        log_message "Refusing to overwrite existing destination: $dst" "ERROR"
230
        return 1
231
    fi
232
    cp -p "$src" "$dst" 2> >(grep -v "set flags (was:" >&2)
233
    return $?
234
}
235

            
236
ensure_unique_destination_path() {
237
    local desired_path="$1"
238

            
239
    if [[ -z "$desired_path" ]]; then
240
        return 1
241
    fi
242

            
243
    if ! destination_path_unavailable "$desired_path"; then
244
        echo "$desired_path"
245
        return 0
246
    fi
247

            
248
    local dir_path filename ext stem candidate
249
    dir_path=$(dirname "$desired_path")
250
    filename=$(basename "$desired_path")
251

            
252
    if [[ "$filename" == *.* ]]; then
253
        ext="${filename##*.}"
254
        stem="${filename%.*}"
255
    else
256
        ext=""
257
        stem="$filename"
258
    fi
259

            
260
    local i
261
    i=1
262
    while [[ $i -le 9999 ]]; do
263
        if [[ -n "$ext" ]]; then
264
            candidate="$dir_path/${stem}_${i}.${ext}"
265
        else
266
            candidate="$dir_path/${stem}_${i}"
267
        fi
268
        if ! destination_path_unavailable "$candidate"; then
269
            echo "$candidate"
270
            return 0
271
        fi
272
        i=$((i + 1))
273
    done
274

            
275
    return 1
276
}
277

            
Bogdan Timofte authored 2 weeks ago
278
destination_path_reserved() {
279
    local candidate="$1"
280
    local reserved_path
281
    for reserved_path in "${RESERVED_DESTINATION_PATHS[@]}"; do
282
        if [[ "$reserved_path" == "$candidate" ]]; then
283
            return 0
284
        fi
285
    done
286
    return 1
287
}
Bogdan Timofte authored 9 months ago
288

            
Bogdan Timofte authored 2 weeks ago
289
destination_path_unavailable() {
290
    local candidate="$1"
291
    [[ -e "$candidate" ]] || destination_path_reserved "$candidate"
292
}
293

            
294
reserve_destination_path() {
295
    local candidate="$1"
296
    if [[ -n "$candidate" ]] && ! destination_path_reserved "$candidate"; then
297
        RESERVED_DESTINATION_PATHS+=("$candidate")
298
    fi
299
}
300

            
301
prompt_destination_conflict_choice() {
302
    local source_file="$1"
303
    local desired_path="$2"
304
    local choice
305

            
306
    if [[ ! -r /dev/tty || ! -w /dev/tty ]]; then
307
        return 1
308
    fi
309

            
310
    {
311
        print_color "$YELLOW" "Destination already exists:"
312
        echo "  Source:      $source_file"
313
        echo "  Destination: $desired_path"
314
        echo ""
315
        echo "Choose conflict action:"
316
        echo "  [s] suffix once"
317
        echo "  [S] suffix for all similar conflicts"
318
        echo "  [k] skip once"
319
        echo "  [K] skip all similar conflicts"
320
        echo "  [a] abort import"
321
    } > /dev/tty
322

            
323
    while true; do
324
        printf "Action [s/S/k/K/a]: " > /dev/tty
325
        IFS= read -r choice < /dev/tty || return 1
326
        case "$choice" in
327
            s|"")
328
                echo "suffix"
329
                return 0
330
                ;;
331
            S)
332
                echo "suffix_all"
333
                return 0
334
                ;;
335
            k)
336
                echo "skip"
337
                return 0
338
                ;;
339
            K)
340
                echo "skip_all"
341
                return 0
342
                ;;
343
            a|A)
344
                echo "abort"
345
                return 0
346
                ;;
347
            *)
348
                print_color "$YELLOW" "Please choose s, S, k, K, or a." > /dev/tty
349
                ;;
350
        esac
351
    done
352
}
353

            
354
resolve_destination_conflict() {
355
    local desired_path="$1"
356
    local source_file="$2"
357
    local resolved_path choice
358
    RESOLVED_DESTINATION_PATH=""
359

            
360
    if [[ -z "$desired_path" ]]; then
361
        return 1
362
    fi
363

            
364
    if ! destination_path_unavailable "$desired_path"; then
365
        RESOLVED_DESTINATION_PATH="$desired_path"
366
        reserve_destination_path "$RESOLVED_DESTINATION_PATH"
367
        return 0
368
    fi
369

            
370
    if [[ "$CONFLICT_APPLY_ALL" == "skip" ]]; then
371
        return 3
372
    fi
373

            
374
    if [[ "$CONFLICT_APPLY_ALL" == "suffix" || $UNATTENDED -eq 1 ]]; then
375
        resolved_path=$(ensure_unique_destination_path "$desired_path")
376
        if [[ -z "$resolved_path" ]]; then
377
            return 1
378
        fi
379
        RESOLVED_DESTINATION_PATH="$resolved_path"
380
        reserve_destination_path "$RESOLVED_DESTINATION_PATH"
381
        return 0
382
    fi
383

            
384
    choice=$(prompt_destination_conflict_choice "$source_file" "$desired_path")
385
    if [[ $? -ne 0 || -z "$choice" ]]; then
386
        log_message "Cannot prompt for destination conflict; using unattended numeric suffix mode" "WARNING"
387
        resolved_path=$(ensure_unique_destination_path "$desired_path")
388
        if [[ -z "$resolved_path" ]]; then
389
            return 1
390
        fi
391
        RESOLVED_DESTINATION_PATH="$resolved_path"
392
        reserve_destination_path "$RESOLVED_DESTINATION_PATH"
393
        return 0
394
    fi
395

            
396
    case "$choice" in
397
        suffix)
398
            resolved_path=$(ensure_unique_destination_path "$desired_path")
399
            ;;
400
        suffix_all)
401
            CONFLICT_APPLY_ALL="suffix"
402
            resolved_path=$(ensure_unique_destination_path "$desired_path")
403
            ;;
404
        skip)
405
            return 3
406
            ;;
407
        skip_all)
408
            CONFLICT_APPLY_ALL="skip"
409
            return 3
410
            ;;
411
        abort)
412
            return 4
413
            ;;
414
        *)
415
            return 1
416
            ;;
417
    esac
418

            
419
    if [[ -z "$resolved_path" ]]; then
420
        return 1
421
    fi
422

            
423
    RESOLVED_DESTINATION_PATH="$resolved_path"
424
    reserve_destination_path "$RESOLVED_DESTINATION_PATH"
425
    return 0
426
}
427

            
428
extract_filesystem_date() {
429
    # Returns yyyy-mm-dd hh:mm:ss based on filesystem mtime.
430
    # We intentionally use mtime (not birthtime) because birthtime isn't preserved by copies
431
    # across filesystems, while mtime can be preserved via `cp -p`.
432
    local file="$1"
433
    if [[ ! -e "$file" ]]; then
434
        return 2
435
    fi
436

            
437
    local epoch=""
438

            
439
    if [[ "$OSTYPE" == "darwin"* ]]; then
440
        epoch=$(stat -f %m "$file" 2>/dev/null || echo "")
441
        [[ -n "$epoch" ]] || return 2
442
        date -j -r "$epoch" "+%Y-%m-%d %H:%M:%S" 2>/dev/null || return 2
443
        return 0
444
    else
445
        epoch=$(stat -c %Y "$file" 2>/dev/null || echo "")
446
        [[ -n "$epoch" ]] || return 2
447
        date -d "@$epoch" "+%Y-%m-%d %H:%M:%S" 2>/dev/null || return 2
448
        return 0
449
    fi
450
}
451

            
452
filesystem_date_reference() {
453
    local file="$1"
454
    local dir base stem ext sidecar_ext sidecar
455
    dir=$(dirname "$file")
456
    base=$(basename "$file")
457
    stem="${base%.*}"
458
    ext="${base##*.}"
459

            
460
    if [[ "$ext" =~ ^([Mm][Pp]4)$ ]]; then
461
        for sidecar_ext in THM thm LRV lrv; do
462
            sidecar="$dir/$stem.$sidecar_ext"
463
            if [[ -f "$sidecar" ]]; then
464
                echo "$sidecar"
465
                return 0
466
            fi
467
        done
468
    fi
469

            
470
    echo "$file"
471
}
472

            
473
is_gopro_media_file() {
474
    local filename
475
    filename=$(basename "$1")
476
    [[ "$filename" =~ ^G[HPX][0-9]{6}\.[Mm][Pp]4$ ]]
477
}
478

            
479
should_prefer_gopro_filesystem_date() {
480
    local file="$1"
481

            
482
    is_gopro_media_file "$file"
483
}
484

            
485
filesystem_date_source_label() {
486
    local file="$1"
487
    local reference="$2"
488

            
489
    if is_gopro_media_file "$file"; then
490
        echo "Filesystem:$(basename "$reference")"
491
    elif [[ "$reference" != "$file" ]]; then
492
        echo "Filesystem:$(basename "$reference")"
493
    else
494
        echo "Filesystem"
495
    fi
496
}
497

            
498
date_to_exiftool_format() {
499
    # yyyy-mm-dd hh:mm:ss -> yyyy:mm:dd hh:mm:ss
500
    local s="$1"
501
    if [[ "$s" =~ ^([0-9]{4})-([0-9]{2})-([0-9]{2})[[:space:]]+([0-9]{2}):([0-9]{2}):([0-9]{2})$ ]]; then
502
        echo "${BASH_REMATCH[1]}:${BASH_REMATCH[2]}:${BASH_REMATCH[3]} ${BASH_REMATCH[4]}:${BASH_REMATCH[5]}:${BASH_REMATCH[6]}"
503
        return 0
504
    fi
505
    return 1
506
}
507

            
508
sync_destination_metadata_to_date() {
509
    local file="$1"
510
    local date_str="$2" # yyyy-mm-dd hh:mm:ss
511

            
512
    local exif_dt
513
    exif_dt=$(date_to_exiftool_format "$date_str") || return 1
514

            
515
    exiftool -overwrite_original \
516
        "-CreateDate=$exif_dt" \
517
        "-DateTimeOriginal=$exif_dt" \
518
        "-DateTime=$exif_dt" \
519
        "-ModifyDate=$exif_dt" \
520
        "-MediaCreateDate=$exif_dt" \
521
        "-TrackCreateDate=$exif_dt" \
522
        "-QuickTime:CreateDate=$exif_dt" \
523
        "-QuickTime:ModifyDate=$exif_dt" \
524
        "$file" >/dev/null 2>&1
525
    return 0
526
}
527

            
528
verify_synced_metadata_date() {
529
    local file="$1"
530
    local expected_date="$2"
531

            
532
    local metadata_date
533
    metadata_date=$(exiftool -api QuickTimeUTC=0 -s -s -s -QuickTime:CreateDate "$file" 2>/dev/null | head -1)
534
    if [[ -z "$metadata_date" ]]; then
535
        metadata_date=$(exiftool -api QuickTimeUTC=0 -s -s -s -CreateDate "$file" 2>/dev/null | head -1)
536
    fi
537

            
538
    if [[ "$metadata_date" =~ ^([0-9]{4}):([0-9]{2}):([0-9]{2})[[:space:]]+([0-9]{2}):([0-9]{2}):([0-9]{2}) ]]; then
539
        metadata_date="${BASH_REMATCH[1]}-${BASH_REMATCH[2]}-${BASH_REMATCH[3]} ${BASH_REMATCH[4]}:${BASH_REMATCH[5]}:${BASH_REMATCH[6]}"
540
    fi
541

            
542
    if [[ "$metadata_date" != "$expected_date" ]]; then
543
        log_message "Destination metadata sync mismatch: expected $expected_date, got ${metadata_date:-none} for $file" "ERROR"
544
        return 1
545
    fi
546

            
547
    return 0
548
}
549

            
550
should_sync_imported_metadata() {
551
    local original_filename="$1"
552
    local date_source="$2"
553

            
554
    if [[ $SYNC_METADATA -eq 1 ]]; then
555
        return 0
556
    fi
557

            
558
    if [[ "$date_source" == Filesystem* ]] && is_gopro_media_file "$original_filename"; then
559
        return 0
560
    fi
561

            
562
    return 1
Bogdan Timofte authored 9 months ago
563
}
564

            
Bogdan Timofte authored 3 weeks ago
565
verify_copied_file() {
566
    local src="$1"
567
    local dst="$2"
568
    local expected_date="$3"
569

            
570
    if [[ ! -f "$dst" ]]; then
571
        log_message "Verified copy missing at destination: $dst" "ERROR"
572
        return 1
573
    fi
574

            
575
    local src_size dst_size
576
    src_size=$(get_file_size "$src")
577
    dst_size=$(get_file_size "$dst")
578
    if [[ "$src_size" != "$dst_size" ]]; then
579
        log_message "Size mismatch after copy: $src ($src_size) != $dst ($dst_size)" "ERROR"
580
        return 1
581
    fi
582

            
583
    if [[ "$VERIFY_MODE" == "strict" ]]; then
584
        if ! cmp -s "$src" "$dst"; then
585
            log_message "Content mismatch after copy: $src -> $dst" "ERROR"
586
            return 1
587
        fi
588
    elif [[ "$VERIFY_MODE" == "none" ]]; then
589
        return 0
590
    fi
591

            
592
    if [[ -n "$expected_date" ]]; then
593
        local destination_date_info
594
        destination_date_info=$(extract_file_date "$dst")
595
        local extract_status=$?
596
        if [[ $extract_status -ne 0 || -z "$destination_date_info" ]]; then
597
            log_message "Destination metadata validation failed: $dst" "ERROR"
598
            return 1
599
        fi
600

            
601
        local destination_date="${destination_date_info%|*}"
602
        if [[ "$destination_date" != "$expected_date" ]]; then
603
            log_message "Destination metadata mismatch: expected $expected_date, got $destination_date for $dst" "ERROR"
604
            return 1
605
        fi
606
    fi
607

            
608
    return 0
609
}
610

            
611
remove_source_file() {
612
    local src="$1"
613
    rm -f "$src"
614
}
615

            
616
copy_with_verification() {
617
    local src="$1"
618
    local dst="$2"
619
    local expected_date="$3"
620

            
Bogdan Timofte authored 2 weeks ago
621
    if [[ -e "$dst" ]]; then
622
        log_message "Refusing to overwrite existing destination: $dst" "ERROR"
Bogdan Timofte authored 3 weeks ago
623
        return 1
624
    fi
625

            
Bogdan Timofte authored 2 weeks ago
626
    local dst_dir tmp
627
    dst_dir=$(dirname "$dst")
628
    tmp=$(mktemp "$dst_dir/.media-importer.$(basename "$dst").tmp.XXXXXX") || return 1
629
    rm -f "$tmp"
630

            
631
    if ! safe_cp "$src" "$tmp"; then
632
        rm -f "$tmp"
633
        return 1
634
    fi
635

            
636
    if ! verify_copied_file "$src" "$tmp" "$expected_date"; then
637
        rm -f "$tmp"
638
        return 1
639
    fi
640

            
641
    if [[ -e "$dst" ]]; then
642
        log_message "Destination appeared during copy, refusing to overwrite: $dst" "ERROR"
643
        rm -f "$tmp"
644
        return 1
645
    fi
646

            
647
    if ! safe_mv "$tmp" "$dst"; then
648
        rm -f "$tmp"
649
        return 1
650
    fi
651

            
652
    if [[ ! -f "$dst" ]]; then
653
        log_message "Copied file missing after final move: $dst" "ERROR"
Bogdan Timofte authored 3 weeks ago
654
        return 1
655
    fi
656

            
657
    return 0
658
}
659

            
660
verified_move_file() {
661
    local src="$1"
662
    local dst="$2"
663
    local expected_date="$3"
664

            
665
    if ! copy_with_verification "$src" "$dst" "$expected_date"; then
666
        return 1
667
    fi
668

            
669
    if ! remove_source_file "$src"; then
670
        log_message "Copied and verified destination, but failed to remove source: $src" "ERROR"
671
        return 1
672
    fi
673

            
674
    return 0
675
}
676

            
Bogdan Timofte authored 9 months ago
677
# Function to format file size
678
format_size() {
679
    local size=$1
680
    if (( size < 1024 )); then
681
        echo "${size}B"
682
    elif (( size < 1048576 )); then
683
        echo "$(( size / 1024 ))KB"
684
    elif (( size < 1073741824 )); then
685
        echo "$(( size / 1048576 ))MB"
686
    else
687
        echo "$(( size / 1073741824 ))GB"
688
    fi
689
}
690

            
Bogdan Timofte authored 2 weeks ago
691
format_duration() {
692
    local total_seconds=$1
693
    local hours=$((total_seconds / 3600))
694
    local minutes=$(((total_seconds % 3600) / 60))
695
    local seconds=$((total_seconds % 60))
696

            
697
    if (( hours > 0 )); then
698
        printf "%dh %02dm %02ds" "$hours" "$minutes" "$seconds"
699
    elif (( minutes > 0 )); then
700
        printf "%dm %02ds" "$minutes" "$seconds"
701
    else
702
        printf "%ds" "$seconds"
703
    fi
704
}
705

            
Bogdan Timofte authored 2 weeks ago
706
format_data_rate() {
707
    local bytes_count="$1"
708
    local elapsed_seconds="$2"
Bogdan Timofte authored 2 weeks ago
709

            
Bogdan Timofte authored 2 weeks ago
710
    awk -v bytes="$bytes_count" -v seconds="$elapsed_seconds" '
Bogdan Timofte authored 2 weeks ago
711
        BEGIN {
Bogdan Timofte authored 2 weeks ago
712
            if (seconds <= 0 || bytes <= 0) {
Bogdan Timofte authored 2 weeks ago
713
                exit
714
            }
715

            
716
            mb_per_second = bytes / seconds / 1048576
Bogdan Timofte authored 2 weeks ago
717
            printf "%.2f MB/sec", mb_per_second
Bogdan Timofte authored 2 weeks ago
718
        }
719
    '
720
}
721

            
Bogdan Timofte authored 2 weeks ago
722
report_line() {
723
    local label="$1"
724
    local value="$2"
725
    printf "  %-24s %s\n" "$label" "$value"
726
}
727

            
Bogdan Timofte authored 9 months ago
728
# Function to extract date from file
729
extract_file_date() {
730
    local file="$1"
731
    local create_date=""
732
    local date_source=""
733
    local exif_found=0
Bogdan Timofte authored 2 weeks ago
734

            
735
    # Filesystem authoritative mode, and GoPro media in auto mode.
736
    # GoPro fallback order is THM, LRV, then the MP4 filesystem timestamp.
737
    if [[ "$DATE_SOURCE" == "filesystem" ]] || { [[ "$DATE_SOURCE" == "auto" ]] && should_prefer_gopro_filesystem_date "$file"; }; then
738
        local filesystem_reference
739
        filesystem_reference=$(filesystem_date_reference "$file")
740
        create_date=$(extract_filesystem_date "$filesystem_reference") || return 2
741
        echo "$create_date|$(filesystem_date_source_label "$file" "$filesystem_reference")"
742
        return 0
743
    fi
744

            
Bogdan Timofte authored 9 months ago
745
    # Try to get creation date from EXIF data
746
    local exif_output=$(exiftool -G1 -s -CreateDate -DateTimeOriginal -DateTime "$file" 2>/dev/null)
747
    if [[ -n "$exif_output" ]]; then
748
        # Parse the exiftool output to find the best date
749
        while IFS= read -r line; do
750
            if [[ "$line" =~ ^\[([^\]]+)\][[:space:]]*([^:]+)[[:space:]]*:[[:space:]]*(.+)$ ]]; then
751
                local group="${BASH_REMATCH[1]}"
752
                local tag="${BASH_REMATCH[2]}"
753
                local value="${BASH_REMATCH[3]}"
754
                # Trim spaces from tag name
755
                tag=$(echo "$tag" | sed 's/[[:space:]]*$//')
756
                # Prefer DateTimeOriginal, then CreateDate, then DateTime
757
                if [[ "$tag" == "DateTimeOriginal" && -z "$create_date" ]]; then
758
                    create_date="$value"
759
                    date_source="$group:$tag"
760
                    exif_found=1
761
                elif [[ "$tag" == "CreateDate" && "$date_source" != *"DateTimeOriginal"* ]]; then
762
                    create_date="$value"
763
                    date_source="$group:$tag"
764
                    exif_found=1
765
                elif [[ "$tag" == "DateTime" && -z "$create_date" ]]; then
766
                    create_date="$value"
767
                    date_source="$group:$tag"
768
                    exif_found=1
769
                fi
770
            fi
771
        done <<< "$exif_output"
772
    fi
773
    # If no EXIF date found, try mediainfo for video files
774
    if [[ -z "$create_date" ]] && command -v mediainfo &> /dev/null; then
775
        local media_date=$(mediainfo --Inform="General;%Recorded_Date%" "$file" 2>/dev/null)
776
        if [[ -n "$media_date" && "$media_date" != "0000-00-00 00:00:00" ]]; then
777
            create_date="$media_date"
778
            date_source="MediaInfo:Recorded_Date"
779
        fi
780
    fi
Bogdan Timofte authored 2 weeks ago
781

            
782
    # In auto mode, if metadata is missing/unreliable, fall back to filesystem timestamps
783
    if [[ -z "$create_date" && "$DATE_SOURCE" == "auto" ]]; then
784
        local filesystem_reference
785
        filesystem_reference=$(filesystem_date_reference "$file")
786
        create_date=$(extract_filesystem_date "$filesystem_reference") || return 2
787
        date_source=$(filesystem_date_source_label "$file" "$filesystem_reference")
788
    fi
789

            
Bogdan Timofte authored 9 months ago
790
    # If no EXIF or mediainfo date found, return failure
791
    if [[ -z "$create_date" ]]; then
792
        return 2  # No date metadata found
793
    fi
794

            
795
    # Convert EXIF format (YYYY:MM:DD HH:MM:SS) to standard format
796
    # Always output as yyyy-mm-dd hh:mm:ss (pad single digits)
797
    if [[ "$create_date" =~ ^([0-9]{4}):([0-9]{1,2}):([0-9]{1,2})[[:space:]]*([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})$ ]]; then
798
        year="${BASH_REMATCH[1]}"
799
        month=$(printf "%02d" "$((10#${BASH_REMATCH[2]}))")
800
        day=$(printf "%02d" "$((10#${BASH_REMATCH[3]}))")
801
        hour=$(printf "%02d" "$((10#${BASH_REMATCH[4]}))")
802
        minute=$(printf "%02d" "$((10#${BASH_REMATCH[5]}))")
803
        second=$(printf "%02d" "$((10#${BASH_REMATCH[6]}))")
804
        create_date="$year-$month-$day $hour:$minute:$second"
805
    else
806
        # Try to convert yyyy-mm-dd hh:mm:ss (already correct)
807
        if [[ "$create_date" =~ ^([0-9]{4})-([0-9]{2})-([0-9]{2})[[:space:]]*([0-9]{2}):([0-9]{2}):([0-9]{2})$ ]]; then
808
            # Already correct
809
            :
810
        else
811
            print_color "$RED" "Error: Cannot parse date '$create_date'" >&2
812
            return 2
813
        fi
814
    fi
815

            
816
    # For QuickTime files, the CreateDate is in UTC and needs conversion to local time
817
    if [[ "$date_source" == *"QuickTime"* ]]; then
818
        # Convert UTC time to local time
819
        if [[ "$OSTYPE" == "darwin"* ]]; then
820
            # On macOS, use TZ=UTC to interpret the input time as UTC
821
            local utc_timestamp=$(TZ=UTC date -j -f "%Y-%m-%d %H:%M:%S" "$create_date" "+%s" 2>/dev/null)
822
            if [[ -n "$utc_timestamp" ]]; then
823
                create_date=$(date -j -r "$utc_timestamp" "+%Y-%m-%d %H:%M:%S" 2>/dev/null)
824
                date_source="$date_source (converted from UTC)"
825
            fi
826
        else
827
            local utc_timestamp=$(date -d "$create_date UTC" "+%s" 2>/dev/null)
828
            if [[ -n "$utc_timestamp" ]]; then
829
                create_date=$(date -d "@$utc_timestamp" "+%Y-%m-%d %H:%M:%S" 2>/dev/null)
830
                date_source="$date_source (converted from UTC)"
831
            fi
832
        fi
833
    fi
834

            
835
    echo "$create_date|$date_source"
836
    return 0
837
}
838

            
839
# Function to generate destination path based on organization pattern
840
generate_destination_path() {
841
    local date_str="$1"
842
    local original_filename="$2"
843
    local base_destination="$3"
844

            
845
    # Extract date components - handle both GNU and BSD date
846
    local year month day hour minute second
847
    if [[ "$OSTYPE" == "darwin"* ]]; then
848
        # macOS (BSD date) - use more robust regex (allow single-digit month/day, tolerate extra spaces)
849
        if [[ "$date_str" =~ ^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})[[:space:]]*([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})$ ]]; then
850
            year="${BASH_REMATCH[1]}"
851
            month=$(printf "%02d" "$((10#${BASH_REMATCH[2]}))")
852
            day=$(printf "%02d" "$((10#${BASH_REMATCH[3]}))")
853
            hour=$(printf "%02d" "$((10#${BASH_REMATCH[4]}))")
854
            minute=$(printf "%02d" "$((10#${BASH_REMATCH[5]}))")
855
            second=$(printf "%02d" "$((10#${BASH_REMATCH[6]}))")
856
        else
857
            return 1
858
        fi
859
    else
860
        # Linux (GNU date)
861
        year=$(date -d "$date_str" "+%Y" 2>/dev/null)
862
        month=$(date -d "$date_str" "+%m" 2>/dev/null)
863
        day=$(date -d "$date_str" "+%d" 2>/dev/null)
864
        hour=$(date -d "$date_str" "+%H" 2>/dev/null)
865
        minute=$(date -d "$date_str" "+%M" 2>/dev/null)
866
        second=$(date -d "$date_str" "+%S" 2>/dev/null)
867
    fi
868

            
869
    if [[ -z "$year" || -z "$month" || -z "$day" ]]; then
870
        return 1
871
    fi
872

            
873
    # Get file extension
874
    local extension="${original_filename##*.}"
875
    local lowercase_ext=$(echo "$extension" | tr '[:upper:]' '[:lower:]')
876

            
877
    # Generate path and filename based on organization pattern
878
    local dir_path=""
879
    local filename=""
Bogdan Timofte authored 9 months ago
880

            
881
    # If no organization specified, use flat destination (base) and choose filename per mode
882
    if [[ -z "$ORGANIZATION" ]]; then
Bogdan Timofte authored 9 months ago
883
        dir_path="$base_destination"
Bogdan Timofte authored 9 months ago
884
        if [[ "$FILENAME_MODE" == "orig" ]]; then
885
            filename="$original_filename"
886
        else
887
            # full or auto both map to full date for flat layout
888
            filename="${year}-${month}-${day}_${hour}-${minute}-${second}.${lowercase_ext}"
889
        fi
890
        echo "$dir_path/$filename"
891
        return 0
892
    fi
893

            
894
    case "$ORGANIZATION" in
Bogdan Timofte authored 9 months ago
895
            "y")
896
                dir_path="$base_destination/$year"
897
                filename="${month}-${day}_${hour}-${minute}-${second}.${lowercase_ext}"
898
                ;;
899
            "m")
900
                dir_path="$base_destination/$year/$month"
901
                filename="${day}_${hour}-${minute}-${second}.${lowercase_ext}"
902
                ;;
903
            "d")
904
                dir_path="$base_destination/$year/$month/$day"
905
                filename="${month}-${day}_${hour}-${minute}-${second}.${lowercase_ext}"
906
                ;;
907
            "h")
908
                dir_path="$base_destination/$year/$month/$day/$hour"
909
                filename="${minute}-${second}.${lowercase_ext}"
910
                ;;
Bogdan Timofte authored 9 months ago
911
            "ym")
912
                # Single folder per month named yyyy-mm; filename includes day and time
913
                dir_path="$base_destination/${year}-${month}"
914
                filename="${day}_${hour}-${minute}-${second}.${lowercase_ext}"
915
                ;;
Bogdan Timofte authored 8 months ago
916
            "ymd")
Bogdan Timofte authored 9 months ago
917
                # Single folder per day named yyyy-mm-dd; filename is time
918
                dir_path="$base_destination/${year}-${month}-${day}"
919
                filename="${hour}-${minute}-${second}.${lowercase_ext}"
920
                ;;
Bogdan Timofte authored 9 months ago
921
            *)
922
                log_message "Invalid organization pattern: $ORGANIZATION" "ERROR"
923
                return 1
924
                ;;
925
        esac
Bogdan Timofte authored 9 months ago
926

            
927
    # Apply filename mode overrides
928
    case "$FILENAME_MODE" in
929
        orig)
930
            filename="$original_filename"
931
            ;;
932
        full)
933
            filename="${year}-${month}-${day}_${hour}-${minute}-${second}.${lowercase_ext}"
934
            ;;
935
        auto)
936
            # keep the auto-generated filename from the organization case
937
            ;;
938
        *)
939
            # fallback to full
940
            filename="${year}-${month}-${day}_${hour}-${minute}-${second}.${lowercase_ext}"
941
            ;;
942
    esac
943

            
Bogdan Timofte authored 9 months ago
944
    echo "$dir_path/$filename"
945
    return 0
946
}
947

            
948
# Function to find files matching patterns
949
find_source_files() {
Bogdan Timofte authored 9 months ago
950
    # Emit absolute file paths for all media files under sources, excluding DESTINATION when it is inside a source
951
    local abs_dest=""
952
    if [[ -n "$DESTINATION" ]]; then
953
        abs_dest=$(cd "$DESTINATION" 2>/dev/null && pwd) || abs_dest="$DESTINATION"
954
    fi
955

            
956
    # Build -iname expression for find
957
    local ext_expr=""
958
    for ext in "${MEDIA_EXTENSIONS[@]}"; do
959
        if [[ -n "$ext_expr" ]]; then
960
            ext_expr="$ext_expr -o"
961
        fi
962
        ext_expr="$ext_expr -iname $ext"
963
    done
964

            
Bogdan Timofte authored 9 months ago
965
    if [[ ${#SOURCE_PATTERNS[@]} -eq 0 ]]; then
Bogdan Timofte authored 9 months ago
966
        # Default: scan current directory
967
        local start_dot="."
968
        local abs_current
969
        abs_current=$(pwd)
970
        local find_cmd=(find -L "$start_dot" -type f)
971
        # If dest is inside cwd, add exclusion
972
        if [[ -n "$abs_dest" && "$abs_dest" == "$abs_current"* ]]; then
973
            find_cmd+=( ! -path "$abs_dest/*" ! -path "$abs_dest" )
Bogdan Timofte authored 9 months ago
974
        fi
Bogdan Timofte authored 9 months ago
975
        # Add expression
976
        # shellcheck disable=SC2068
Bogdan Timofte authored 2 weeks ago
977
        "${find_cmd[@]}" ! -name '._*' \( $ext_expr \) 2>/dev/null || true
Bogdan Timofte authored 9 months ago
978
    else
Bogdan Timofte authored 9 months ago
979
        # Scan each provided source
980
        for src in "${SOURCE_PATTERNS[@]}"; do
981
            if [[ -f "$src" ]]; then
Bogdan Timofte authored 2 weeks ago
982
                if [[ "$(basename "$src")" == ._* ]]; then
983
                    continue
984
                fi
Bogdan Timofte authored 9 months ago
985
                # single file - skip if it's inside dest
986
                local abs_file
987
                abs_file=$(cd "$(dirname "$src")" 2>/dev/null && pwd)/$(basename "$src")
988
                if [[ -n "$abs_dest" && "$abs_file" == "$abs_dest"* ]]; then
989
                    continue
990
                fi
991
                echo "$abs_file"
992
            elif [[ -d "$src" ]]; then
993
                local abs_src
994
                abs_src=$(cd "$src" 2>/dev/null && pwd)
995
                if [[ -n "$abs_src" ]]; then
996
                    if [[ -n "$abs_dest" && "$abs_dest" == "$abs_src"* ]]; then
Bogdan Timofte authored 2 weeks ago
997
                        find -L "$abs_src" -type f ! -name '._*' \( $ext_expr \) ! -path "$abs_dest/*" ! -path "$abs_dest" 2>/dev/null || true
Bogdan Timofte authored 9 months ago
998
                    else
Bogdan Timofte authored 2 weeks ago
999
                        find -L "$abs_src" -type f ! -name '._*' \( $ext_expr \) 2>/dev/null || true
Bogdan Timofte authored 9 months ago
1000
                    fi
Bogdan Timofte authored 9 months ago
1001
                else
1002
                    print_color "$YELLOW" "Warning: Could not resolve source directory: $src"
Bogdan Timofte authored 9 months ago
1003
                fi
Bogdan Timofte authored 9 months ago
1004
            else
1005
                print_color "$YELLOW" "Warning: Source path does not exist or is not a file/directory: $src"
Bogdan Timofte authored 9 months ago
1006
            fi
1007
        done
1008
    fi
1009
}
1010

            
Bogdan Timofte authored 2 weeks ago
1011
cleanup_gopro_sidecars() {
1012
    local file="$1"
1013
    local dir base stem ext sidecar_ext sidecar
1014
    dir=$(dirname "$file")
1015
    base=$(basename "$file")
1016
    stem="${base%.*}"
1017
    ext="${base##*.}"
1018

            
1019
    if [[ ! "$ext" =~ ^([Mm][Pp]4)$ ]]; then
1020
        return 0
1021
    fi
1022

            
1023
    for sidecar_ext in THM thm LRV lrv; do
1024
        sidecar="$dir/$stem.$sidecar_ext"
1025
        if [[ -f "$sidecar" ]]; then
1026
            if rm -f "$sidecar"; then
1027
                log_message "Deleted GoPro sidecar: $sidecar" "INFO"
1028
            else
1029
                log_message "Failed to delete GoPro sidecar: $sidecar" "WARNING"
1030
            fi
1031
        fi
1032
    done
1033
}
1034

            
Bogdan Timofte authored 9 months ago
1035
# Function to process a single file
1036
process_file() {
1037
    local file="$1"
1038
    local file_size=$(get_file_size "$file")
Bogdan Timofte authored 2 weeks ago
1039
    local file_label
1040
    file_label="$(basename "$file")"
Bogdan Timofte authored 9 months ago
1041
    TOTAL_SIZE=$((TOTAL_SIZE + file_size))
1042

            
Bogdan Timofte authored 2 weeks ago
1043
    if [[ $TOTAL_FILES -gt 0 && $CURRENT_FILE_INDEX -gt 0 ]]; then
1044
        print_color "$BLUE" "Processing [$CURRENT_FILE_INDEX/$TOTAL_FILES]: $file_label ($(format_size "$file_size"))"
1045
    else
1046
        print_color "$BLUE" "Processing: $file_label ($(format_size "$file_size"))"
1047
    fi
Bogdan Timofte authored 9 months ago
1048
    log_message "Processing: $file" "INFO"
1049

            
1050
    # Extract date information
1051
    local date_info=$(extract_file_date "$file")
1052
        local extract_status=$?
1053
        if [[ $extract_status -eq 2 ]]; then
1054
            if [[ $COLLECT_UNSORTABLE -eq 1 ]]; then
1055
                local unsortable_dir="$DESTINATION/unsortable"
1056
                mkdir -p "$unsortable_dir"
1057
                local unsortable_path="$unsortable_dir/$(basename "$file")"
Bogdan Timofte authored 2 weeks ago
1058
                local desired_unsortable_path="$unsortable_path"
1059
                local unsortable_conflict_status
1060
                resolve_destination_conflict "$unsortable_path" "$file"
1061
                unsortable_conflict_status=$?
1062
                if [[ $unsortable_conflict_status -eq 0 ]]; then
1063
                    unsortable_path="$RESOLVED_DESTINATION_PATH"
1064
                    if [[ "$unsortable_path" != "$desired_unsortable_path" ]]; then
1065
                        log_message "Destination already exists or is already planned: $desired_unsortable_path - using: $unsortable_path" "WARNING"
1066
                    fi
1067
                elif [[ $unsortable_conflict_status -eq 3 ]]; then
1068
                    log_message "Destination conflict skipped: $desired_unsortable_path" "WARNING"
1069
                    SKIPPED_FILES=$((SKIPPED_FILES + 1))
1070
                    return 1
1071
                elif [[ $unsortable_conflict_status -eq 4 ]]; then
1072
                    log_message "Import aborted by user at destination conflict: $desired_unsortable_path" "ERROR"
1073
                    ERROR_FILES=$((ERROR_FILES + 1))
1074
                    FATAL_ERROR=1
1075
                    return 2
1076
                else
1077
                    log_message "Could not resolve a unique destination path for $file (wanted: $desired_unsortable_path)" "ERROR"
1078
                    ERROR_FILES=$((ERROR_FILES + 1))
1079
                    return 1
1080
                fi
Bogdan Timofte authored 9 months ago
1081
                if [[ $DRY_RUN -eq 1 ]]; then
1082
                    print_color "$BLUE" "Would move unsortable: $file -> $unsortable_path"
1083
                else
Bogdan Timofte authored 3 weeks ago
1084
                    if verified_move_file "$file" "$unsortable_path" ""; then
Bogdan Timofte authored 9 months ago
1085
                        log_message "Unsortable: $file -> $unsortable_path" "SUCCESS"
1086
                    else
Bogdan Timofte authored 3 weeks ago
1087
                        log_message "Failed to move unsortable file after verification: $file" "ERROR"
Bogdan Timofte authored 9 months ago
1088
                    fi
1089
                fi
1090
                SKIPPED_FILES=$((SKIPPED_FILES + 1))
1091
            else
1092
                log_message "Could not extract date from $file - skipping" "WARNING"
1093
                SKIPPED_FILES=$((SKIPPED_FILES + 1))
1094
            fi
1095
            return 1
1096
        elif [[ $extract_status -ne 0 ]] || [[ -z "$date_info" ]]; then
1097
            log_message "Could not extract date from $file - skipping" "WARNING"
1098
            SKIPPED_FILES=$((SKIPPED_FILES + 1))
1099
            return 1
1100
        fi
1101
        local date_str="${date_info%|*}"
1102
        local date_source="${date_info#*|}"
1103
        log_message "Date: $date_str (from $date_source)" "INFO"
1104
        # Generate destination path
Bogdan Timofte authored 2 weeks ago
1105
        local original_basename
1106
        original_basename="$(basename "$file")"
1107
        local dest_path
1108
        dest_path=$(generate_destination_path "$date_str" "$original_basename" "$DESTINATION")
Bogdan Timofte authored 9 months ago
1109
        if [[ $? -ne 0 ]] || [[ -z "$dest_path" ]]; then
1110
            log_message "Could not generate destination path for $file" "ERROR"
1111
            ERROR_FILES=$((ERROR_FILES + 1))
1112
            FATAL_ERROR=1
1113
            return 2
1114
    fi
Bogdan Timofte authored 2 weeks ago
1115

            
1116
    local desired_dest_path="$dest_path"
1117
    local conflict_status
1118
    resolve_destination_conflict "$dest_path" "$file"
1119
    conflict_status=$?
1120
    if [[ $conflict_status -eq 0 ]]; then
1121
        dest_path="$RESOLVED_DESTINATION_PATH"
1122
    elif [[ $conflict_status -eq 3 ]]; then
1123
        log_message "Destination conflict skipped: $desired_dest_path" "WARNING"
1124
        SKIPPED_FILES=$((SKIPPED_FILES + 1))
1125
        return 1
1126
    elif [[ $conflict_status -eq 4 ]]; then
1127
        log_message "Import aborted by user at destination conflict: $desired_dest_path" "ERROR"
1128
        ERROR_FILES=$((ERROR_FILES + 1))
1129
        FATAL_ERROR=1
1130
        return 2
1131
    else
1132
        log_message "Could not resolve a unique destination path for $file (wanted: $desired_dest_path)" "ERROR"
1133
        ERROR_FILES=$((ERROR_FILES + 1))
1134
        return 1
Bogdan Timofte authored 9 months ago
1135
    fi
Bogdan Timofte authored 2 weeks ago
1136
    if [[ "$dest_path" != "$desired_dest_path" ]]; then
1137
        log_message "Destination already exists or is already planned: $desired_dest_path - using: $dest_path" "WARNING"
1138
    fi
1139

            
1140
    local dest_dir
1141
    dest_dir=$(dirname "$dest_path")
Bogdan Timofte authored 9 months ago
1142

            
1143
    if [[ $DRY_RUN -eq 1 ]]; then
1144
        if [[ $KEEP_ORIGINALS -eq 1 ]]; then
1145
            print_color "$BLUE" "Would copy: $file -> $dest_path"
1146
        else
1147
            print_color "$BLUE" "Would move: $file -> $dest_path"
1148
        fi
Bogdan Timofte authored 2 weeks ago
1149
        if should_sync_imported_metadata "$original_basename" "$date_source"; then
1150
            print_color "$BLUE" "Would sync metadata date: $dest_path -> $date_str"
1151
        fi
Bogdan Timofte authored 9 months ago
1152
        PROCESSED_FILES=$((PROCESSED_FILES + 1))
1153
        PROCESSED_SIZE=$((PROCESSED_SIZE + file_size))
1154
        return 0
1155
    fi
1156

            
1157
    # Create destination directory
1158
    if ! mkdir -p "$dest_dir"; then
1159
        log_message "Could not create directory: $dest_dir" "ERROR"
1160
        ERROR_FILES=$((ERROR_FILES + 1))
1161
        return 1
1162
    fi
1163

            
Bogdan Timofte authored 2 weeks ago
1164
    local sync_metadata_after_copy=0
1165
    local verification_date="$date_str"
1166
    if should_sync_imported_metadata "$original_basename" "$date_source"; then
1167
        sync_metadata_after_copy=1
1168
        verification_date=""
1169
    fi
1170

            
1171
    # Copy or move file using safe helpers after destination conflicts are resolved.
Bogdan Timofte authored 9 months ago
1172
    if [[ $KEEP_ORIGINALS -eq 1 ]]; then
Bogdan Timofte authored 2 weeks ago
1173
        if copy_with_verification "$file" "$dest_path" "$verification_date"; then
1174
            if [[ $sync_metadata_after_copy -eq 1 ]]; then
1175
                if ! sync_destination_metadata_to_date "$dest_path" "$date_str"; then
1176
                    log_message "Failed to sync destination metadata timestamps: $dest_path" "ERROR"
1177
                    ERROR_FILES=$((ERROR_FILES + 1))
1178
                    return 1
1179
                elif ! verify_synced_metadata_date "$dest_path" "$date_str"; then
1180
                    ERROR_FILES=$((ERROR_FILES + 1))
1181
                    return 1
1182
                fi
1183
            fi
Bogdan Timofte authored 9 months ago
1184
            log_message "Copied: $file -> $dest_path" "SUCCESS"
Bogdan Timofte authored 2 weeks ago
1185
            if [[ $CLEANUP_GOPRO_SIDECARS -eq 1 ]]; then
1186
                cleanup_gopro_sidecars "$file"
1187
            fi
Bogdan Timofte authored 9 months ago
1188
            PROCESSED_FILES=$((PROCESSED_FILES + 1))
1189
            PROCESSED_SIZE=$((PROCESSED_SIZE + file_size))
1190
            return 0
1191
        else
Bogdan Timofte authored 3 weeks ago
1192
            log_message "Failed to copy or verify destination: $file -> $dest_path" "ERROR"
Bogdan Timofte authored 9 months ago
1193
            ERROR_FILES=$((ERROR_FILES + 1))
1194
            return 1
1195
        fi
1196
    else
Bogdan Timofte authored 2 weeks ago
1197
        if [[ $sync_metadata_after_copy -eq 1 ]]; then
1198
            if copy_with_verification "$file" "$dest_path" "$verification_date"; then
1199
                if ! sync_destination_metadata_to_date "$dest_path" "$date_str"; then
1200
                    log_message "Failed to sync destination metadata timestamps: $dest_path" "ERROR"
1201
                    ERROR_FILES=$((ERROR_FILES + 1))
1202
                    return 1
1203
                fi
1204
                if ! verify_synced_metadata_date "$dest_path" "$date_str"; then
1205
                    ERROR_FILES=$((ERROR_FILES + 1))
1206
                    return 1
1207
                fi
1208
                if ! remove_source_file "$file"; then
1209
                    log_message "Copied, verified, and synced destination, but failed to remove source: $file" "ERROR"
1210
                    ERROR_FILES=$((ERROR_FILES + 1))
1211
                    return 1
1212
                fi
1213
                log_message "Moved: $file -> $dest_path" "SUCCESS"
Bogdan Timofte authored 2 weeks ago
1214
            if [[ $CLEANUP_GOPRO_SIDECARS -eq 1 ]]; then
1215
                cleanup_gopro_sidecars "$file"
1216
            fi
Bogdan Timofte authored 2 weeks ago
1217
                PROCESSED_FILES=$((PROCESSED_FILES + 1))
1218
                PROCESSED_SIZE=$((PROCESSED_SIZE + file_size))
1219
                return 0
1220
            else
1221
                log_message "Failed to move after copy verification: $file -> $dest_path" "ERROR"
1222
                ERROR_FILES=$((ERROR_FILES + 1))
1223
                return 1
1224
            fi
1225
        elif verified_move_file "$file" "$dest_path" "$date_str"; then
Bogdan Timofte authored 9 months ago
1226
            log_message "Moved: $file -> $dest_path" "SUCCESS"
Bogdan Timofte authored 2 weeks ago
1227
            if [[ $CLEANUP_GOPRO_SIDECARS -eq 1 ]]; then
1228
                cleanup_gopro_sidecars "$file"
1229
            fi
Bogdan Timofte authored 2 weeks ago
1230
            if [[ $sync_metadata_after_copy -eq 1 ]]; then
1231
                if ! sync_destination_metadata_to_date "$dest_path" "$date_str"; then
1232
                    log_message "Failed to sync destination metadata timestamps: $dest_path" "WARNING"
1233
                elif ! verify_synced_metadata_date "$dest_path" "$date_str"; then
1234
                    log_message "Failed to verify synced destination metadata timestamps: $dest_path" "WARNING"
1235
                fi
1236
            fi
Bogdan Timofte authored 9 months ago
1237
            PROCESSED_FILES=$((PROCESSED_FILES + 1))
1238
            PROCESSED_SIZE=$((PROCESSED_SIZE + file_size))
1239
            return 0
1240
        else
Bogdan Timofte authored 3 weeks ago
1241
            log_message "Failed to move after copy verification: $file -> $dest_path" "ERROR"
Bogdan Timofte authored 9 months ago
1242
            ERROR_FILES=$((ERROR_FILES + 1))
1243
            return 1
1244
        fi
1245
    fi
1246
}
1247

            
1248
# Function to display final report
1249
show_report() {
1250
    local end_time=$(date +%s)
1251
    local elapsed_time=$((end_time - START_TIME))
1252
    local hours=$((elapsed_time / 3600))
1253
    local minutes=$(((elapsed_time % 3600) / 60))
1254
    local seconds=$((elapsed_time % 60))
1255

            
1256
    echo ""
1257
    print_color "$GREEN" "=========================================="
1258
    print_color "$GREEN" "           PROCESSING REPORT"
1259
    print_color "$GREEN" "=========================================="
1260
    echo ""
Bogdan Timofte authored 2 weeks ago
1261

            
1262
    echo "Files Summary:"
1263
    report_line "Total files found:" "$TOTAL_FILES"
1264
    report_line "Successfully processed:" "$PROCESSED_FILES"
1265
    report_line "Skipped:" "$SKIPPED_FILES"
1266
    report_line "Errors:" "$ERROR_FILES"
1267
    echo ""
1268

            
Bogdan Timofte authored 9 months ago
1269
    echo "Size Summary:"
Bogdan Timofte authored 2 weeks ago
1270
    report_line "Total size found:" "$(format_size $TOTAL_SIZE)"
1271
    report_line "Successfully processed:" "$(format_size $PROCESSED_SIZE)"
Bogdan Timofte authored 9 months ago
1272
    echo ""
Bogdan Timofte authored 2 weeks ago
1273

            
1274
    echo "Time Summary:"
1275
    report_line "Time elapsed:" "$(printf "%02d:%02d:%02d" $hours $minutes $seconds)"
1276
    if [[ $elapsed_time -gt 0 && $PROCESSED_SIZE -gt 0 ]]; then
1277
        local data_rate
1278
        data_rate=$(format_data_rate "$PROCESSED_SIZE" "$elapsed_time")
1279
        if [[ -n "$data_rate" ]]; then
1280
            report_line "Data rate:" "$data_rate"
1281
        fi
1282
    fi
1283

            
1284
    echo ""
1285

            
Bogdan Timofte authored 9 months ago
1286
    if [[ $DRY_RUN -eq 1 ]]; then
1287
        print_color "$YELLOW" "DRY RUN MODE - No files were actually moved/copied"
1288
    elif [[ $KEEP_ORIGINALS -eq 1 ]]; then
1289
        print_color "$BLUE" "COPY MODE - Original files were preserved"
1290
    else
1291
        print_color "$GREEN" "MOVE MODE - Files were moved to destination"
1292
    fi
1293

            
1294
    echo ""
1295
    print_color "$GREEN" "=========================================="
1296
}
1297

            
Bogdan Timofte authored 2 weeks ago
1298
if [[ "${BASH_SOURCE[0]}" != "$0" ]]; then
1299
    return 0
1300
fi
1301

            
Bogdan Timofte authored 9 months ago
1302
# Parse command line arguments
1303
while [[ $# -gt 0 ]]; do
1304
    case $1 in
1305
        -o|--organization)
1306
            ORGANIZATION="$2"
Bogdan Timofte authored 8 months ago
1307
            # Accept new patterns: ym, ymd as well as single-letter ones
1308
            if [[ ! "$ORGANIZATION" =~ ^(y|m|d|h|ym|ymd)$ ]]; then
Bogdan Timofte authored 9 months ago
1309
                print_color "$RED" "Error: Invalid organization pattern. Must be one of: y, m, d, h, ym, ymd"
Bogdan Timofte authored 9 months ago
1310
                exit 1
1311
            fi
1312
            shift 2
1313
            ;;
Bogdan Timofte authored 9 months ago
1314

            
1315
        -F|--filename-mode)
1316
            FILENAME_MODE="$2"
1317
            if [[ ! "$FILENAME_MODE" =~ ^(auto|full|orig)$ ]]; then
1318
                print_color "$RED" "Error: Invalid filename mode. Must be one of: auto, full, orig"
1319
                exit 1
1320
            fi
1321
            shift 2
Bogdan Timofte authored 9 months ago
1322
            ;;
Bogdan Timofte authored 9 months ago
1323
    # (conflict resolution option removed; let exiftool/filesystem handle naming conflicts)
Bogdan Timofte authored 9 months ago
1324
        --collect-unsortable)
1325
            COLLECT_UNSORTABLE=1
1326
            shift
1327
            ;;
Bogdan Timofte authored 8 months ago
1328
        --keep-empty-dirs)
1329
            CLEANUP_EMPTY_DIRS=0
1330
            shift
1331
            ;;
Bogdan Timofte authored 9 months ago
1332
        -s|--source)
1333
            SOURCE_PATTERNS+=("$2")
1334
            shift 2
1335
            ;;
1336
        -d|--destination)
1337
            DESTINATION="$2"
1338
            shift 2
1339
            ;;
1340
        -k|--keep-originals)
1341
            KEEP_ORIGINALS=1
1342
            shift
1343
            ;;
Bogdan Timofte authored 3 weeks ago
1344
        --verify-mode)
1345
            VERIFY_MODE="$2"
1346
            if [[ ! "$VERIFY_MODE" =~ ^(size|strict|none)$ ]]; then
1347
                print_color "$RED" "Error: Invalid verify mode. Must be one of: size, strict, none"
1348
                exit 1
1349
            fi
1350
            shift 2
1351
            ;;
Bogdan Timofte authored 2 weeks ago
1352
        --date-source)
1353
            DATE_SOURCE="$2"
1354
            if [[ ! "$DATE_SOURCE" =~ ^(auto|exif|filesystem)$ ]]; then
1355
                print_color "$RED" "Error: Invalid date source. Must be one of: auto, exif, filesystem"
1356
                exit 1
1357
            fi
1358
            shift 2
1359
            ;;
1360
        --sync-metadata)
1361
            SYNC_METADATA=1
1362
            shift
1363
            ;;
1364
        --unattended)
1365
            UNATTENDED=1
1366
            shift
1367
            ;;
Bogdan Timofte authored 2 weeks ago
1368
        --keep-gopro-sidecars)
1369
            CLEANUP_GOPRO_SIDECARS=0
1370
            shift
1371
            ;;
Bogdan Timofte authored 9 months ago
1372
        --dry-run)
1373
            DRY_RUN=1
1374
            shift
1375
            ;;
1376
        -v|--verbose)
1377
            VERBOSE=1
1378
            shift
1379
            ;;
1380
        -h|--help)
1381
            show_help
1382
            exit 0
1383
            ;;
1384
        --version)
1385
            show_version
1386
            exit 0
1387
            ;;
1388
        *)
1389
            print_color "$RED" "Error: Unknown option: $1"
1390
            echo "Use -h or --help for usage information."
1391
            exit 1
1392
            ;;
1393
    esac
1394
done
1395

            
Bogdan Timofte authored 2 weeks ago
1396
# Non-interactive execution cannot safely ask conflict questions.
1397
if [[ $UNATTENDED -eq 0 && ( ! -t 0 || ! -t 1 ) ]]; then
1398
    UNATTENDED=1
1399
fi
1400

            
Bogdan Timofte authored 9 months ago
1401
# If no organization is provided, leave ORGANIZATION empty and filename mode will decide naming
1402

            
Bogdan Timofte authored 3 weeks ago
1403
# If no source specified, default to current directory. Refuse to run when cwd is unsafe.
1404
if [[ ${#SOURCE_PATTERNS[@]} -eq 0 ]]; then
1405
    cwd=$(pwd)
1406
    # Resolve home and root paths
1407
    home_dir="$HOME"
1408
    case "$cwd" in
1409
        "$home_dir"|"/"|"/etc"|"/var"|"/bin"|"/sbin"|"/dev"|"/proc"|"/sys"|"/run"|"/usr"|"/lib"|"/lib64"|"/boot"|"/snap")
1410
            print_color "$RED" "Refusing to run with default source in unsafe directory: $cwd"
1411
            print_color "$RED" "Please specify $cwd as source explicitly with -s or run from a safer directory."
1412
            exit 1
1413
            ;;
1414
        *)
1415
            SOURCE_PATTERNS+=("$cwd")
1416
            ;;
1417
    esac
1418
fi
1419

            
1420
# Set default destination: if user didn't provide -d and a source was given, use first source + /sorted
Bogdan Timofte authored 9 months ago
1421
if [[ -z "$DESTINATION" ]]; then
Bogdan Timofte authored 9 months ago
1422
    if [[ ${#SOURCE_PATTERNS[@]} -gt 1 ]]; then
1423
        print_color "$RED" "Error: Multiple sources specified - destination (-d|--destination) is required when using multiple sources."
1424
        echo "Use -h for help."
1425
        exit 1
1426
    fi
1427

            
1428
    if [[ ${#SOURCE_PATTERNS[@]} -gt 0 ]]; then
1429
        first_source="${SOURCE_PATTERNS[0]}"
Bogdan Timofte authored 3 weeks ago
1430
        if [[ -d "$first_source" ]]; then
1431
            DESTINATION="$first_source/sorted"
1432
        elif [[ -f "$first_source" ]]; then
1433
            DESTINATION="$(dirname "$first_source")/sorted"
Bogdan Timofte authored 9 months ago
1434
        else
1435
            print_color "$YELLOW" "Warning: first source does not exist; defaulting destination to ./sorted"
1436
            DESTINATION="./sorted"
1437
        fi
1438
    else
1439
        DESTINATION="./sorted"
1440
    fi
Bogdan Timofte authored 9 months ago
1441
fi
1442

            
1443
# Convert destination to absolute path
1444
DESTINATION=$(cd "$(dirname "$DESTINATION")" 2>/dev/null && pwd)/$(basename "$DESTINATION") || DESTINATION=$(realpath "$DESTINATION" 2>/dev/null) || DESTINATION="$DESTINATION"
1445

            
1446
# Display configuration
1447
print_color "$GREEN" "$SCRIPT_NAME v$VERSION"
1448
echo ""
1449
echo "Configuration:"
1450
echo "  Organization pattern: $ORGANIZATION"
1451
echo "  Destination:         $DESTINATION"
1452
echo "  Keep originals:      $([ $KEEP_ORIGINALS -eq 1 ] && echo "Yes" || echo "No")"
Bogdan Timofte authored 3 weeks ago
1453
echo "  Verify mode:         $VERIFY_MODE"
Bogdan Timofte authored 2 weeks ago
1454
echo "  Date source:         $DATE_SOURCE"
1455
echo "  Sync metadata:       $([ $SYNC_METADATA -eq 1 ] && echo "Yes" || echo "No")"
1456
echo "  Unattended:          $([ $UNATTENDED -eq 1 ] && echo "Yes" || echo "No")"
Bogdan Timofte authored 9 months ago
1457
echo "  Dry run:             $([ $DRY_RUN -eq 1 ] && echo "Yes" || echo "No")"
Bogdan Timofte authored 8 months ago
1458
echo "  Keep empty dirs:     $([ $CLEANUP_EMPTY_DIRS -eq 0 ] && echo "Yes" || echo "No")"
Bogdan Timofte authored 9 months ago
1459
echo "  Verbose:             $([ $VERBOSE -eq 1 ] && echo "Yes" || echo "No")"
1460

            
1461
if [[ ${#SOURCE_PATTERNS[@]} -gt 0 ]]; then
1462
    echo "  Source patterns:"
1463
    for pattern in "${SOURCE_PATTERNS[@]}"; do
1464
        echo "    - $pattern"
1465
    done
1466
else
1467
    echo "  Source patterns:     All media files in current directory"
1468
fi
1469

            
1470
echo ""
1471

            
1472
# Check dependencies
1473
check_dependencies
1474

            
1475
# Create destination directory if it doesn't exist (unless dry run)
1476
if [[ $DRY_RUN -eq 0 ]]; then
1477
    if ! mkdir -p "$DESTINATION"; then
1478
        print_color "$RED" "Error: Cannot create destination directory: $DESTINATION"
1479
        exit 1
1480
    fi
1481
fi
1482

            
1483
# Find all source files
1484

            
1485
print_color "$BLUE" "Scanning for media files..."
1486
files=()
1487
while IFS= read -r file; do
1488
    files+=("$file")
1489
done < <(find_source_files)
Bogdan Timofte authored 2 weeks ago
1490
if [[ ${#files[@]} -gt 0 ]]; then
1491
    IFS=$'\n' files=($(printf '%s\n' "${files[@]}" | sort))
1492
    unset IFS
1493
fi
Bogdan Timofte authored 9 months ago
1494
TOTAL_FILES=${#files[@]}
1495

            
1496
if [[ $TOTAL_FILES -eq 0 ]]; then
1497
    print_color "$YELLOW" "No media files found matching the specified patterns."
1498
    exit 0
1499
fi
1500

            
1501
print_color "$BLUE" "Found $TOTAL_FILES media files to process"
1502
echo ""
1503

            
1504
# Process each file
1505

            
1506
FATAL_ERROR=0
1507
for file in "${files[@]}"; do
1508
    if [[ -f "$file" ]]; then
Bogdan Timofte authored 2 weeks ago
1509
        CURRENT_FILE_INDEX=$((CURRENT_FILE_INDEX + 1))
Bogdan Timofte authored 9 months ago
1510
        process_file "$file"
1511
        if [[ $FATAL_ERROR -eq 1 ]]; then
1512
            print_color "$RED" "Fatal error encountered. Stopping further processing."
1513
            break
1514
        fi
1515
    fi
1516
done
1517

            
Bogdan Timofte authored 8 months ago
1518
# Clean up empty directories if requested (default behavior)
1519
if [[ $CLEANUP_EMPTY_DIRS -eq 1 && $DRY_RUN -eq 0 ]]; then
1520
    print_color "$BLUE" "Cleaning up empty directories..."
1521
    # Find and remove empty directories under destination, but don't remove the destination itself
1522
    find "$DESTINATION" -type d -empty -not -path "$DESTINATION" -delete 2>/dev/null || true
1523
    print_color "$GREEN" "Empty directory cleanup completed"
1524
fi
1525

            
Bogdan Timofte authored 9 months ago
1526
# Show final report
1527
show_report
1528

            
1529
# Exit with appropriate code
1530
if [[ $ERROR_FILES -gt 0 ]]; then
1531
    exit 1
1532
else
1533
    exit 0
1534
fi