<?php
function init_db($server_name, $port, $user, $password) {
    $dbconn = pg_connect(sprintf("host=%s port=%s user=%s password=%s", $server_name, $port, $user, $password));
    $res = pg_query($dbconn, "select datname from pg_database");
    
    if (!in_array('scada', pg_fetch_all_columns($res, 0)))
        pg_query($dbconn, "CREATE DATABASE scada");
    pg_close($dbconn);

    $dbconn = pg_connect(sprintf("host=%s port=%s dbname=scada user=%s password=%s", $server_name, $port, $user, $password));
    // 全局未启用TSDB的时候在这里对scada数据库启用就好
    pg_query($dbconn, "CREATE EXTENSION IF NOT EXISTS timescaledb");
    pg_query(
        $dbconn,
        "DO $$ BEGIN
            CREATE TYPE category
            AS ENUM (
                'DEVICE_STATUS',
                'ITEM_ID',
                'DEVICE_DATA',
                'PROCESS_DATA',
                'RESULT_DATA',
                'STATISTICAL_DATA'
            );
        EXCEPTION
            WHEN duplicate_object
            THEN null;
        END $$"
    );
    pg_query($dbconn, "CREATE TABLE IF NOT EXISTS hf_mes_scada_data_capture_node_configure (
        id serial2 primary key,
        code text,
        name text NOT NULL,
        type text NOT NULL,
        category category,
        flow_code text,
        working_subclass text NOT NULL,
        workstation text,
        create_date timestamp NOT NULL DEFAULT NOW(),
        note text
    )");
    pg_query($dbconn, "CREATE TABLE IF NOT EXISTS hf_mes_scada_edgeserver_controller_server (
        id serial2 primary key,
        code text,
        name text NOT NULL,
        url text NOT NULL,
        port int2 NOT NULL,
        address text NOT NULL,
        create_date timestamp NOT NULL DEFAULT NOW(),
        note text,
        updated bool NOT NULL DEFAULT false
    )");
    pg_query($dbconn, "CREATE TABLE IF NOT EXISTS hf_mes_scada_edgeserver_controller_device (
        id serial2 primary key,
        code text,
        name text NOT NULL,
        server_id serial2
            REFERENCES hf_mes_scada_edgeserver_controller_server(id),
        conf json,
        create_date timestamp NOT NULL DEFAULT NOW(),
        note text
    )");
    pg_query($dbconn, "CREATE TABLE IF NOT EXISTS hf_mes_scada_edgeserver_controller_command (
        id serial8 primary key,
        server_id serial2
            REFERENCES hf_mes_scada_edgeserver_controller_server(id)
            ON DELETE CASCADE,
        device_name text,
        command text,
        create_date timestamp NOT NULL DEFAULT NOW(),
        success bool
    )");
    pg_close($dbconn);
}
