DROP TABLE IF EXISTS user;
DROP TABLE IF EXISTS pubkeys;
DROP TABLE IF EXISTS certificates;
DROP TABLE IF EXISTS settings;

CREATE TABLE settings (
    id INTEGER PRIMARY KEY,
    current_serialnumber INTEGER NOT NULL,
    default_principals TEXT,
    default_commands TEXT,
    default_capabilities TEXT,
    default_client_from TEXT,
    current_timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE user (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT UNIQUE NOT NULL,
    password TEXT NOT NULL,
    fullname TEXT NOT NULL,
    email TEXT NOT NULL,
    principals TEXT,
    commands TEXT DEFAULT username NOT NULL,
    capabilities TEXT,
    client_from TEXT,
    admin INTEGER DEFAULT 0 NOT NULL,
    systemadmin INTEGER DEFAULT 0 NOT NULL,
    created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE pubkeys (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    key_name TEXT NOT NULL,
    ssh_pubkey TEXT NOT NULL,
    fingerprint TEXT,
    revoked INTEGER DEFAULT 0 NOT NULL,
    deleted INTEGER DEFAULT 0 NOT NULL,
    userca INTEGER DEFAULT 0 NOT NULL,
    hostca INTEGER DEFAULT 0 NOT NULL,
    created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES user (id)
);

CREATE TABLE certificates (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    pubkey_id INTEGER NOT NULL,
    key_id TEXT NOT NULL,
    serial INTEGER NOT NULL,
    principals TEXT,
    commands TEXT,
    capabilities TEXT,
    client_from TEXT,
    revoked INTEGER DEFAULT 0 NOT NULL,
    deleted INTEGER DEFAULT 0 NOT NULL,
    valid_from TIMESTAMP,
    valid_unitl TIMESTAMP,
    expired INTEGER DEFAULT 0 NOT NULL,
    created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (pubkey_id) REFERENCES pubkeys (id)
);

