-- AtlasOS - Calypso
-- Add ZFS Shares and iSCSI Export Tables
-- Version: 6.0
-- Description: Separate tables for filesystem shares (NFS/SMB) and volume iSCSI exports

-- ZFS Filesystem Shares Table (for NFS/SMB)
CREATE TABLE IF NOT EXISTS zfs_shares (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    dataset_id UUID NOT NULL REFERENCES zfs_datasets(id) ON DELETE CASCADE,
    share_type VARCHAR(50) NOT NULL, -- 'nfs', 'smb', 'both'
    nfs_enabled BOOLEAN NOT NULL DEFAULT false,
    nfs_options TEXT, -- e.g., "rw,sync,no_subtree_check"
    nfs_clients TEXT[], -- Allowed client IPs/networks
    smb_enabled BOOLEAN NOT NULL DEFAULT false,
    smb_share_name VARCHAR(255), -- SMB share name
    smb_path TEXT, -- SMB share path (usually same as mount_point)
    smb_comment TEXT,
    smb_guest_ok BOOLEAN NOT NULL DEFAULT false,
    smb_read_only BOOLEAN NOT NULL DEFAULT false,
    smb_browseable BOOLEAN NOT NULL DEFAULT true,
    is_active BOOLEAN NOT NULL DEFAULT true,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
    created_by UUID REFERENCES users(id),
    UNIQUE(dataset_id) -- One share config per dataset
);

-- ZFS Volume iSCSI Exports Table
CREATE TABLE IF NOT EXISTS zfs_iscsi_exports (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    dataset_id UUID NOT NULL REFERENCES zfs_datasets(id) ON DELETE CASCADE,
    target_id UUID REFERENCES scst_targets(id) ON DELETE SET NULL, -- Link to SCST target
    lun_number INTEGER, -- LUN number in the target
    device_path TEXT, -- /dev/zvol/pool/volume path
    is_active BOOLEAN NOT NULL DEFAULT true,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
    created_by UUID REFERENCES users(id),
    UNIQUE(dataset_id) -- One iSCSI export per volume
);

-- Create indexes
CREATE INDEX IF NOT EXISTS idx_zfs_shares_dataset_id ON zfs_shares(dataset_id);
CREATE INDEX IF NOT EXISTS idx_zfs_shares_type ON zfs_shares(share_type);
CREATE INDEX IF NOT EXISTS idx_zfs_shares_active ON zfs_shares(is_active);

CREATE INDEX IF NOT EXISTS idx_zfs_iscsi_exports_dataset_id ON zfs_iscsi_exports(dataset_id);
CREATE INDEX IF NOT EXISTS idx_zfs_iscsi_exports_target_id ON zfs_iscsi_exports(target_id);
CREATE INDEX IF NOT EXISTS idx_zfs_iscsi_exports_active ON zfs_iscsi_exports(is_active);

