CREATE SCHEMA osh;

GRANT USAGE ON SCHEMA osh TO postgres;

CREATE TABLE IF NOT EXISTS osh.offerings(
    offering_id VARCHAR(100),
    description VARCHAR(200),
    PRIMARY KEY (offering_id)
);

CREATE TABLE IF NOT EXISTS osh.results(
    results_id SERIAL,
    datetime TIMESTAMP WITHOUT TIME ZONE DEFAULT (NOW() AT TIME ZONE 'utc') NOT NULL,
    state BOOLEAN,
    logs bytea,
    task_reference VARCHAR(50),
    PRIMARY KEY (results_id)
);

CREATE TABLE IF NOT EXISTS osh.scans(
    scan_id SERIAL,
    offering_id VARCHAR(100),
    event_id VARCHAR(100) NOT NULL,
    is_managed_service BOOLEAN NOT NULL,
    component_list VARCHAR(100),
    datetime TIMESTAMP WITHOUT TIME ZONE DEFAULT (NOW() AT TIME ZONE 'utc') NOT NULL,
    owner VARCHAR(50) NOT NULL,
    results SERIAL,
    status VARCHAR (50) CONSTRAINT valid_status CHECK(status in ('PENDING', 'DELETED', 'COMPLETED', 'IN PROGRESS')),
    last_updated TIMESTAMP WITHOUT TIME ZONE DEFAULT (NOW() AT TIME ZONE 'utc') NOT NULL,
    PRIMARY KEY(scan_id),
    FOREIGN KEY (offering_id) REFERENCES osh.offerings(offering_id),
    FOREIGN KEY (results) REFERENCES osh.results(results_id)
);

CREATE TABLE IF NOT EXISTS osh.archive(
    scan_id SERIAL,
    offering_id VARCHAR(100),
    event_id VARCHAR(100) NOT NULL,
    is_managed_service BOOLEAN NOT NULL,
    component_list VARCHAR(100),
    datetime TIMESTAMP WITHOUT TIME ZONE DEFAULT (NOW() AT TIME ZONE 'utc') NOT NULL,
    owner VARCHAR(50) NOT NULL,
    results SERIAL,
    status VARCHAR (50) CONSTRAINT valid_status CHECK(status in ('PENDING', 'DELETED', 'COMPLETED', 'IN PROGRESS')),
    last_updated TIMESTAMP WITHOUT TIME ZONE DEFAULT (NOW() AT TIME ZONE 'utc') NOT NULL,
    PRIMARY KEY(scan_id),
    FOREIGN KEY (offering_id) REFERENCES osh.offerings(offering_id),
    FOREIGN KEY (results) REFERENCES osh.results(results_id)
);

CREATE TABLE IF NOT EXISTS osh.gitscans (
    id SERIAL,
    build_system_type VARCHAR(80),
    repository VARCHAR(150),
    reference VARCHAR(100),
    commit_id VARCHAR(100),
    -- SHA256 has a length of 256 bits, so 256 bits would represent 64 hex characters
    hashsum VARCHAR(64),
    PRIMARY KEY(id)
);

CREATE TABLE IF NOT EXISTS osh.pncscans(
    id SERIAL,
    build_system_type VARCHAR(80),
    build_id VARCHAR(100),
    PRIMARY KEY(id)
);

CREATE TABLE IF NOT EXISTS osh.brewscans(
    id SERIAL,
    build_system_type VARCHAR(80),
    brew_id VARCHAR(100),
    brew_nvr VARCHAR(100),
    pnc_id VARCHAR(100),
    artifact_type VARCHAR(100),
    file_name VARCHAR(100),
    built_from_source BOOLEAN,
    PRIMARY KEY(id)
);
