CREATE TABLE IF NOT EXISTS agents (
    alias TEXT
    , agent_id TEXT NOT NULL UNIQUE
    , hostname TEXT NOT NULL
    , id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
    , is_root BOOLEAN NOT NULL DEFAULT 0
    , is_root_allowed BOOLEAN NOT NULL DEFAULT 0
    , last_active TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    -- target triplet
    , platform TEXT NOT NULL
    , regtime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    , status TEXT
    -- is needed to processing requests
    , token TEXT
    , username TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS ip_addrs (
    agent_id INTEGER NOT NULL
    , check_ts DATETIME NOT NULL
    , gateway TEXT
    , id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
    , iface TEXT NOT NULL
    , ip_addr TEXT NOT NULL
    , is_gray BOOLEAN NOT NULL DEFAULT 1
    , netmask TEXT NOT NULL
    , FOREIGN KEY(agent_id) REFERENCES agents(id)
);

CREATE TABLE IF NOT EXISTS jobs (
    alias TEXT
    , id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
    -- Shell, Binary (with program download), Python (with program and python download if not exist), Management
    , job_type TEXT CHECK(job_type IN ('S','B','P','M')) NOT NULL DEFAULT 'S'
    -- Executable type: ALL - no matter, W - windows, L = linux
    , exec_type TEXT CHECK(exec_type IN ('ALL', 'W', 'L')) NOT NULL DEFAULT 'L'
    , platform TEXT CHECK(platform IN ('x86', 'x64', 'aarch32', 'aarch64'))
    , data BLOB NOT NULL
);

CREATE TABLE IF NOT EXISTS results (
    agent_id INTEGER NOT NULL
    , created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    , id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
    , job_id INTEGER NOT NULL
    , result BLOB
    -- Queued, Pending, Running, Finished
    , status TEXT CHECK(status IN ('Q', 'P', 'R', 'F'))
    , ts TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    , FOREIGN KEY(agent_id) REFERENCES agents(id)
    , FOREIGN KEY(job_id) REFERENCES jobs(id)
);

CREATE TABLE IF NOT EXISTS certificates (
    agent_id INTEGER NOT NULL
    , id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
    , is_revoked BOOLEAN NOT NULL DEFAULT FALSE
    , FOREIGN KEY(agent_id) REFERENCES agents(id)
);