autoNAS / scripts / autonas-media-importer.sh
Newer Older
701 lines | 23.347kb
Bogdan Timofte authored 3 months ago
1
#!/bin/bash
2

            
3
# AutoNAS Media Importer
4
# Advanced media import engine that processes, organizes and imports media files from cameras
Bogdan Timofte authored 3 weeks ago
5
# Usage: autonas-media-importer.sh <source_mount> <destination_path> [options]
6
# Features: organization patterns (ymd/ym/d/h/m/y), GoPro handling, metadata sync
Bogdan Timofte authored 3 months ago
7

            
8
LOG_TAG="autonas-import"
Bogdan Timofte authored 3 weeks ago
9
VERSION="2.0"
10

            
11
# Default values (compatible with original)
12
ORGANIZATION="ymd"
13
FILENAME_MODE="full"
14
VERIFY_MODE="size"
15
DATE_SOURCE="auto"
16
SYNC_METADATA=0
17
UNATTENDED=1
18
COLLECT_UNSORTABLE=0
19
KEEP_EMPTY_DIRS=1
20
DRY_RUN=0
21
VERBOSE=0
22
KEEP_ORIGINALS=0
23
FILE_LIMIT=0
24
CONFLICT_APPLY_ALL=""
25
RESOLVED_DESTINATION_PATH=""
26
RESERVED_DESTINATION_PATHS=()
27

            
28
TOTAL_FILES=0
29
PROCESSED_FILES=0
30
SKIPPED_FILES=0
31
ERROR_FILES=0
32
TOTAL_SIZE=0
33
PROCESSED_SIZE=0
34
START_TIME=$(date +%s)
35

            
36
RED='\033[0;31m'
37
GREEN='\033[0;32m'
38
YELLOW='\033[1;33m'
39
BLUE=$'\033[1;36m'
40
NC='\033[0m'
41

            
42
MEDIA_EXTENSIONS=("*.jpg" "*.jpeg" "*.png" "*.tiff" "*.tif" "*.cr2" "*.nef" "*.arw" "*.dng" "*.raw" "*.mp4" "*.mov" "*.avi" "*.mts" "*.m2ts" "*.mkv" "*.wmv" "*.3gp" "*.m4v")
43

            
44
print_color() {
45
    local color="$1"
46
    local message="$2"
47
    echo -e "${color}${message}${NC}"
48
}
Bogdan Timofte authored 3 months ago
49

            
50
log_message() {
51
    local message="$1"
Bogdan Timofte authored 3 weeks ago
52
    local priority="${2:-info}"
53

            
Bogdan Timofte authored 3 months ago
54
    logger -p "local0.$priority" -t "$LOG_TAG" "$message"
Bogdan Timofte authored 3 weeks ago
55

            
Bogdan Timofte authored 3 months ago
56
    if [ -t 1 ]; then
Bogdan Timofte authored 3 weeks ago
57
        case "$priority" in
58
            "err")
59
                print_color "$RED" "$(date '+%Y-%m-%d %H:%M:%S') - ERROR: $message" >&2
60
                ;;
61
            "warning")
62
                print_color "$YELLOW" "$(date '+%Y-%m-%d %H:%M:%S') - WARNING: $message"
63
                ;;
64
            "info")
65
                if [[ $VERBOSE -eq 1 ]]; then
66
                    print_color "$BLUE" "$(date '+%Y-%m-%d %H:%M:%S') - INFO: $message"
67
                fi
68
                ;;
69
            *)
70
                echo "$(date '+%Y-%m-%d %H:%M:%S') - $message"
71
                ;;
72
        esac
Bogdan Timofte authored 3 months ago
73
    fi
74
}
75

            
Bogdan Timofte authored 3 weeks ago
76
show_help() {
77
    cat << EOF
78
AutoNAS Media Importer v$VERSION
79
Advanced camera import engine
80

            
81
Usage:
82
    $0 <source_mount> <destination_path> [OPTIONS]
83

            
84
Arguments:
85
    source_mount      Mount point of camera
86
    destination_path  Destination directory for imported files
87

            
88
Options:
89
    -o, --organization   y|m|d|h|ym|ymd (default: ymd)
90
    -F, --filename-mode  auto|full|orig (default: full)
91
    --date-source        auto|exif|filesystem (default: auto)
92
    --sync-metadata      Write date into destination metadata
93
    --collect-unsortable Put undated files into DEST/unsortable
94
    --keep-empty-dirs    Keep empty directories after processing
95
    --dry-run            Show actions without changing files
96
    --keep-originals     Copy files instead of moving
97
    --verbose            Enable verbose output
98
    --limit N            Process only N files
99
    -h, --help           Show this help
100
EOF
101
}
102

            
103
check_dependencies() {
104
    if ! command -v exiftool &> /dev/null; then
105
        print_color "$RED" "ERROR: exiftool is required but not installed"
106
        exit 1
107
    fi
108
}
109

            
110
# Utility functions
111
get_file_size() {
112
    local file="$1"
113
    if [[ -f "$file" ]]; then
114
        if stat -c%s "$file" >/dev/null 2>&1; then
115
            stat -c%s "$file" 2>/dev/null
116
        elif stat -f%z "$file" >/dev/null 2>&1; then
117
            stat -f%z "$file" 2>/dev/null
118
        else
119
            ls -ln "$file" | awk '{print $5}'
120
        fi
121
    else
122
        echo "0"
123
    fi
124
}
125

            
126
is_gopro_media_file() {
127
    local filename
128
    filename=$(basename "$1")
129
    [[ "$filename" =~ ^G[HPX][0-9]{6}\.[Mm][Pp]4$ ]]
130
}
131

            
132
should_prefer_gopro_filesystem_date() {
133
    is_gopro_media_file "$1"
134
}
135

            
136
filesystem_date_reference() {
137
    local file="$1"
138
    local dir base stem ext sidecar_ext sidecar
139
    dir=$(dirname "$file")
140
    base=$(basename "$file")
141
    stem="${base%.*}"
142
    ext="${base##*.}"
143

            
144
    if [[ "$ext" =~ ^([Mm][Pp]4)$ ]]; then
145
        for sidecar_ext in THM thm LRV lrv; do
146
            sidecar="$dir/$stem.$sidecar_ext"
147
            if [[ -f "$sidecar" ]]; then
148
                echo "$sidecar"
149
                return 0
150
            fi
151
        done
152
    fi
153

            
154
    echo "$file"
155
}
156

            
157
extract_filesystem_date() {
158
    local file="$1"
159
    if [[ ! -e "$file" ]]; then
160
        return 2
161
    fi
162

            
163
    local epoch=""
164
    if [[ "$OSTYPE" == "darwin"* ]]; then
165
        epoch=$(stat -f %m "$file" 2>/dev/null || echo "")
166
        [[ -n "$epoch" ]] || return 2
167
        date -j -r "$epoch" "+%Y-%m-%d %H:%M:%S" 2>/dev/null || return 2
168
    else
169
        epoch=$(stat -c %Y "$file" 2>/dev/null || echo "")
170
        [[ -n "$epoch" ]] || return 2
171
        date -d "@$epoch" "+%Y-%m-%d %H:%M:%S" 2>/dev/null || return 2
172
    fi
173
}
174

            
175
destination_path_unavailable() {
176
    local candidate="$1"
177
    [[ -e "$candidate" ]] && return 0
178
    for reserved_path in "${RESERVED_DESTINATION_PATHS[@]}"; do
179
        [[ "$reserved_path" == "$candidate" ]] && return 0
180
    done
181
    return 1
182
}
183

            
184
reserve_destination_path() {
185
    local candidate="$1"
186
    if [[ -n "$candidate" ]]; then
187
        RESERVED_DESTINATION_PATHS+=("$candidate")
188
    fi
189
}
190

            
191
extract_file_date() {
192
    local file="$1"
193
    local create_date=""
194
    local date_source=""
195

            
196
    if [[ "$DATE_SOURCE" == "filesystem" ]] || { [[ "$DATE_SOURCE" == "auto" ]] && should_prefer_gopro_filesystem_date "$file"; }; then
197
        local filesystem_reference
198
        filesystem_reference=$(filesystem_date_reference "$file")
199
        create_date=$(extract_filesystem_date "$filesystem_reference") || return 2
200
        if is_gopro_media_file "$file"; then
201
            echo "$create_date|Filesystem:GoPro"
202
        else
203
            echo "$create_date|Filesystem"
204
        fi
205
        return 0
206
    fi
207

            
208
    # Try EXIF data
209
    local exif_output=$(exiftool -G1 -s -CreateDate -DateTimeOriginal -DateTime "$file" 2>/dev/null)
210
    if [[ -n "$exif_output" ]]; then
211
        while IFS= read -r line; do
212
            if [[ "$line" =~ ^\[([^\]]+)\][[:space:]]*([^:]+)[[:space:]]*:[[:space:]]*(.+)$ ]]; then
213
                local group="${BASH_REMATCH[1]}"
214
                local tag="${BASH_REMATCH[2]}"
215
                local value="${BASH_REMATCH[3]}"
216
                tag=$(echo "$tag" | sed 's/[[:space:]]*$//')
217

            
218
                if [[ "$tag" == "DateTimeOriginal" && -z "$create_date" ]]; then
219
                    create_date="$value"
220
                    date_source="$group:$tag"
221
                elif [[ "$tag" == "CreateDate" && "$date_source" != *"DateTimeOriginal"* ]]; then
222
                    create_date="$value"
223
                    date_source="$group:$tag"
224
                elif [[ "$tag" == "DateTime" && -z "$create_date" ]]; then
225
                    create_date="$value"
226
                    date_source="$group:$tag"
227
                fi
228
            fi
229
        done <<< "$exif_output"
230
    fi
231

            
232
    # Fallback to filesystem in auto mode
233
    if [[ -z "$create_date" && "$DATE_SOURCE" == "auto" ]]; then
234
        local filesystem_reference
235
        filesystem_reference=$(filesystem_date_reference "$file")
236
        create_date=$(extract_filesystem_date "$filesystem_reference") || return 2
237
        date_source="Filesystem"
238
    fi
239

            
240
    [[ -z "$create_date" ]] && return 2
241

            
242
    # Convert EXIF format (YYYY:MM:DD HH:MM:SS) to standard
243
    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
244
        local year="${BASH_REMATCH[1]}"
245
        local month=$(printf "%02d" "$((10#${BASH_REMATCH[2]}))")
246
        local day=$(printf "%02d" "$((10#${BASH_REMATCH[3]}))")
247
        local hour=$(printf "%02d" "$((10#${BASH_REMATCH[4]}))")
248
        local minute=$(printf "%02d" "$((10#${BASH_REMATCH[5]}))")
249
        local second=$(printf "%02d" "$((10#${BASH_REMATCH[6]}))")
250
        create_date="$year-$month-$day $hour:$minute:$second"
251
    fi
252

            
253
    # QuickTime UTC conversion
254
    if [[ "$date_source" == *"QuickTime"* ]]; then
255
        if [[ "$OSTYPE" == "darwin"* ]]; then
256
            local utc_timestamp=$(TZ=UTC date -j -f "%Y-%m-%d %H:%M:%S" "$create_date" "+%s" 2>/dev/null)
257
            [[ -n "$utc_timestamp" ]] && create_date=$(date -j -r "$utc_timestamp" "+%Y-%m-%d %H:%M:%S" 2>/dev/null)
258
        else
259
            local utc_timestamp=$(date -d "$create_date UTC" "+%s" 2>/dev/null)
260
            [[ -n "$utc_timestamp" ]] && create_date=$(date -d "@$utc_timestamp" "+%Y-%m-%d %H:%M:%S" 2>/dev/null)
261
        fi
262
    fi
263

            
264
    echo "$create_date|$date_source"
265
    return 0
266
}
267

            
268
generate_destination_path() {
269
    local date_str="$1"
270
    local original_filename="$2"
271
    local base_destination="$3"
272

            
273
    local year month day hour minute second
274
    if [[ "$OSTYPE" == "darwin"* ]]; then
275
        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
276
            year="${BASH_REMATCH[1]}"
277
            month=$(printf "%02d" "$((10#${BASH_REMATCH[2]}))")
278
            day=$(printf "%02d" "$((10#${BASH_REMATCH[3]}))")
279
            hour=$(printf "%02d" "$((10#${BASH_REMATCH[4]}))")
280
            minute=$(printf "%02d" "$((10#${BASH_REMATCH[5]}))")
281
            second=$(printf "%02d" "$((10#${BASH_REMATCH[6]}))")
282
        else
283
            return 1
284
        fi
285
    else
286
        year=$(date -d "$date_str" "+%Y" 2>/dev/null)
287
        month=$(date -d "$date_str" "+%m" 2>/dev/null)
288
        day=$(date -d "$date_str" "+%d" 2>/dev/null)
289
        hour=$(date -d "$date_str" "+%H" 2>/dev/null)
290
        minute=$(date -d "$date_str" "+%M" 2>/dev/null)
291
        second=$(date -d "$date_str" "+%S" 2>/dev/null)
292
    fi
293

            
294
    [[ -z "$year" || -z "$month" || -z "$day" ]] && return 1
295

            
296
    local extension="${original_filename##*.}"
297
    local lowercase_ext=$(echo "$extension" | tr '[:upper:]' '[:lower:]')
298

            
299
    local dir_path=""
300
    local filename=""
301

            
302
    case "$ORGANIZATION" in
303
        "y")
304
            dir_path="$base_destination/$year"
305
            filename="${month}-${day}_${hour}-${minute}-${second}.${lowercase_ext}"
306
            ;;
307
        "m")
308
            dir_path="$base_destination/$year/$month"
309
            filename="${day}_${hour}-${minute}-${second}.${lowercase_ext}"
310
            ;;
311
        "d")
312
            dir_path="$base_destination/$year/$month/$day"
313
            filename="${hour}-${minute}-${second}.${lowercase_ext}"
314
            ;;
315
        "h")
316
            dir_path="$base_destination/$year/$month/$day/$hour"
317
            filename="${minute}-${second}.${lowercase_ext}"
318
            ;;
319
        "ym")
320
            dir_path="$base_destination/${year}-${month}"
321
            filename="${day}_${hour}-${minute}-${second}.${lowercase_ext}"
322
            ;;
323
        "ymd")
324
            dir_path="$base_destination/${year}-${month}-${day}"
325
            filename="${hour}-${minute}-${second}.${lowercase_ext}"
326
            ;;
327
        *)
328
            return 1
329
            ;;
330
    esac
331

            
332
    case "$FILENAME_MODE" in
333
        orig)
334
            filename="$original_filename"
335
            ;;
336
        full)
337
            filename="${year}-${month}-${day}_${hour}-${minute}-${second}.${lowercase_ext}"
338
            ;;
339
        auto)
340
            ;;
341
        *)
342
            filename="${year}-${month}-${day}_${hour}-${minute}-${second}.${lowercase_ext}"
343
            ;;
344
    esac
345

            
346
    echo "$dir_path/$filename"
347
    return 0
348
}
349

            
350
ensure_unique_destination_path() {
351
    local desired_path="$1"
352
    local counter=1
353
    local resolved_path="$desired_path"
354

            
355
    while destination_path_unavailable "$resolved_path"; do
356
        local dir=$(dirname "$desired_path")
357
        local base=$(basename "$desired_path")
358
        local name_without_ext="${base%.*}"
359
        local ext="${base##*.}"
360

            
361
        if [[ "$ext" == "$base" ]]; then
362
            resolved_path="$dir/${name_without_ext}_${counter}"
363
        else
364
            resolved_path="$dir/${name_without_ext}_${counter}.$ext"
365
        fi
366
        counter=$((counter + 1))
367

            
368
        [[ $counter -gt 1000 ]] && return 1
369
    done
370

            
371
    echo "$resolved_path"
372
    return 0
373
}
374

            
375
resolve_destination_conflict() {
376
    local desired_path="$1"
377
    RESOLVED_DESTINATION_PATH=""
378

            
379
    [[ -z "$desired_path" ]] && return 1
380

            
381
    if ! destination_path_unavailable "$desired_path"; then
382
        RESOLVED_DESTINATION_PATH="$desired_path"
383
        reserve_destination_path "$RESOLVED_DESTINATION_PATH"
384
        return 0
385
    fi
386

            
387
    local resolved_path
388
    resolved_path=$(ensure_unique_destination_path "$desired_path")
389
    [[ -z "$resolved_path" ]] && return 1
390

            
391
    RESOLVED_DESTINATION_PATH="$resolved_path"
392
    reserve_destination_path "$RESOLVED_DESTINATION_PATH"
393
    return 0
394
}
395

            
396
safe_mv() {
397
    local src="$1" dst="$2"
398
    mv "$src" "$dst" 2> >(grep -v "set flags (was:" >&2)
399
}
400

            
401
# Process a single file
402
process_file() {
403
    local file="$1"
404
    local relative_path="${file#$SOURCE_MOUNT/}"
405
    local file_size=$(get_file_size "$file")
406
    TOTAL_SIZE=$((TOTAL_SIZE + file_size))
407

            
408
    # Check mount point
409
    if ! mountpoint -q "$SOURCE_MOUNT" 2>/dev/null; then
410
        log_message "Error: Source mount point is no longer available" "err"
411
        return 1
412
    fi
413

            
414
    # Check if file still exists
415
    if [[ ! -f "$file" ]]; then
416
        log_message "Error: File no longer exists: $relative_path" "err"
417
        log_message "Camera appears to be disconnected, stopping import" "warning"
418
        exit 1
419
    fi
420

            
421
    [[ $VERBOSE -eq 1 ]] && log_message "Processing: $relative_path" "info"
422

            
423
    # Extract date
424
    local date_info=$(extract_file_date "$file")
425
    local extract_status=$?
426

            
427
    if [[ $extract_status -eq 2 ]]; then
428
        if [[ $COLLECT_UNSORTABLE -eq 1 ]]; then
429
            local unsortable_dir="$DESTINATION/unsortable"
430
            mkdir -p "$unsortable_dir"
431
            local unsortable_path="$unsortable_dir/$(basename "$file")"
432
            resolve_destination_conflict "$unsortable_path"
433
            [[ $? -eq 0 ]] && unsortable_path="$RESOLVED_DESTINATION_PATH"
434
            if [[ $DRY_RUN -eq 0 ]]; then
435
                safe_mv "$file" "$unsortable_path"
436
                log_message "Moved to unsortable: $relative_path" "info"
437
            fi
438
        else
439
            log_message "No date found for $relative_path - skipping" "warning"
440
        fi
441
        SKIPPED_FILES=$((SKIPPED_FILES + 1))
442
        return 1
443
    elif [[ $extract_status -ne 0 ]]; then
444
        log_message "Failed to extract date from $relative_path" "warning"
445
        SKIPPED_FILES=$((SKIPPED_FILES + 1))
446
        return 1
447
    fi
448

            
449
    local date_str="${date_info%|*}"
450
    local date_source="${date_info#*|}"
451
    [[ $VERBOSE -eq 1 ]] && log_message "Date: $date_str (from $date_source)" "info"
452

            
453
    # Generate destination path
454
    local original_basename=$(basename "$file")
455
    local dest_path=$(generate_destination_path "$date_str" "$original_basename" "$DESTINATION")
456
    [[ $? -ne 0 ]] && { log_message "Could not generate destination path for $relative_path" "err"; ERROR_FILES=$((ERROR_FILES + 1)); return 1; }
457

            
458
    local desired_dest_path="$dest_path"
459
    resolve_destination_conflict "$dest_path"
460
    [[ $? -eq 0 ]] && dest_path="$RESOLVED_DESTINATION_PATH" || { ERROR_FILES=$((ERROR_FILES + 1)); return 1; }
461

            
462
    [[ "$dest_path" != "$desired_dest_path" ]] && log_message "Destination conflict resolved" "info"
463

            
464
    local dest_dir=$(dirname "$dest_path")
465

            
466
    if [[ $DRY_RUN -eq 1 ]]; then
467
        if [[ $KEEP_ORIGINALS -eq 1 ]]; then
468
            echo "Would copy: $relative_path -> ${dest_path#$DESTINATION/}"
469
        else
470
            echo "Would move: $relative_path -> ${dest_path#$DESTINATION/}"
471
        fi
472
        PROCESSED_FILES=$((PROCESSED_FILES + 1))
473
        PROCESSED_SIZE=$((PROCESSED_SIZE + file_size))
474
        return 0
475
    fi
476

            
477
    mkdir -p "$dest_dir" || { log_message "Could not create directory: $dest_dir" "err"; ERROR_FILES=$((ERROR_FILES + 1)); return 1; }
478

            
479
    if [[ $KEEP_ORIGINALS -eq 1 ]]; then
480
        if cp "$file" "$dest_path"; then
481
            log_message "Copied: $relative_path" "info"
482
            [[ $VERBOSE -eq 1 ]] && echo "✓ Copied"
483
            PROCESSED_FILES=$((PROCESSED_FILES + 1))
484
            PROCESSED_SIZE=$((PROCESSED_SIZE + file_size))
485
            return 0
486
        else
487
            log_message "Failed to copy $relative_path" "err"
488
            ERROR_FILES=$((ERROR_FILES + 1))
489
            return 1
490
        fi
491
    else
492
        if safe_mv "$file" "$dest_path"; then
493
            log_message "Moved: $relative_path" "info"
494
            [[ $VERBOSE -eq 1 ]] && echo "✓ Moved"
495
            PROCESSED_FILES=$((PROCESSED_FILES + 1))
496
            PROCESSED_SIZE=$((PROCESSED_SIZE + file_size))
497
            return 0
498
        else
499
            log_message "Failed to move $relative_path" "err"
500
            ERROR_FILES=$((ERROR_FILES + 1))
501
            return 1
502
        fi
503
    fi
Bogdan Timofte authored 3 months ago
504
}
505

            
506
# Parse command line arguments
507
SOURCE_MOUNT=""
508
DESTINATION=""
509

            
510
while [[ $# -gt 0 ]]; do
511
    case $1 in
Bogdan Timofte authored 3 weeks ago
512
        -o|--organization)
513
            ORGANIZATION="$2"
514
            [[ ! "$ORGANIZATION" =~ ^(y|m|d|h|ym|ymd)$ ]] && { echo "Invalid organization pattern"; exit 1; }
515
            shift 2
516
            ;;
517
        -F|--filename-mode)
518
            FILENAME_MODE="$2"
519
            [[ ! "$FILENAME_MODE" =~ ^(auto|full|orig)$ ]] && { echo "Invalid filename mode"; exit 1; }
520
            shift 2
521
            ;;
522
        --date-source)
523
            DATE_SOURCE="$2"
524
            [[ ! "$DATE_SOURCE" =~ ^(auto|exif|filesystem)$ ]] && { echo "Invalid date source"; exit 1; }
525
            shift 2
526
            ;;
527
        --sync-metadata)
528
            SYNC_METADATA=1
529
            shift
530
            ;;
531
        --collect-unsortable)
532
            COLLECT_UNSORTABLE=1
533
            shift
534
            ;;
535
        --keep-empty-dirs)
536
            KEEP_EMPTY_DIRS=0
537
            shift
538
            ;;
Bogdan Timofte authored 3 months ago
539
        --dry-run)
540
            DRY_RUN=1
541
            shift
542
            ;;
543
        --keep-originals)
544
            KEEP_ORIGINALS=1
545
            shift
546
            ;;
Bogdan Timofte authored 3 weeks ago
547
        -v|--verbose)
Bogdan Timofte authored 3 months ago
548
            VERBOSE=1
549
            shift
550
            ;;
551
        --limit)
552
            FILE_LIMIT="$2"
Bogdan Timofte authored 3 weeks ago
553
            [[ ! "$FILE_LIMIT" =~ ^[0-9]+$ ]] && { echo "Error: --limit requires a number"; exit 1; }
Bogdan Timofte authored 3 months ago
554
            shift 2
555
            ;;
Bogdan Timofte authored 3 weeks ago
556
        -h|--help)
557
            show_help
Bogdan Timofte authored 3 months ago
558
            exit 0
559
            ;;
560
        -*)
561
            echo "Unknown option: $1"
562
            exit 1
563
            ;;
564
        *)
565
            if [[ -z "$SOURCE_MOUNT" ]]; then
566
                SOURCE_MOUNT="$1"
567
            elif [[ -z "$DESTINATION" ]]; then
568
                DESTINATION="$1"
569
            else
570
                echo "Too many arguments"
571
                exit 1
572
            fi
573
            shift
574
            ;;
575
    esac
576
done
577

            
Bogdan Timofte authored 3 weeks ago
578
[[ -z "$SOURCE_MOUNT" || -z "$DESTINATION" ]] && { echo "Error: Both source_mount and destination_path are required"; show_help; exit 1; }
Bogdan Timofte authored 3 months ago
579

            
Bogdan Timofte authored 3 weeks ago
580
# Validate paths
581
[[ ! -d "$SOURCE_MOUNT" ]] && { log_message "Error: Source mount point does not exist: $SOURCE_MOUNT" "err"; exit 1; }
582
! mountpoint -q "$SOURCE_MOUNT" 2>/dev/null && log_message "Warning: Source path is not a mount point: $SOURCE_MOUNT" "warning"
Bogdan Timofte authored 3 months ago
583

            
584
if [[ $DRY_RUN -eq 0 ]]; then
Bogdan Timofte authored 3 weeks ago
585
    mkdir -p "$DESTINATION" || { log_message "Error: Cannot create destination directory: $DESTINATION" "err"; exit 1; }
Bogdan Timofte authored 3 months ago
586
fi
587

            
Bogdan Timofte authored 3 weeks ago
588
check_dependencies
Bogdan Timofte authored 3 months ago
589

            
Bogdan Timofte authored 3 weeks ago
590
# Find camera directories
Bogdan Timofte authored 3 months ago
591
find_camera_directories() {
592
    local search_patterns=("DCIM" "PRIVATE" "MP_ROOT" "AVCHD" "Photos" "Videos")
593
    local found_dirs=()
Bogdan Timofte authored 3 weeks ago
594

            
595
    ! timeout 3 ls "$SOURCE_MOUNT" >/dev/null 2>&1 && { log_message "Error: Mount point is not accessible" "err"; exit 1; }
596

            
Bogdan Timofte authored 3 months ago
597
    for pattern in "${search_patterns[@]}"; do
598
        while IFS= read -r -d '' dir; do
599
            found_dirs+=("$dir")
600
        done < <(timeout 5 find "$SOURCE_MOUNT" -maxdepth 3 -type d -iname "$pattern" -print0 2>/dev/null)
601
    done
Bogdan Timofte authored 3 weeks ago
602

            
Bogdan Timofte authored 3 months ago
603
    if [[ ${#found_dirs[@]} -eq 0 ]]; then
604
        log_message "No camera directories found, searching for media files..." "info"
Bogdan Timofte authored 3 weeks ago
605
        for ext in "${MEDIA_EXTENSIONS[@]}"; do
Bogdan Timofte authored 3 months ago
606
            while IFS= read -r -d '' file; do
607
                local dir=$(dirname "$file")
Bogdan Timofte authored 3 weeks ago
608
                local already_added=0
609
                for found_dir in "${found_dirs[@]}"; do
610
                    [[ "$found_dir" == "$dir" ]] && { already_added=1; break; }
611
                done
612
                [[ $already_added -eq 0 ]] && found_dirs+=("$dir")
Bogdan Timofte authored 3 months ago
613
            done < <(timeout 5 find "$SOURCE_MOUNT" -maxdepth 3 -type f -iname "$ext" -print0 2>/dev/null)
614
        done
615
    fi
Bogdan Timofte authored 3 weeks ago
616

            
Bogdan Timofte authored 3 months ago
617
    printf '%s\n' "${found_dirs[@]}" | sort -u
618
}
619

            
620
log_message "Starting camera import from $SOURCE_MOUNT to $DESTINATION" "info"
Bogdan Timofte authored 3 weeks ago
621
[[ $DRY_RUN -eq 1 ]] && log_message "DRY RUN MODE - No files will be moved/copied" "info"
622
[[ $KEEP_ORIGINALS -eq 1 ]] && log_message "KEEP ORIGINALS MODE - Files will be copied instead of moved" "info"
Bogdan Timofte authored 3 months ago
623

            
624
log_message "Scanning for camera directories..." "info"
625
camera_dirs=$(find_camera_directories)
626

            
627
if [[ -z "$camera_dirs" ]]; then
628
    log_message "No camera directories or media files found in $SOURCE_MOUNT" "warning"
629
    exit 0
630
fi
631

            
632
echo "Found camera directories:"
633
echo "$camera_dirs" | while IFS= read -r dir; do
634
    echo "  $dir"
635
done
636

            
Bogdan Timofte authored 3 weeks ago
637
# Clean up GLV files (preview files - usually not needed)
Bogdan Timofte authored 3 months ago
638
log_message "Cleaning up GLV preview files..." "info"
639
glv_count=0
640
while IFS= read -r dir; do
641
    if [[ $DRY_RUN -eq 1 ]]; then
642
        glv_files=$(find "$dir" -type f -iname "*.glv" 2>/dev/null | wc -l)
Bogdan Timofte authored 3 weeks ago
643
        [[ $glv_files -gt 0 ]] && echo "Would delete $glv_files GLV files from $dir" && glv_count=$((glv_count + glv_files))
Bogdan Timofte authored 3 months ago
644
    else
645
        while IFS= read -r -d '' glv_file; do
Bogdan Timofte authored 3 weeks ago
646
            rm "$glv_file" 2>/dev/null && glv_count=$((glv_count + 1))
Bogdan Timofte authored 3 months ago
647
        done < <(find "$dir" -type f -iname "*.glv" -print0 2>/dev/null)
648
    fi
649
done <<< "$camera_dirs"
650

            
Bogdan Timofte authored 3 weeks ago
651
[[ $glv_count -gt 0 ]] && log_message "GLV files cleaned up: $glv_count" "info"
Bogdan Timofte authored 3 months ago
652

            
653
# Process media files
654
log_message "Processing media files..." "info"
655

            
656
max_files_to_show=20
657
files_shown=0
658
files_processed_count=0
659

            
660
while IFS= read -r dir; do
Bogdan Timofte authored 3 weeks ago
661
    ! mountpoint -q "$SOURCE_MOUNT" 2>/dev/null && { log_message "Camera disconnected, stopping import" "warning"; break; }
662

            
663
    for ext in "${MEDIA_EXTENSIONS[@]}"; do
Bogdan Timofte authored 3 months ago
664
        while IFS= read -r -d '' file; do
Bogdan Timofte authored 3 weeks ago
665
            TOTAL_FILES=$((TOTAL_FILES + 1))
Bogdan Timofte authored 3 months ago
666
            files_processed_count=$((files_processed_count + 1))
Bogdan Timofte authored 3 weeks ago
667

            
668
            ! mountpoint -q "$SOURCE_MOUNT" 2>/dev/null && { log_message "Camera disconnected during processing" "warning"; exit 1; }
669

            
670
            [[ $FILE_LIMIT -gt 0 && $files_processed_count -gt $FILE_LIMIT ]] && { echo "Reached file limit"; break 3; }
671

            
Bogdan Timofte authored 3 months ago
672
            if [[ $DRY_RUN -eq 1 && $files_shown -ge $max_files_to_show ]]; then
Bogdan Timofte authored 3 weeks ago
673
                [[ $files_shown -eq $max_files_to_show ]] && echo "... (limiting output in dry-run mode)"
674
                ((files_shown++))
Bogdan Timofte authored 3 months ago
675
            else
Bogdan Timofte authored 3 weeks ago
676
                [[ $DRY_RUN -eq 1 ]] && ((files_shown++))
677
                process_file "$file"
Bogdan Timofte authored 3 months ago
678
            fi
679
        done < <(find "$dir" -type f -iname "$ext" -print0 2>/dev/null)
680
    done
681
done <<< "$camera_dirs"
682

            
683
# Summary
Bogdan Timofte authored 3 weeks ago
684
log_message "Import completed: $PROCESSED_FILES/$TOTAL_FILES files processed successfully" "info"
685
[[ $ERROR_FILES -gt 0 ]] && log_message "Import had errors: $ERROR_FILES files failed" "warning"
Bogdan Timofte authored 3 months ago
686

            
687
echo ""
688
echo "=== Import Summary ==="
Bogdan Timofte authored 3 weeks ago
689
echo "Total files found: $TOTAL_FILES"
690
echo "Successfully processed: $PROCESSED_FILES"
691
echo "Skipped: $SKIPPED_FILES"
692
echo "Errors: $ERROR_FILES"
693
[[ $glv_count -gt 0 ]] && echo "GLV files cleaned up: $glv_count"
Bogdan Timofte authored 3 months ago
694

            
Bogdan Timofte authored 3 weeks ago
695
# Cleanup empty directories
696
if [[ $KEEP_EMPTY_DIRS -eq 1 && $DRY_RUN -eq 0 ]]; then
697
    log_message "Cleaning up empty directories..." "info"
698
    find "$DESTINATION" -type d -empty -not -path "$DESTINATION" -delete 2>/dev/null || true
Bogdan Timofte authored 3 months ago
699
fi
Bogdan Timofte authored 3 weeks ago
700

            
701
[[ $ERROR_FILES -gt 0 ]] && exit 1 || exit 0