CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE TABLE IF NOT EXISTS agents (
    alias TEXT
    , hostname TEXT NOT NULL
    , id UUID NOT NULL DEFAULT uuid_generate_v4()
    , is_root BOOLEAN NOT NULL DEFAULT false
    , is_root_allowed BOOLEAN NOT NULL DEFAULT false
    , 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
    , PRIMARY KEY(id)
);

CREATE TABLE IF NOT EXISTS ip_addrs (
    agent_id UUID NOT NULL
    , check_ts TIMESTAMP NOT NULL
    , gateway TEXT
    , id SERIAL
    , iface TEXT NOT NULL
    , ip_addr TEXT NOT NULL
    , is_gray BOOLEAN NOT NULL DEFAULT true
    , netmask TEXT NOT NULL
    , PRIMARY KEY(id)
    , FOREIGN KEY(agent_id) REFERENCES agents(id)
);

CREATE TABLE IF NOT EXISTS jobs (
    alias TEXT
    , id SERIAL
    -- 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'))
    , path TEXT NOT NULL
    , PRIMARY KEY(id)
);

CREATE TABLE IF NOT EXISTS results (
    agent_id UUID NOT NULL
    , created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    , id SERIAL
    , job_id INTEGER NOT NULL
    , result TEXT
    -- 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)
    , PRIMARY KEY(id)
);

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