autoNAS / scripts / autonas.sh
Newer Older
d426b0e 3 months ago History
1053 lines | 33.791kb
Bogdan Timofte authored 3 months ago
1
#!/bin/bash
2

            
3
# AutoNAS - Unified AutoNAS Management Tool
4
# Combines manager, configuration, and all other functionality into one script
5
# Usage: autonas <command> [options]
6

            
7
# Load core AutoNAS library
8
if [[ -f "/usr/local/bin/autonas-core.sh" ]]; then
9
    source "/usr/local/bin/autonas-core.sh"
10
else
11
    echo "Error: AutoNAS core library not found at /usr/local/bin/autonas-core.sh" >&2
12
    exit 1
13
fi
14

            
15
# Function to handle disk attachment
16
handle_attach() {
Bogdan Timofte authored 3 months ago
17
    local identifier="$1"
18

            
19
    log_message "AutoNAS attach operation started for identifier: $identifier"
20

            
21
    # Get configuration by UUID, name, or mount point
Bogdan Timofte authored 3 months ago
22
    local config
Bogdan Timofte authored 3 months ago
23
    config=$(resolve_config_identifier "$identifier")
24

            
Bogdan Timofte authored 3 months ago
25
    if [[ -z "$config" ]]; then
Bogdan Timofte authored 3 months ago
26
        log_message "No configuration found for identifier: $identifier - disk will be ignored"
Bogdan Timofte authored 3 months ago
27
        log_message "To configure this disk, run: autonas-config.sh add"
28
        return 1
29
    fi
Bogdan Timofte authored 3 months ago
30

            
Bogdan Timofte authored 3 months ago
31
    # Parse configuration
32
    local parsed
33
    parsed=($(parse_config "$config"))
34
    local cfg_uuid="${parsed[0]}"
35
    local name="${parsed[1]}"
36
    local ip="${parsed[2]}"
37
    local interface="${parsed[3]}"
38
    local mount_point="${parsed[4]}"
39
    local nfs_options="${parsed[5]}"
Bogdan Timofte authored 3 months ago
40

            
41
    log_message "Handling disk attachment for UUID: $cfg_uuid"
Bogdan Timofte authored 3 months ago
42
    log_message "Processing disk: $name (IP: $ip, Mount: $mount_point)"
Bogdan Timofte authored 3 months ago
43

            
Bogdan Timofte authored 3 months ago
44
    # Handle different disk types
45
    if [[ "$ip" == "IMPORT" && "$interface" == "IMPORT" ]]; then
46
        # Camera import workflow: mount temporarily, import, then unmount
Bogdan Timofte authored 3 months ago
47
        log_message "Detected camera import configuration for UUID: $cfg_uuid"
48

            
Bogdan Timofte authored 3 months ago
49
        # Mount disk for import
Bogdan Timofte authored 3 months ago
50
        if mount_disk "$cfg_uuid" "$mount_point"; then
Bogdan Timofte authored 3 months ago
51
            # Start import process
Bogdan Timofte authored 3 months ago
52
            handle_camera_import "$cfg_uuid" "$mount_point" "$nfs_options"
Bogdan Timofte authored 3 months ago
53
            return $?
54
        else
55
            log_message "Error: Failed to mount camera device" "err"
56
            return 1
57
        fi
58
    elif [[ "$ip" == "LOCAL" ]]; then
59
        # Local mount only (no network sharing)
Bogdan Timofte authored 3 months ago
60
        if mount_disk "$cfg_uuid" "$mount_point"; then
Bogdan Timofte authored 3 months ago
61
            log_message "Local disk mounted successfully at $mount_point"
62
            return 0
63
        else
64
            return 1
65
        fi
66
    else
67
        # Regular NFS workflow: activate IP, mount, export via NFS
68
        if activate_ip "$ip" "$interface"; then
Bogdan Timofte authored 3 months ago
69
            if mount_disk "$cfg_uuid" "$mount_point"; then
Bogdan Timofte authored 3 months ago
70
                if add_nfs_export "$mount_point" "$nfs_options"; then
71
                    log_message "Disk attached successfully: $name"
72
                    return 0
73
                else
74
                    log_message "Warning: Disk mounted but NFS export failed" "warning"
75
                    return 1
76
                fi
77
            else
78
                deactivate_ip "$ip" "$interface"
79
                return 1
80
            fi
81
        else
82
            return 1
83
        fi
84
    fi
85
}
86

            
87
# Function to handle disk detachment
88
handle_detach() {
Bogdan Timofte authored 3 months ago
89
    local identifier="$1"
90

            
91
    log_message "AutoNAS detach operation started for identifier: $identifier"
92

            
93
    # Get configuration by UUID, name, or mount point
Bogdan Timofte authored 3 months ago
94
    local config
Bogdan Timofte authored 3 months ago
95
    config=$(resolve_config_identifier "$identifier")
96

            
Bogdan Timofte authored 3 months ago
97
    if [[ -z "$config" ]]; then
Bogdan Timofte authored 3 months ago
98
        log_message "No configuration found for identifier: $identifier"
Bogdan Timofte authored 3 months ago
99
        return 1
100
    fi
Bogdan Timofte authored 3 months ago
101

            
Bogdan Timofte authored 3 months ago
102
    # Parse configuration
103
    local parsed
104
    parsed=($(parse_config "$config"))
105
    local cfg_uuid="${parsed[0]}"
106
    local name="${parsed[1]}"
107
    local ip="${parsed[2]}"
108
    local interface="${parsed[3]}"
109
    local mount_point="${parsed[4]}"
110
    local nfs_options="${parsed[5]}"
Bogdan Timofte authored 3 months ago
111

            
112
    log_message "Handling disk detachment for UUID: $cfg_uuid"
Bogdan Timofte authored 3 months ago
113
    log_message "Processing disk: $name (Mount: $mount_point)"
114

            
115
    # Remove NFS export (if applicable)
116
    if [[ "$ip" != "LOCAL" && "$ip" != "IMPORT" ]]; then
117
        remove_nfs_export "$mount_point"
118
    fi
119

            
120
    # Unmount disk
121
    if unmount_disk "$mount_point"; then
122
        # Deactivate IP (if applicable)
123
        if [[ "$ip" != "LOCAL" && "$ip" != "IMPORT" ]]; then
124
            deactivate_ip "$ip" "$interface"
125
        fi
126

            
127
        log_message "Disk detached successfully: $name"
128
        return 0
129
    else
130
        log_message "Error: Failed to detach disk: $name" "err"
131
        return 1
132
    fi
133
}
134

            
135
# Function to reload configuration
136
handle_reload() {
137
    log_message "Reloading AutoNAS configuration"
138

            
139
    log_message "Reloading udev rules"
140
    udevadm control --reload-rules
141
    udevadm trigger --subsystem-match=block
142

            
143
    log_message "Reloading NFS exports"
144
    exportfs -ra || log_message "Warning: Failed to reload NFS exports" "warning"
145

            
146
    log_message "Reloading systemd daemon"
147
    systemctl daemon-reload || log_message "Warning: Failed to reload systemd daemon" "warning"
148

            
149
    log_message "AutoNAS configuration reload completed"
150
    return 0
151
}
152

            
153
# Show usage information
154
show_usage() {
155
    cat << EOF
156
AutoNAS - Unified AutoNAS Management Tool
157

            
158
Usage: $0 <command> [options]
159

            
160
DISK OPERATIONS:
Bogdan Timofte authored 3 months ago
161
  attach <uuid|name|mount>   - Attach configured disk
162
  detach <uuid|name|mount>   - Detach configured disk
Bogdan Timofte authored 3 months ago
163
  import <uuid> <source> <dest> [script] - Run background import (internal use)
164
  reload                     - Reload AutoNAS configuration
165

            
166
CONFIGURATION MANAGEMENT:
167
  add [uuid]                 - Add new disk configuration
Bogdan Timofte authored 3 months ago
168
  remove [uuid|name|mount]   - Remove disk configuration
Bogdan Timofte authored 3 months ago
169
  list                       - List all configured disks
Bogdan Timofte authored 3 months ago
170
  test [uuid|name|mount]     - Test disk configuration
Bogdan Timofte authored 3 months ago
171
  show                       - Show available disks
172

            
173
MAINTENANCE:
174
  status                     - Show system status
175
  debug enable               - Enable debug mode (verbose logging)
176
  debug disable              - Disable debug mode
177
  debug status               - Show current debug status
178

            
179
Examples:
180
  $0 attach f6ac3d86-5681-4b33-bc64-aa272b333057
181
  $0 add 8765-4321
182
  $0 list
183
  $0 show
184
  $0 status
185

            
186
EOF
187
}
188

            
189
# Function to show available disks
190
show_available_disks() {
191
    echo "=== Available Storage Devices ==="
192
    echo
193

            
194
    local found_devices=0
195
    local blkid_output
196

            
197
    # Get blkid output and process it
198
    if ! blkid_output=$(blkid 2>/dev/null); then
199
        echo "Error: Unable to scan for block devices (are you running as root?)"
200
        return 1
201
    fi
202

            
203
    while IFS= read -r blkid_line; do
204
        [[ -z "$blkid_line" ]] && continue
205

            
206
        local device=$(echo "$blkid_line" | cut -d: -f1)
207

            
208
        # Skip if device doesn't exist (shouldn't happen with blkid, but just in case)
209
        [[ ! -b "$device" ]] && continue
210

            
211
        # Skip loop devices, ram disks, and other virtual devices
212
        case "$device" in
213
            /dev/loop*|/dev/ram*|/dev/dm-*) continue ;;
214
        esac
215

            
216
        # Extract device information
217
        local uuid=$(echo "$blkid_line" | grep -o 'UUID="[^"]*"' | cut -d'"' -f2)
218
        local label=$(echo "$blkid_line" | grep -o 'LABEL="[^"]*"' | cut -d'"' -f2)
219
        local fstype=$(echo "$blkid_line" | grep -o 'TYPE="[^"]*"' | cut -d'"' -f2)
220
        local partuuid=$(echo "$blkid_line" | grep -o 'PARTUUID="[^"]*"' | cut -d'"' -f2)
221

            
222
        # Skip if no UUID (we need UUID for AutoNAS)
223
        [[ -z "$uuid" ]] && continue
224

            
225
        found_devices=$((found_devices + 1))
226

            
227
        # Get device size
228
        local size=""
229
        if [[ -b "$device" ]]; then
230
            size=$(lsblk -b -d -o SIZE "$device" 2>/dev/null | tail -n1)
231
            if [[ -n "$size" ]] && [[ "$size" =~ ^[0-9]+$ ]]; then
232
                # Convert to human readable
233
                size=$(numfmt --to=iec --suffix=B "$size" 2>/dev/null || echo "${size}B")
234
            fi
235
        fi
236

            
237
        # Display device information
238
        echo "Device: $device"
239
        [[ -n "$size" ]] && echo "  Size: $size"
240
        echo "  UUID: $uuid"
241
        [[ -n "$label" ]] && echo "  Label: $label"
242
        [[ -n "$fstype" ]] && echo "  Filesystem: $fstype"
243

            
244
        # Check if already configured
245
        if grep -q "^${uuid}:" "$CONFIG_FILE" 2>/dev/null; then
246
            local config_line=$(grep "^${uuid}:" "$CONFIG_FILE" 2>/dev/null)
247
            local config_name=$(echo "$config_line" | cut -d: -f2)
248
            echo "  Status: ✅ Configured as '$config_name'"
249
        else
250
            echo "  Status: ⚠️  Not configured"
251
        fi
252

            
253
        # Check if currently mounted
254
        local mount_info
255
        mount_info=$(findmnt -n -o TARGET "$device" 2>/dev/null)
256
        if [[ -n "$mount_info" ]]; then
257
            echo "  Mount: 🟢 $mount_info"
258
        else
259
            echo "  Mount: ⚪ Not mounted"
260
        fi
261

            
262
        echo
263
    done <<< "$blkid_output"
264

            
265
    if [[ $found_devices -eq 0 ]]; then
266
        echo "No storage devices with UUIDs found."
267
        echo "Make sure devices are connected and you're running as root."
268
    else
269
        echo "Found $found_devices storage device(s)"
270
        echo
271
        echo "To configure a device: autonas add <UUID>"
272
        echo "To list configured devices: autonas list"
273
    fi
274

            
275
    return 0
276
}
277

            
278
# Show usage information
279

            
280
# Function to check if UUID exists in configuration
281
check_uuid_exists() {
282
    local uuid="$1"
283
    grep -q "^${uuid}:" "$CONFIG_FILE" 2>/dev/null
284
}
285

            
286
# Function to get device information
287
get_device_info() {
288
    local uuid="$1"
289

            
290
    # Find device by UUID using blkid
291
    local device_line
292
    device_line=$(blkid | grep "UUID=\"$uuid\"")
293

            
294
    if [[ -z "$device_line" ]]; then
295
        return 1
296
    fi
297

            
298
    local device=$(echo "$device_line" | cut -d: -f1)
299
    local blkid_info=$(echo "$device_line" | cut -d: -f2-)
300

            
301
    echo "device:$device"
302
    echo "$blkid_info"
303
    return 0
304
}
305

            
306
# Function to list configured disks
307
list_disks() {
308
    echo "AutoNAS Disk Configurations:"
309
    echo "============================"
310
    echo ""
311

            
312
    if [[ ! -f "$CONFIG_FILE" ]]; then
313
        echo "No configuration file found at: $CONFIG_FILE"
314
        echo "Use 'autonas add' to add your first disk configuration."
315
        return 1
316
    fi
317

            
318
    local config_count=0
319
    while IFS=':' read -r uuid name ip interface mount_point nfs_options; do
320
        # Skip empty lines and comments
321
        [[ -z "$uuid" || "$uuid" =~ ^# ]] && continue
322

            
323
        config_count=$((config_count + 1))
324

            
325
        echo "UUID: $uuid"
326
        echo "Name: $name"
327

            
328
        # Check if it's a local mount configuration
329
        if [[ "$ip" == "LOCAL" && "$interface" == "LOCAL" && "$nfs_options" == "LOCAL" ]]; then
330
            echo "Type: 📁 Local Mount (no network sharing)"
331
            echo "Mount Point: $mount_point"
332
        elif [[ "$ip" == "IMPORT" && "$interface" == "IMPORT" ]]; then
333
            echo "Type: 📷 Camera Import (mount, import, unmount)"
334
            echo "Import Destination: $nfs_options"
335
            echo "Import Script: /usr/local/bin/autonas-media-importer.sh (built-in, non-configurable)"
336
            echo "Temp Mount Point: $mount_point"
337
        else
338
            echo "Type: 🌐 NFS Network Share"
339
            echo "IP: $ip"
340
            echo "Interface: $interface"
341
            echo "Mount Point: $mount_point"
342
            echo "NFS Options: $nfs_options"
343
        fi
344

            
345
        # Check device status
346
        local device_info
347
        if device_info=$(get_device_info "$uuid" 2>/dev/null); then
348
            local device=$(echo "$device_info" | grep "^device:" | cut -d: -f2)
349
            echo "Status: ✅ Connected"
350

            
351
            # Check if mounted
352
            if mountpoint -q "$mount_point" 2>/dev/null; then
353
                echo "Mount Status: 🟢 Mounted"
354
                echo "Current Mount: $mount_point"
355
            else
356
                echo "Mount Status: 🔴 Not Mounted"
357
            fi
358
        else
359
            echo "Status: 🔴 Not Connected"
360
        fi
361

            
362
        echo "----"
363
    done < <(grep -v '^#' "$CONFIG_FILE" 2>/dev/null | grep -v '^$')
364

            
365
    if [[ $config_count -eq 0 ]]; then
366
        echo "No disk configurations found."
367
        echo "Use 'autonas add' to add your first disk configuration."
368
        return 1
369
    fi
370

            
371
    echo ""
372
    echo "Total configurations: $config_count"
373
    return 0
374
}
375

            
376
# Function to add disk configuration
377
add_disk() {
378
    local preset_uuid="$1"  # Optional UUID parameter
379

            
380
    echo "AutoNAS - Add New Disk Configuration"
381
    echo "===================================="
382
    echo ""
383

            
384
    # Show available disks first
385
    show_available_disks
386
    if [ $? -ne 0 ]; then
387
        echo "Cannot proceed without available disks."
388
        return 1
389
    fi
390

            
391
    echo "Please enter the configuration for your disk:"
392
    echo ""
393

            
394
    # Get UUID with validation
395
    local uuid="$preset_uuid"
396
    if [ -n "$uuid" ]; then
397
        echo "Using provided UUID: $uuid"
398

            
399
        if ! validate_uuid "$uuid"; then
400
            echo "Error: Invalid UUID format. Expected format: 12345678-1234-1234-1234-123456789abc"
401
            echo "Please run without UUID parameter to enter manually."
402
            return 1
403
        fi
404

            
405
        if check_uuid_exists "$uuid"; then
406
            echo "Error: UUID $uuid is already configured."
407
            echo "Use 'autonas remove $uuid' to remove existing configuration first."
408
            return 1
409
        fi
410
    else
411
        while true; do
412
            read -p "Enter disk UUID: " uuid
413
            if [ -z "$uuid" ]; then
414
                echo "Error: UUID cannot be empty"
415
                continue
416
            fi
417

            
418
            if ! validate_uuid "$uuid"; then
419
                echo "Error: Invalid UUID format. Expected format: 12345678-1234-1234-1234-123456789abc"
420
                continue
421
            fi
422

            
423
            if check_uuid_exists "$uuid"; then
424
                echo "Error: UUID $uuid is already configured."
425
                echo "Use 'autonas remove $uuid' to remove existing configuration first."
426
                continue
427
            fi
428

            
429
            break
430
        done
431
    fi
432

            
433
    # Get and validate disk name
434
    local name
435
    while true; do
436
        read -p "Enter disk name (letters, numbers, hyphens, underscores, @ allowed): " name
437
        if [ -z "$name" ]; then
438
            echo "Error: Disk name cannot be empty"
439
            continue
440
        fi
441

            
442
        if ! validate_disk_name_complete "$name"; then
443
            local validation_result=$?
444
            if [[ $validation_result -eq 2 ]]; then
445
                echo "Error: Disk name '$name' already exists. Please choose another name."
446
                echo ""
447
                list_existing_disk_names
448
                echo ""
449
                continue
450
            else
451
                echo "Error: Invalid disk name. Requirements:"
452
                echo "  - Max 50 characters"
453
                echo "  - Must start with letter or number"
454
                echo "  - Only letters, numbers, hyphens (-), underscores (_), and at symbol (@)"
455
                echo "  - Cannot be reserved names (root, home, tmp, etc.)"
456
                continue
457
            fi
458
        fi
459

            
460
        break
461
    done
462

            
463
    # Choose configuration type
464
    echo ""
465
    echo "Select disk type:"
466
    echo "1) NFS Network Share (default) - Share disk over network"
467
    echo "2) Camera Import - Import photos/videos from camera and unmount"
468
    echo "3) Local Mount - Mount locally without network sharing"
469
    echo ""
470

            
471
    local config_type
472
    read -p "Choose type [1-3] (default: 1): " config_type
473
    config_type=${config_type:-1}
474

            
475
    case "$config_type" in
476
        1)
477
            configure_nfs_disk "$uuid" "$name"
478
            ;;
479
        2)
480
            configure_import_disk "$uuid" "$name"
481
            ;;
482
        3)
483
            configure_local_disk "$uuid" "$name"
484
            ;;
485
        *)
486
            echo "Invalid choice. Using NFS Network Share (default)."
487
            configure_nfs_disk "$uuid" "$name"
488
            ;;
489
    esac
490
}
491

            
492
# Function to configure NFS disk
493
configure_nfs_disk() {
494
    local uuid="$1"
495
    local name="$2"
496

            
497
    echo ""
498
    echo "=== NFS Network Share Configuration ==="
499

            
500
    # Get IP address
501
    local ip
502
    while true; do
503
        read -p "Enter IP address for NFS sharing (e.g., 192.168.1.100): " ip
504
        if [ -z "$ip" ]; then
505
            echo "Error: IP address cannot be empty"
506
            continue
507
        fi
508

            
509
        # Basic IP validation
510
        if [[ ! "$ip" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
511
            echo "Error: Invalid IP address format"
512
            continue
513
        fi
514

            
515
        # Check each octet
516
        local valid_ip=true
517
        IFS='.' read -ra OCTETS <<< "$ip"
518
        for octet in "${OCTETS[@]}"; do
519
            if [ "$octet" -lt 0 ] || [ "$octet" -gt 255 ]; then
520
                valid_ip=false
521
                break
522
            fi
523
        done
524

            
525
        if [ "$valid_ip" = false ]; then
526
            echo "Error: IP address octets must be between 0-255"
527
            continue
528
        fi
529

            
530
        break
531
    done
532

            
533
    # Get network interface
534
    local interface
535
    echo ""
536
    echo "Available network interfaces:"
537
    ip link show | grep "^[0-9]" | cut -d: -f2 | sed 's/^ *//' | grep -v "^lo$"
538
    echo ""
539

            
540
    while true; do
541
        read -p "Enter network interface (e.g., eth0, enp0s3): " interface
542
        if [ -z "$interface" ]; then
543
            echo "Error: Network interface cannot be empty"
544
            continue
545
        fi
546

            
547
        # Check if interface exists
548
        if ! ip link show "$interface" >/dev/null 2>&1; then
549
            echo "Error: Network interface '$interface' does not exist"
550
            echo "Available interfaces:"
551
            ip link show | grep "^[0-9]" | cut -d: -f2 | sed 's/^ *//' | grep -v "^lo$"
552
            continue
553
        fi
554

            
555
        break
556
    done
557

            
558
    # Generate mount point
559
    local mount_point="$MOUNT_BASE/$name"
560
    echo ""
561
    echo "Mount point will be: $mount_point"
562

            
563
    # Get NFS options
564
    local nfs_options
565
    echo ""
566
    echo "NFS Options (press Enter for default):"
567
    echo "Default: *(rw,all_squash,insecure,async,no_subtree_check,anonuid=0,anongid=0)"
568
    read -p "Enter custom NFS options or press Enter for default: " nfs_options
569

            
570
    if [ -z "$nfs_options" ]; then
571
        nfs_options="*(rw,all_squash,insecure,async,no_subtree_check,anonuid=0,anongid=0)"
572
    fi
573

            
574
    # Create configuration entry
575
    local config_entry="${uuid}:${name}:${ip}:${interface}:${mount_point}:${nfs_options}"
576

            
577
    # Show configuration summary
578
    echo ""
579
    echo "=== Configuration Summary ==="
580
    echo "UUID: $uuid"
581
    echo "Name: $name"
582
    echo "Type: NFS Network Share"
583
    echo "IP: $ip"
584
    echo "Interface: $interface"
585
    echo "Mount Point: $mount_point"
586
    echo "NFS Options: $nfs_options"
587
    echo ""
588

            
589
    # Confirm configuration
590
    read -p "Save this configuration? (Y/n): " confirm
591
    if [[ "$confirm" =~ ^[Nn]$ ]]; then
592
        echo "Configuration cancelled."
593
        return 1
594
    fi
595

            
596
    # Save configuration
597
    echo "$config_entry" >> "$CONFIG_FILE"
598
    echo ""
599
    echo "✅ Configuration saved successfully!"
600
    echo ""
601
    echo "To test this configuration: autonas test $uuid"
602
    echo "To attach this disk when connected: autonas attach $uuid"
603

            
604
    return 0
605
}
606

            
607
# Function to configure local disk
608
configure_local_disk() {
609
    local uuid="$1"
610
    local name="$2"
611

            
612
    echo ""
613
    echo "=== Local Mount Configuration ==="
614
    echo "This disk will be mounted locally without network sharing."
615
    echo ""
616

            
617
    # Generate mount point
618
    local mount_point="$MOUNT_BASE/$name"
619
    echo "Mount point will be: $mount_point"
620
    echo ""
621

            
622
    # Create configuration entry
623
    local config_entry="${uuid}:${name}:LOCAL:LOCAL:${mount_point}:LOCAL"
624

            
625
    # Show configuration summary
626
    echo "=== Configuration Summary ==="
627
    echo "UUID: $uuid"
628
    echo "Name: $name"
629
    echo "Type: Local Mount (no network sharing)"
630
    echo "Mount Point: $mount_point"
631
    echo ""
632

            
633
    # Confirm configuration
634
    read -p "Save this configuration? (Y/n): " confirm
635
    if [[ "$confirm" =~ ^[Nn]$ ]]; then
636
        echo "Configuration cancelled."
637
        return 1
638
    fi
639

            
640
    # Save configuration
641
    echo "$config_entry" >> "$CONFIG_FILE"
642
    echo ""
643
    echo "✅ Configuration saved successfully!"
644
    echo ""
645
    echo "To test this configuration: autonas test $uuid"
646
    echo "To attach this disk when connected: autonas attach $uuid"
647

            
648
    return 0
649
}
650

            
651
# Function to configure import disk (camera)
652
configure_import_disk() {
653
    local uuid="$1"
654
    local name="$2"
655

            
656
    echo ""
657
    echo "=== Camera Import Configuration ==="
658
    echo "This device will be mounted temporarily, media imported, then unmounted."
659
    echo ""
660

            
661
    # Get destination path for import
662
    local destination_path
663
    while true; do
664
        read -p "Enter destination path for imported media: " destination_path
665
        if [ -z "$destination_path" ]; then
666
            echo "Error: Destination path cannot be empty"
667
            continue
668
        fi
669

            
670
        # Convert relative path to absolute
671
        if [[ ! "$destination_path" =~ ^/ ]]; then
672
            destination_path="$(pwd)/$destination_path"
673
        fi
674

            
675
        # Validate parent directory exists
676
        local parent_dir=$(dirname "$destination_path")
677
        if [ ! -d "$parent_dir" ]; then
678
            echo "Warning: Parent directory '$parent_dir' does not exist."
679
            read -p "Create parent directories? (Y/n): " create_dirs
680
            if [[ ! "$create_dirs" =~ ^[Nn]$ ]]; then
681
                if mkdir -p "$parent_dir" 2>/dev/null; then
682
                    echo "Created parent directories."
683
                else
684
                    echo "Error: Failed to create parent directories. Please check permissions."
685
                    continue
686
                fi
687
            else
688
                echo "Please enter a valid destination path."
689
                continue
690
            fi
691
        fi
692

            
693
        break
694
    done
695

            
696
    # Generate temporary mount point for import
697
    local temp_mount_point="$MOUNT_BASE/$name"
698

            
699
    # Create configuration entry (simplified format - no script path)
700
    local config_entry="${uuid}:${name}:IMPORT:IMPORT:${temp_mount_point}:${destination_path}"
701

            
702
    # Show configuration summary
703
    echo ""
704
    echo "=== Configuration Summary ==="
705
    echo "UUID: $uuid"
706
    echo "Name: $name"
707
    echo "Type: Camera Import (mount, import, unmount)"
708
    echo "Import destination: $destination_path"
709
    echo "Import script: /usr/local/bin/autonas-media-importer.sh (built-in, non-configurable)"
710
    echo "Temp mount point: $temp_mount_point"
711
    echo ""
712

            
713
    # Confirm configuration
714
    read -p "Save this configuration? (Y/n): " confirm
715
    if [[ "$confirm" =~ ^[Nn]$ ]]; then
716
        echo "Configuration cancelled."
717
        return 1
718
    fi
719

            
720
    # Save configuration
721
    echo "$config_entry" >> "$CONFIG_FILE"
722
    echo ""
723
    echo "✅ Configuration saved successfully!"
724
    echo ""
725
    echo "To test this configuration: autonas test $uuid"
726
    echo "When camera is connected, media will be imported automatically to: $destination_path"
727

            
728
    return 0
729
}
730

            
731
# Function to remove disk configuration
732
remove_disk() {
Bogdan Timofte authored 3 months ago
733
    local identifier="$1"
Bogdan Timofte authored 3 months ago
734

            
Bogdan Timofte authored 3 months ago
735
    if [[ -z "$identifier" ]]; then
736
        echo "Usage: autonas remove <uuid|name|mount_point>"
Bogdan Timofte authored 3 months ago
737
        return 1
738
    fi
739

            
740
    if [[ ! -f "$CONFIG_FILE" ]]; then
741
        echo "No configuration file found."
742
        return 1
743
    fi
744

            
Bogdan Timofte authored 3 months ago
745
    local config
746
    config=$(resolve_config_identifier "$identifier")
747
    if [[ -z "$config" ]]; then
748
        echo "Error: Entry '$identifier' not found in configuration."
Bogdan Timofte authored 3 months ago
749
        return 1
750
    fi
Bogdan Timofte authored 3 months ago
751

            
752
    local parsed=($(parse_config "$config"))
753
    local uuid="${parsed[0]}"
754

            
Bogdan Timofte authored 3 months ago
755
    # Show current configuration
Bogdan Timofte authored 3 months ago
756
    echo "Current configuration for identifier: $identifier"
Bogdan Timofte authored 3 months ago
757
    echo "=================================="
758
    echo "Name: ${parsed[1]}"
759
    echo "Type: ${parsed[2]}:${parsed[3]}"
760
    echo "Mount: ${parsed[4]}"
761
    echo ""
762

            
763
    # Confirm removal
764
    read -p "Remove this configuration? (y/N): " confirm
765
    if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
766
        echo "Removal cancelled."
767
        return 1
768
    fi
769

            
770
    # Remove configuration
771
    local temp_file=$(mktemp)
772
    grep -v "^${uuid}:" "$CONFIG_FILE" > "$temp_file"
773
    mv "$temp_file" "$CONFIG_FILE"
774

            
775
    echo "✅ Configuration removed successfully!"
776
    return 0
777
}
778

            
779
# Function to test disk configuration
780
test_config() {
Bogdan Timofte authored 3 months ago
781
    local identifier="$1"
782

            
783
    if [[ -z "$identifier" ]]; then
784
        echo "Usage: autonas test <uuid|name|mount_point>"
Bogdan Timofte authored 3 months ago
785
        return 1
786
    fi
787

            
788
    echo "AutoNAS Configuration Test"
789
    echo "========================="
790
    echo ""
791

            
792
    # Check if configuration exists
793
    local config
Bogdan Timofte authored 3 months ago
794
    config=$(resolve_config_identifier "$identifier")
795

            
Bogdan Timofte authored 3 months ago
796
    if [[ -z "$config" ]]; then
Bogdan Timofte authored 3 months ago
797
        echo "❌ Configuration not found for identifier: $identifier"
Bogdan Timofte authored 3 months ago
798
        echo ""
799
        echo "Available configurations:"
800
        list_disks
801
        return 1
802
    fi
803

            
804
    # Parse configuration
805
    local parsed=($(parse_config "$config"))
806
    local cfg_uuid="${parsed[0]}"
807
    local name="${parsed[1]}"
808
    local ip="${parsed[2]}"
809
    local interface="${parsed[3]}"
810
    local mount_point="${parsed[4]}"
811
    local nfs_options="${parsed[5]}"
Bogdan Timofte authored 3 months ago
812

            
813
    echo "✅ Configuration found"
814
    echo "   UUID: $cfg_uuid"
815
    echo "   Identifier used: $identifier"
Bogdan Timofte authored 3 months ago
816
    echo "   Name: $name"
817
    echo "   Type: $ip:$interface"
818
    echo "   Mount Point: $mount_point"
819
    echo ""
820

            
821
    # Test device detection
822
    echo "🔍 Testing device detection..."
823
    local device_info
Bogdan Timofte authored 3 months ago
824
    if device_info=$(get_device_info "$cfg_uuid" 2>/dev/null); then
Bogdan Timofte authored 3 months ago
825
        local device=$(echo "$device_info" | grep "^device:" | cut -d: -f2)
826
        echo "✅ Device found: $device"
827

            
828
        # Show device details
829
        echo "$device_info" | grep -v "^device:" | while IFS= read -r line; do
830
            echo "   $line"
831
        done
832
    else
833
        echo "❌ Device not found or not connected"
Bogdan Timofte authored 3 months ago
834
        echo "   Make sure the device with UUID $cfg_uuid is connected"
Bogdan Timofte authored 3 months ago
835
        return 1
836
    fi
837
    echo ""
838

            
839
    # Test network configuration (if applicable)
840
    if [[ "$ip" != "LOCAL" && "$ip" != "IMPORT" ]]; then
841
        echo "🌐 Testing network configuration..."
842

            
843
        # Test interface
844
        if interface_exists "$interface"; then
845
            echo "✅ Network interface exists: $interface"
846
        else
847
            echo "❌ Network interface not found: $interface"
848
            echo "   Available interfaces:"
849
            ip link show | grep "^[0-9]" | cut -d: -f2 | sed 's/^ *//' | grep -v "^lo$" | sed 's/^/     /'
850
            return 1
851
        fi
852

            
853
        # Test IP configuration
854
        if is_ip_configured "$ip" "$interface"; then
855
            echo "✅ IP already configured: $ip on $interface"
856
        else
857
            echo "ℹ️  IP not currently configured: $ip on $interface"
858
            echo "   (This is normal - IP will be activated during attach)"
859
        fi
860
        echo ""
861
    fi
862

            
863
    # Test mount point
864
    echo "📁 Testing mount point..."
865
    if [[ -d "$mount_point" ]]; then
866
        if mountpoint -q "$mount_point" 2>/dev/null; then
867
            echo "✅ Mount point exists and is mounted: $mount_point"
868
            local mounted_device=$(findmnt -n -o SOURCE "$mount_point")
869
            echo "   Mounted device: $mounted_device"
870
        else
871
            echo "ℹ️  Mount point directory exists but not mounted: $mount_point"
872
        fi
873
    else
874
        echo "ℹ️  Mount point directory will be created: $mount_point"
875
    fi
876
    echo ""
877

            
878
    # Test import configuration (if applicable)
879
    if [[ "$ip" == "IMPORT" && "$interface" == "IMPORT" ]]; then
880
        echo "📷 Testing camera import configuration..."
881
        local destination="$nfs_options"
882

            
883
        if [[ -d "$destination" ]]; then
884
            echo "✅ Import destination exists: $destination"
885
            if [[ -w "$destination" ]]; then
886
                echo "✅ Import destination is writable"
887
            else
888
                echo "⚠️  Import destination is not writable"
889
                echo "   You may need to check permissions"
890
            fi
891
        else
892
            echo "ℹ️  Import destination will be created: $destination"
893
            local parent_dir=$(dirname "$destination")
894
            if [[ -d "$parent_dir" && -w "$parent_dir" ]]; then
895
                echo "✅ Parent directory exists and is writable"
896
            else
897
                echo "❌ Cannot create import destination"
898
                echo "   Parent directory: $parent_dir"
899
                return 1
900
            fi
901
        fi
902

            
903
        # Test import script
904
        if [[ -x "/usr/local/bin/autonas-media-importer.sh" ]]; then
905
            echo "✅ Media import script is available and executable"
906
        else
907
            echo "❌ Media import script not found or not executable"
908
            echo "   Expected: /usr/local/bin/autonas-media-importer.sh"
909
            return 1
910
        fi
911
        echo ""
912
    fi
913

            
914
    echo "🎉 Configuration test completed successfully!"
915
    echo ""
Bogdan Timofte authored 3 months ago
916
    echo "You can now attach this disk with: autonas attach $cfg_uuid"
Bogdan Timofte authored 3 months ago
917
    return 0
918
}
919

            
920
# Main configuration functions would go here...
921

            
922
# Main command dispatcher
923
case "${1:-}" in
924
    "attach")
925
        if [[ -z "$2" ]]; then
Bogdan Timofte authored 3 months ago
926
            echo "Error: UUID, disk name, or mount point required for attach command"
Bogdan Timofte authored 3 months ago
927
            show_usage
928
            exit 1
929
        fi
930
        handle_attach "$2"
931
        ;;
932
    "detach")
933
        if [[ -z "$2" ]]; then
Bogdan Timofte authored 3 months ago
934
            echo "Error: UUID, disk name, or mount point required for detach command"
Bogdan Timofte authored 3 months ago
935
            show_usage
936
            exit 1
937
        fi
938
        handle_detach "$2"
939
        ;;
940
    "import")
941
        # Internal use only - background import process
942
        if [[ -z "$4" ]]; then
943
            echo "Error: Missing arguments for import command"
944
            exit 1
945
        fi
946
        run_background_import "$2" "$3" "$4" "$5"
947
        ;;
948
    "reload")
949
        handle_reload
950
        ;;
951
    "add")
952
        add_disk "$2"
953
        ;;
954
    "remove")
955
        if [[ -z "$2" ]]; then
Bogdan Timofte authored 3 months ago
956
            echo "Error: UUID, disk name, or mount point required for remove command"
Bogdan Timofte authored 3 months ago
957
            show_usage
958
            exit 1
959
        fi
960
        remove_disk "$2"
961
        ;;
962
    "list")
963
        list_disks
964
        ;;
965
    "test")
966
        if [[ -z "$2" ]]; then
Bogdan Timofte authored 3 months ago
967
            echo "Error: UUID, disk name, or mount point required for test command"
Bogdan Timofte authored 3 months ago
968
            show_usage
969
            exit 1
970
        fi
971
        test_config "$2"
972
        ;;
973
    "show")
974
        show_available_disks
975
        ;;
976
    "status")
977
        echo "=== AutoNAS System Status ==="
978
        echo "Configuration file: $CONFIG_FILE"
979
        if [[ -f "$CONFIG_FILE" ]]; then
980
            count=$(grep -c "^[^#].*:.*:.*:" "$CONFIG_FILE" 2>/dev/null || echo "0")
981
            echo "Configured disks: $count"
982
        else
983
            echo "Configured disks: 0 (no config file)"
984
        fi
985
        echo "NFS server: $(systemctl is-active nfs-kernel-server 2>/dev/null || echo "unknown")"
986
        echo "AutoNAS service: $(systemctl is-active autonas 2>/dev/null || echo "unknown")"
987
        echo "Boot scan service: $(systemctl is-active autonas-boot-scan 2>/dev/null || echo "unknown")"
988
        echo ""
989
        echo "Recent logs:"
990
        journalctl -t autonas -n 5 --no-pager 2>/dev/null || echo "No recent logs found"
991
        ;;
992
    "debug")
993
        case "${2:-}" in
994
            "enable")
995
                if [ -f "/etc/default/autonas" ]; then
996
                    sed -i 's/AUTONAS_DEBUG="false"/AUTONAS_DEBUG="true"/' /etc/default/autonas
997
                    echo "✓ Debug mode enabled - verbose logging is now active"
998
                    echo "  All AutoNAS operations will produce detailed debug output"
999
                else
1000
                    echo "Error: Configuration file /etc/default/autonas not found"
1001
                    exit 1
1002
                fi
1003
                ;;
1004
            "disable")
1005
                if [ -f "/etc/default/autonas" ]; then
1006
                    sed -i 's/AUTONAS_DEBUG="true"/AUTONAS_DEBUG="false"/' /etc/default/autonas
1007
                    echo "✓ Debug mode disabled - normal logging restored"
1008
                else
1009
                    echo "Error: Configuration file /etc/default/autonas not found"
1010
                    exit 1
1011
                fi
1012
                ;;
1013
            "status")
1014
                if [ -f "/etc/default/autonas" ]; then
1015
                    echo "=== AutoNAS Debug Configuration ==="
1016
                    source /etc/default/autonas
1017
                    echo "Debug mode: ${AUTONAS_DEBUG:-false}"
1018
                    echo "Log level: ${AUTONAS_LOG_LEVEL:-info}"
1019
                    if [ "$AUTONAS_DEBUG" = "true" ]; then
1020
                        echo "Status: 🟢 Debug logging is ENABLED"
1021
                        echo "  - Verbose messages will appear in logs and stderr"
1022
                        echo "  - All operations will be traced in detail"
1023
                    else
1024
                        echo "Status: 🔴 Debug logging is DISABLED"
1025
                        echo "  - Only normal info/warning/error messages will appear"
1026
                    fi
1027
                else
1028
                    echo "Error: Configuration file /etc/default/autonas not found"
1029
                    exit 1
1030
                fi
1031
                ;;
1032
            "")
1033
                echo "Error: Debug command requires an argument"
1034
                echo "Usage: $0 debug {enable|disable|status}"
1035
                exit 1
1036
                ;;
1037
            *)
1038
                echo "Error: Unknown debug command '$2'"
1039
                echo "Usage: $0 debug {enable|disable|status}"
1040
                exit 1
1041
                ;;
1042
        esac
1043
        ;;
1044
    "help"|"-h"|"--help"|"")
1045
        show_usage
1046
        ;;
1047
    *)
1048
        echo "Error: Unknown command '$1'"
1049
        echo
1050
        show_usage
1051
        exit 1
1052
        ;;
1053
esac