CREATE TABLE liteboxfs_roots (
  id INTEGER PRIMARY KEY,
  uuid TEXT NOT NULL UNIQUE DEFAULT (new_uuid_v4()),
  name TEXT UNIQUE,
  created BLOB NOT NULL DEFAULT (now_nanos_blob())
);

INSERT INTO
  liteboxfs_roots (name)
VALUES
  ('default');

CREATE TABLE liteboxfs_files (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  kind INTEGER NOT NULL,
  mode INTEGER NOT NULL,
  atime BLOB NOT NULL,
  mtime BLOB NOT NULL,
  ctime BLOB NOT NULL,
  btime BLOB,
  uid INTEGER NOT NULL,
  gid INTEGER NOT NULL,
  major INTEGER,
  minor INTEGER,
  target BLOB
);

CREATE TABLE liteboxfs_paths (
  id INTEGER PRIMARY KEY,
  file INTEGER NOT NULL REFERENCES liteboxfs_files (id) ON DELETE RESTRICT,
  root INTEGER NOT NULL REFERENCES liteboxfs_roots (id) ON DELETE CASCADE,
  name BLOB NOT NULL,
  parent INTEGER REFERENCES liteboxfs_paths (id) ON DELETE CASCADE,
  UNIQUE (parent, name)
);

CREATE INDEX idx_liteboxfs_paths_file ON liteboxfs_paths (file);

WITH time AS (
  SELECT
    now_nanos_blob() AS now
)
INSERT INTO
    liteboxfs_files (kind, mode, atime, mtime, ctime, btime, uid, gid)
VALUES
  (
    2,
    493, -- 0755
    (SELECT now from time),
    (SELECT now from time),
    (SELECT now from time),
    (SELECT now from time),
    0,
    0
  );

INSERT INTO
  liteboxfs_paths (file, root, name)
VALUES
  (
    last_insert_rowid(),
    (SELECT id FROM liteboxfs_roots WHERE name = 'default'),
    x'2f' -- '/'
  );

CREATE TABLE liteboxfs_file_blocks (
  file INTEGER NOT NULL REFERENCES liteboxfs_files (id) ON DELETE CASCADE,
  block INTEGER NOT NULL REFERENCES liteboxfs_blocks (id) ON DELETE RESTRICT,
  "index" INTEGER NOT NULL,
  PRIMARY KEY (file, "index")
);

CREATE INDEX idx_liteboxfs_file_blocks_block ON liteboxfs_file_blocks (block);

CREATE TABLE liteboxfs_xattrs (
  id INTEGER PRIMARY KEY,
  file INTEGER NOT NULL REFERENCES liteboxfs_files (id) ON DELETE CASCADE,
  name BLOB NOT NULL,
  value BLOB NOT NULL,

  UNIQUE (file, name)
);
