#!/bin/bash
set -e

echo "=== MarkBase iSCSI Configuration Script ==="

USER_ID="${1:-demo}"
DISKS="${2:-/dev/sdb /dev/sdc /dev/sdd}"
STRIPE_SIZE="${3:-64}"

echo "Configuration Parameters:"
echo "  User ID: $USER_ID"
echo "  Disks: $DISKS"
echo "  Stripe Size (KB): $STRIPE_SIZE"

echo ""
echo "Step 1: Verifying disk availability..."
for disk in $DISKS; do
    if [ ! -b "$disk" ]; then
        echo "ERROR: Disk $disk not found"
        exit 1
    fi
    echo "  ✓ $disk exists"
done

echo ""
echo "Step 2: Creating RAID5 array..."
cargo run --bin configure_iscsi "$USER_ID" --disks $DISKS

echo ""
echo "Step 3: Verifying RAID5 status..."
sudo dmsetup status markbase_$USER_ID

echo ""
echo "Step 4: Creating database..."
DB_PATH="data/users/$USER_ID.sqlite"
if [ ! -f "$DB_PATH" ]; then
    echo "  Creating new database: $DB_PATH"
    cargo run -- scan --user "$USER_ID" --dir "/tmp/test_data"
fi

echo ""
echo "Step 5: Mapping LUNs to SQLite nodes..."
echo "  This requires manual setup via targetcli or custom script"

echo ""
echo "Step 6: Testing iSCSI connection..."
echo "  Use initiator client to connect:"
echo "  Target IQN: iqn.2026-05.momentry:markbase_$USER_ID"
echo "  Portal: 0.0.0.0:3260"

echo ""
echo "=== Configuration Complete ==="
echo "RAID Device: /dev/mapper/markbase_$USER_ID"
echo "iSCSI Target: iqn.2026-05.momentry:markbase_$USER_ID"
echo "Database: $DB_PATH"