/*
 * MYSQL DATABASE SCHEMA FOR THE M/MONIT DATABASE.
 *
 * To create the database:
 * 1) Create the mmonit database: mysqladmin create mmonit -u root -p
 * 2) Create the mmonit user and grant access to the mmonit database, example:
 *    CREATE USER mmonit@localhost IDENTIFIED BY '<password>';
 *    GRANT ALL ON mmonit.* to mmonit@localhost;
 *    FLUSH PRIVILEGES;
 * 3) Create the schema: mysql -u mmonit mmonit -p < mmonit-schema.mysql
 */


/* ---------------------------------------------------- M/Monit system table */


CREATE TABLE mmonit (
  schemaversion INTEGER NOT NULL,
  welcome TINYINT,
  purgeevents INTEGER,
  purgeanalytics INTEGER,
  skew INTEGER,
  programtimeout INTEGER,
  auditdefaultpasswords INTEGER,
  auditmd5passwords INTEGER,
  checkmonitversion INTEGER,
  checkmmonitversion INTEGER
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


/* -------------------------------------------------------------- Name table */


CREATE TABLE name (
  id BIGINT PRIMARY KEY,
  name VARCHAR(255) UNIQUE NOT NULL,
  INDEX name_name_index (name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;


/* ------------------------------------------------------------- Host tables */


CREATE TABLE host (
  id BIGINT PRIMARY KEY,
  created_at BIGINT,
  updated_at BIGINT,
  incarnation INTEGER,
  status CHAR(1) NOT NULL,
  nameid BIGINT NOT NULL,
  keepname INTEGER DEFAULT 0,
  monitid VARCHAR(255) UNIQUE NOT NULL,
  ipaddrin VARCHAR(255) NOT NULL,
  ipaddrout VARCHAR(255),
  portin INTEGER,
  portout INTEGER DEFAULT -1,
  uname VARCHAR(255),
  password VARCHAR(255),
  sslin TINYINT,
  sslout TINYINT DEFAULT -1,
  description TEXT,
  poll INTEGER DEFAULT 0,
  startdelay INTEGER DEFAULT 0,
  controlfilenameid BIGINT NOT NULL,
  statusmodified BIGINT,
  servicemodified BIGINT DEFAULT 0,
  serviceskew INTEGER DEFAULT -1,
  serviceup INTEGER DEFAULT 0,
  servicedown INTEGER DEFAULT 0,
  serviceunmonitorauto INTEGER,
  serviceunmonitormanual INTEGER,
  version VARCHAR(20),
  platformname VARCHAR(255),
  platformrelease VARCHAR(255),
  platformversion VARCHAR(255),
  platformmachine VARCHAR(255),
  platformcpu INTEGER DEFAULT 0,
  platformmemory BIGINT DEFAULT 0,
  platformswap BIGINT DEFAULT 0,
  platformuptime BIGINT DEFAULT 0,
  statusheartbeat INTEGER DEFAULT 1,
  CONSTRAINT host_nameid_fk FOREIGN KEY (nameid) REFERENCES name (id) ON DELETE CASCADE,
  CONSTRAINT host_controlfilenameid_fk FOREIGN KEY (controlfilenameid) REFERENCES name (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE hostgroup (
  id BIGINT PRIMARY KEY,
  nameid BIGINT NOT NULL,
  CONSTRAINT hostgroup_nameid_fk FOREIGN KEY (nameid) REFERENCES name (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE groupedhost (
  groupid BIGINT NOT NULL,
  hostid  BIGINT NOT NULL,
  origin  INTEGER DEFAULT 0,
  PRIMARY KEY(groupid, hostid),
  CONSTRAINT groupedhost_groupid_fk FOREIGN KEY (groupid) REFERENCES hostgroup (id) ON DELETE CASCADE,
  CONSTRAINT groupedhost_hostid_fk FOREIGN KEY (hostid) REFERENCES host (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


/* ---------------------------------------------------------- Service tables */


CREATE TABLE service (
  id BIGINT PRIMARY KEY,
  created_at BIGINT,
  updated_at BIGINT,
  nameid BIGINT NOT NULL,
  hostid BIGINT NOT NULL,
  type INTEGER NOT NULL,
  status INTEGER NOT NULL,
  statushint INTEGER NOT NULL,
  monitoringstate INTEGER NOT NULL,
  monitoringmode INTEGER NOT NULL,
  onreboot INTEGER NOT NULL,
  statusmodified BIGINT DEFAULT 0,
  everytype INTEGER DEFAULT 0,
  everycyclenumber INTEGER DEFAULT 0,
  everycyclecounter INTEGER DEFAULT 0,
  everycron VARCHAR(255),
  INDEX service_hostid_index (hostid),
  CONSTRAINT service_hostid_fk FOREIGN KEY (hostid) REFERENCES host (id) ON DELETE CASCADE,
  CONSTRAINT service_nameid_fk FOREIGN KEY (nameid) REFERENCES name (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE servicegroup (
  id BIGINT PRIMARY KEY,
  nameid BIGINT NOT NULL,
  hostid BIGINT NOT NULL,
  INDEX servicegroup_hostid_index (hostid),
  CONSTRAINT servicegroup_hostid_fk FOREIGN KEY (hostid) REFERENCES host (id) ON DELETE CASCADE,
  CONSTRAINT servicegroup_nameid_fk FOREIGN KEY (nameid) REFERENCES name (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE groupedservices (
  servicegroupid BIGINT NOT NULL,
  service_nameid BIGINT NOT NULL,
  PRIMARY KEY(servicegroupid, service_nameid),
  CONSTRAINT groupedservices_servicegroupid_fk FOREIGN KEY (servicegroupid) REFERENCES servicegroup (id) ON DELETE CASCADE,
  CONSTRAINT groupedservices_service_nameid_fk FOREIGN KEY (service_nameid) REFERENCES name (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


/* --------------------------------------------------- Access control tables */


CREATE TABLE users (
  id BIGINT PRIMARY KEY,
  uname VARCHAR(20) UNIQUE NOT NULL,
  password VARCHAR(128) NOT NULL,
  fullname VARCHAR(255),
  title VARCHAR(255),
  email VARCHAR(255),
  phone VARCHAR(40),
  mobile VARCHAR(40),
  imname VARCHAR(255),
  imtype VARCHAR(20),
  image VARCHAR(255),
  refresh INTEGER DEFAULT 5000,
  INDEX users_uname_index (uname)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE roles (
  id BIGINT PRIMARY KEY,
  role VARCHAR(100) UNIQUE NOT NULL,
  description VARCHAR(255),
  admin BOOLEAN DEFAULT 0,
  active BOOLEAN DEFAULT 0,
  builtin BOOLEAN DEFAULT 0,
  INDEX roles_role_index (role)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE rolerow (
  id BIGINT PRIMARY KEY,
  roleid BIGINT NOT NULL,
  INDEX rolerow_roleid_index (roleid),
  CONSTRAINT rolerow_roleid_fk FOREIGN KEY(roleid) REFERENCES roles(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE rolerowhost (
  rolerowid BIGINT,
  hostid BIGINT,
  INDEX rolerowhost_rolerowid_index (rolerowid),
  INDEX rolerowhost_hostid_index (hostid),
  CONSTRAINT rolerowhost_rolerowid_fk FOREIGN KEY(rolerowid) REFERENCES rolerow(id) ON DELETE CASCADE,
  CONSTRAINT rolerowhost_hostid_fk FOREIGN KEY(hostid) REFERENCES host(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE rolerowhostgroup (
  rolerowid BIGINT,
  hostgroupid BIGINT,
  INDEX rolerowhostgroup_rolerowid_index (rolerowid),
  INDEX rolerowhostgroup_hostgroupid_index (hostgroupid),
  CONSTRAINT rolerowhostgroup_rolerowid_fk FOREIGN KEY(rolerowid) REFERENCES rolerow(id) ON DELETE CASCADE,
  CONSTRAINT rolerowhostgroup_hostgroupid_fk FOREIGN KEY(hostgroupid) REFERENCES hostgroup(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE rolerowpermission (
  rolerowid BIGINT,
  permission INTEGER,
  INDEX rolerowpermission_roleid_index (rolerowid),
  CONSTRAINT rolerowpermission_rolerowid_fk FOREIGN KEY(rolerowid) REFERENCES rolerow(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE userroles (
  userid BIGINT NOT NULL,
  roleid BIGINT NOT NULL,
  PRIMARY KEY(userid, roleid),
  INDEX userroles_roleid_index (roleid),
  CONSTRAINT userroles_roleid_fk FOREIGN KEY(roleid) REFERENCES roles(id) ON DELETE CASCADE,
  CONSTRAINT userroles_userid_fk FOREIGN KEY(userid) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


/* ------------------------------------------------------- Statistics tables */


CREATE TABLE statistics (
  id BIGINT PRIMARY KEY,
  serviceid BIGINT NOT NULL,
  type INTEGER NOT NULL,
  datatype INTEGER NOT NULL,
  descriptor VARCHAR(255),
  INDEX statistics_serviceid_index (serviceid),
  INDEX statistics_type_index (type),
  CONSTRAINT statistics_serviceid_fk FOREIGN KEY (serviceid) REFERENCES service(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE statistics_string (
  statisticsid BIGINT,
  collectedsec BIGINT NOT NULL,
  value TEXT,
  INDEX statistics_string_statisticsid_index (statisticsid),
  INDEX statistics_string_collectedsec_index (collectedsec),
  CONSTRAINT statistics_string_statisticsid_fk FOREIGN KEY (statisticsid) REFERENCES statistics(id) ON DELETE CASCADE
);


CREATE TABLE statistics_int (
  statisticsid BIGINT,
  collectedsec BIGINT NOT NULL,
  value INTEGER,
  INDEX statistics_int_statisticsid_index (statisticsid),
  INDEX statistics_int_collectedsec_index (collectedsec),
  CONSTRAINT statistics_int_statisticsid_fk FOREIGN KEY (statisticsid) REFERENCES statistics(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE statistics_llong (
  statisticsid BIGINT,
  collectedsec BIGINT NOT NULL,
  value BIGINT,
  INDEX statistics_llong_statisticsid_index (statisticsid),
  INDEX statistics_llong_collectedsec_index (collectedsec),
  CONSTRAINT statistics_llong_statisticsid_fk FOREIGN KEY (statisticsid) REFERENCES statistics(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE statistics_float (
  statisticsid BIGINT,
  collectedsec BIGINT NOT NULL,
  value FLOAT,
  INDEX statistics_float_statisticsid_index (statisticsid),
  INDEX statistics_float_collectedsec_index (collectedsec),
  CONSTRAINT statistics_float_statisticsid_fk FOREIGN KEY (statisticsid) REFERENCES statistics(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE statistics_double (
  statisticsid BIGINT,
  collectedsec BIGINT NOT NULL,
  value DOUBLE PRECISION,
  INDEX statistics_double_statisticsid_index (statisticsid),
  INDEX statistics_double_collectedsec_index (collectedsec),
  CONSTRAINT statistics_double_statisticsid_fk FOREIGN KEY (statisticsid) REFERENCES statistics(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE statistics_aggregate_1m (
  statisticsid BIGINT,
  collectedsec BIGINT NOT NULL,
  value_avg DOUBLE PRECISION,
  count BIGINT,
  INDEX statistics_aggregate_1m_statisticsid_index (statisticsid),
  INDEX statistics_aggregate_1m_collectedsec_index (collectedsec),
  CONSTRAINT statistics_aggregate_1m_statisticsid_fk FOREIGN KEY (statisticsid) REFERENCES statistics(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE statistics_aggregate_2m (
  statisticsid BIGINT,
  collectedsec BIGINT NOT NULL,
  value_avg DOUBLE PRECISION,
  count BIGINT,
  INDEX statistics_aggregate_2m_statisticsid_index (statisticsid),
  INDEX statistics_aggregate_2m_collectedsec_index (collectedsec),
  CONSTRAINT statistics_aggregate_2m_statisticsid_fk FOREIGN KEY (statisticsid) REFERENCES statistics(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE statistics_aggregate_15m (
  statisticsid BIGINT,
  collectedsec BIGINT NOT NULL,
  value_avg DOUBLE PRECISION,
  count BIGINT,
  INDEX statistics_aggregate_15m_statisticsid_index (statisticsid),
  INDEX statistics_aggregate_15m_collectedsec_index (collectedsec),
  CONSTRAINT statistics_aggregate_15m_statisticsid_fk FOREIGN KEY (statisticsid) REFERENCES statistics(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE statistics_aggregate_30m (
  statisticsid BIGINT,
  collectedsec BIGINT NOT NULL,
  value_avg DOUBLE PRECISION,
  count BIGINT,
  INDEX statistics_aggregate_30m_statisticsid_index (statisticsid),
  INDEX statistics_aggregate_30m_collectedsec_index (collectedsec),
  CONSTRAINT statistics_aggregate_30m_statisticsid_fk FOREIGN KEY (statisticsid) REFERENCES statistics(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE statistics_aggregate_1h (
  statisticsid BIGINT,
  collectedsec BIGINT NOT NULL,
  value_avg DOUBLE PRECISION,
  count BIGINT,
  INDEX statistics_aggregate_1h_statisticsid_index (statisticsid),
  INDEX statistics_aggregate_1h_collectedsec_index (collectedsec),
  CONSTRAINT statistics_aggregate_1h_statisticsid_fk FOREIGN KEY (statisticsid) REFERENCES statistics(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE statistics_aggregate_2h (
  statisticsid BIGINT,
  collectedsec BIGINT NOT NULL,
  value_avg DOUBLE PRECISION,
  count BIGINT,
  INDEX statistics_aggregate_2h_statisticsid_index (statisticsid),
  INDEX statistics_aggregate_2h_collectedsec_index (collectedsec),
  CONSTRAINT statistics_aggregate_2h_statisticsid_fk FOREIGN KEY (statisticsid) REFERENCES statistics(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE statistics_aggregate_4h (
  statisticsid BIGINT,
  collectedsec BIGINT NOT NULL,
  value_avg DOUBLE PRECISION,
  count BIGINT,
  INDEX statistics_aggregate_4h_statisticsid_index (statisticsid),
  INDEX statistics_aggregate_4h_collectedsec_index (collectedsec),
  CONSTRAINT statistics_aggregate_4h_statisticsid_fk FOREIGN KEY (statisticsid) REFERENCES statistics(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE statistics_aggregate_12h (
  statisticsid BIGINT,
  collectedsec BIGINT NOT NULL,
  value_avg DOUBLE PRECISION,
  count BIGINT,
  INDEX statistics_aggregate_12h_statisticsid_index (statisticsid),
  INDEX statistics_aggregate_12h_collectedsec_index (collectedsec),
  CONSTRAINT statistics_aggregate_12h_statisticsid_fk FOREIGN KEY (statisticsid) REFERENCES statistics(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE statistics_aggregate_1d (
  statisticsid BIGINT,
  collectedsec BIGINT NOT NULL,
  value_avg DOUBLE PRECISION,
  count BIGINT,
  INDEX statistics_aggregate_1d_statisticsid_index (statisticsid),
  INDEX statistics_aggregate_1d_collectedsec_index (collectedsec),
  CONSTRAINT statistics_aggregate_1d_statisticsid_fk FOREIGN KEY (statisticsid) REFERENCES statistics(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE statistics_aggregate_3d (
  statisticsid BIGINT,
  collectedsec BIGINT NOT NULL,
  value_avg DOUBLE PRECISION,
  count BIGINT,
  INDEX statistics_aggregate_3d_statisticsid_index (statisticsid),
  INDEX statistics_aggregate_3d_collectedsec_index (collectedsec),
  CONSTRAINT statistics_aggregate_3d_statisticsid_fk FOREIGN KEY (statisticsid) REFERENCES statistics(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE statistics_aggregate_7d (
  statisticsid BIGINT,
  collectedsec BIGINT NOT NULL,
  value_avg DOUBLE PRECISION,
  count BIGINT,
  INDEX statistics_aggregate_7d_statisticsid_index (statisticsid),
  INDEX statistics_aggregate_7d_collectedsec_index (collectedsec),
  CONSTRAINT statistics_aggregate_7d_statisticsid_fk FOREIGN KEY (statisticsid) REFERENCES statistics(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE statistics_aggregate_14d (
  statisticsid BIGINT,
  collectedsec BIGINT NOT NULL,
  value_avg DOUBLE PRECISION,
  count BIGINT,
  INDEX statistics_aggregate_14d_statisticsid_index (statisticsid),
  INDEX statistics_aggregate_14d_collectedsec_index (collectedsec),
  CONSTRAINT statistics_aggregate_14d_statisticsid_fk FOREIGN KEY (statisticsid) REFERENCES statistics(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE statistics_aggregate_4w (
  statisticsid BIGINT,
  collectedsec BIGINT NOT NULL,
  value_avg DOUBLE PRECISION,
  count BIGINT,
  INDEX statistics_aggregate_4w_statisticsid_index (statisticsid),
  INDEX statistics_aggregate_4w_collectedsec_index (collectedsec),
  CONSTRAINT statistics_aggregate_4w_statisticsid_fk FOREIGN KEY (statisticsid) REFERENCES statistics(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE statistics_events  (
  timeframe INTEGER NOT NULL,
  hostid BIGINT NOT NULL,
  state INTEGER NOT NULL,
  count BIGINT NOT NULL,
  INDEX statistics_events_state_index (state),
  INDEX statistics_events_hostid_index (hostid),
  CONSTRAINT statistics_events_hostid_fk FOREIGN KEY (hostid) REFERENCES host (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


/* ------------------------------------------------------------ Event tables */


CREATE TABLE event (
  id BIGINT PRIMARY KEY,
  hostid BIGINT NOT NULL,
  serviceid BIGINT NOT NULL,
  collectedsec BIGINT NOT NULL,
  collectedusec BIGINT NOT NULL,
  service_nameid BIGINT NOT NULL,
  servicetype INTEGER NOT NULL,
  event INTEGER NOT NULL,
  state INTEGER NOT NULL,
  action INTEGER NOT NULL,
  message TEXT NOT NULL,
  hasnotice INTEGER,
  active INTEGER,
  INDEX event_hostid_index (hostid),
  INDEX event_serviceid_index (serviceid),
  INDEX event_collectedsec_collectedusec_index (collectedsec, collectedusec),
  INDEX event_service_nameid_index (service_nameid),
  INDEX event_servicetype_index (servicetype),
  INDEX event_state_index (state),
  INDEX event_event_index (event),
  INDEX event_active_index (active),
  CONSTRAINT event_hostid_fk FOREIGN KEY (hostid) REFERENCES host (id) ON DELETE CASCADE,
  CONSTRAINT event_serviceid_fk FOREIGN KEY (serviceid) REFERENCES service (id) ON DELETE CASCADE,
  CONSTRAINT event_service_nameid_fk FOREIGN KEY (service_nameid) REFERENCES name (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE eventnotice (
  eventid BIGINT NOT NULL,
  date INTEGER NOT NULL,
  uname VARCHAR(20) NOT NULL, /* Note: store uname string instead of id to keep history of notes even if user is deleted */
  notice TEXT NOT NULL,
  INDEX eventnotice_eventid_index (eventid),
  CONSTRAINT eventnotice_eventid_fk FOREIGN KEY (eventid) REFERENCES event (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE eventfilter (
  eventid BIGINT NOT NULL,
  userid BIGINT NOT NULL,
  INDEX eventfilter_eventid_index (eventid),
  INDEX eventfilter_userid_index (userid),
  CONSTRAINT eventfilter_eventid_fk FOREIGN KEY (eventid) REFERENCES event (id) ON DELETE CASCADE,
  CONSTRAINT eventfilter_userid_fk FOREIGN KEY (userid) REFERENCES users (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


/* ------------------------------------------------------------- Rule tables */


CREATE TABLE rule (
  id BIGINT PRIMARY KEY,
  created_at BIGINT,
  updated_at BIGINT,
  description VARCHAR(255),
  active CHAR(1),
  operator CHAR(1) DEFAULT 0,
  INDEX rule_active_index (active)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE rulerow (
  id BIGINT PRIMARY KEY,
  ruleid BIGINT NOT NULL,
  CONSTRAINT rulerow_ruleid_fk FOREIGN KEY (ruleid) REFERENCES rule (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE rulerowhost (
  rulerowid BIGINT,
  hostid BIGINT,
  CONSTRAINT rulerowhost_rulerowid_fk FOREIGN KEY (rulerowid) REFERENCES rulerow (id) ON DELETE CASCADE,
  CONSTRAINT rulerowhost_hostid_fk FOREIGN KEY (hostid) REFERENCES host (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE rulerowhostgroup (
  rulerowid BIGINT,
  hostgroupid BIGINT,
  CONSTRAINT rulerowhostgroup_rulerowid_fk FOREIGN KEY (rulerowid) REFERENCES rulerow (id) ON DELETE CASCADE,
  CONSTRAINT rulerowhostgroup_hostgroupid_fk FOREIGN KEY (hostgroupid) REFERENCES hostgroup (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE rulerowservice (
  rulerowid BIGINT,
  service_nameid BIGINT,
  CONSTRAINT rulerowservice_rulerowid_fk FOREIGN KEY (rulerowid) REFERENCES rulerow (id) ON DELETE CASCADE,
  CONSTRAINT rulerowservice_service_nameid_fk FOREIGN KEY (service_nameid) REFERENCES name (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE rulerowservicegroup (
  rulerowid BIGINT,
  servicegroup_nameid BIGINT,
  CONSTRAINT rulerowservicegroup_rulerowid_fk FOREIGN KEY (rulerowid) REFERENCES rulerow (id) ON DELETE CASCADE,
  CONSTRAINT rulerowservicegroup_servicegroup_nameid_fk FOREIGN KEY (servicegroup_nameid) REFERENCES name (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE rulerowstate (
  rulerowid BIGINT,
  eventstate INTEGER,
  CONSTRAINT rulerowstate_rulerowid_fk FOREIGN KEY (rulerowid) REFERENCES rulerow (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE rulerowevent (
  rulerowid BIGINT,
  eventid INTEGER,
  CONSTRAINT rulerowevent_rulerowid_fk FOREIGN KEY (rulerowid) REFERENCES rulerow (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE actionrow (
  id BIGINT PRIMARY KEY,
  ruleid BIGINT NOT NULL,
  action INTEGER NOT NULL,
  repetition INTEGER DEFAULT 0,
  timeout INTEGER DEFAULT -1,
  CONSTRAINT actionrow_ruleid_fk FOREIGN KEY (ruleid) REFERENCES rule (id) ON DELETE CASCADE,
  INDEX actionrow_action_index (action)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE actionrowtarget (
  actionrowid BIGINT NOT NULL,
  target TEXT NOT NULL,
  CONSTRAINT actionrowtarget_actionrowid_fk FOREIGN KEY (actionrowid) REFERENCES actionrow(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE actionrowoption (
  actionrowid BIGINT NOT NULL,
  name VARCHAR(255) NOT NULL,
  value TEXT,
  CONSTRAINT actionrowoption_actionrowid_fk FOREIGN KEY (actionrowid) REFERENCES actionrow(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE actionqueue (
  actionrowid BIGINT NOT NULL,
  eventid BIGINT NOT NULL,
  created_at BIGINT,
  process_at BIGINT,
  CONSTRAINT actionqueue_actionrowid_fk FOREIGN KEY (actionrowid) REFERENCES actionrow(id) ON DELETE CASCADE,
  CONSTRAINT actionqueue_eventid_fk FOREIGN KEY (eventid) REFERENCES event(id) ON DELETE CASCADE,
  INDEX actionqueue_actionrowid_index (actionrowid),
  INDEX actionqueue_eventid_index (eventid),
  INDEX actionqueue_process_at_index (process_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


/* ----------------------------------------------------- Notification tables */


CREATE TABLE mailserver (
  id BIGINT PRIMARY KEY,
  hostname VARCHAR(255) NOT NULL,
  port INTEGER NOT NULL,
  uname VARCHAR(255),
  password VARCHAR(255),
  usessl CHAR(1),
  isdefault CHAR(1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE jabberserver (
  id BIGINT PRIMARY KEY,
  hostname VARCHAR(255) NOT NULL,
  port INTEGER NOT NULL,
  uname VARCHAR(255),
  password VARCHAR(255),
  isdefault CHAR(1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE messageformat (
  id BIGINT PRIMARY KEY,
  description VARCHAR(255),
  sendername VARCHAR(255),
  senderaddress VARCHAR(255),
  subjectsingle VARCHAR(255),
  subjectmulti VARCHAR(255),
  txtheader TEXT,
  txtbody TEXT,
  txtfooter TEXT,
  htmlheader TEXT,
  htmlbody TEXT,
  htmlfooter TEXT,
  contenttype INTEGER DEFAULT 0,
  isdefault CHAR(1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE messagequeue (
  deferredsize INTEGER,
  retry INTEGER,
  minbackoff INTEGER,
  maxbackoff INTEGER,
  flush INTEGER,
  maxmsgsize INTEGER,
  maxmsgevents INTEGER
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE alertservice (
  id BIGINT PRIMARY KEY,
  name VARCHAR(64) NOT NULL UNIQUE,
  description VARCHAR(255),
  endpoint VARCHAR(255),
  apikey TEXT,
  script TEXT NOT NULL,
  expanded TEXT NOT NULL,
  created_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


/* ----------------------------------- Persistent Alert message queue tables */


CREATE TABLE message (
  id BIGINT PRIMARY KEY,
  type INTEGER,
  contenttype VARCHAR(255),
  sendername VARCHAR(255),
  senderaddress VARCHAR(255),
  subject VARCHAR(255),
  body TEXT,
  created BIGINT,
  retry INTEGER
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE messagerecipients (
  messageid BIGINT NOT NULL,
  recipient VARCHAR(255) NOT NULL,
  CONSTRAINT messagerecipients_message_fk FOREIGN KEY (messageid) REFERENCES message (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


/* ----------------------------------------------- Persistent SESSION tables */


CREATE TABLE session (
  id VARCHAR(65) PRIMARY KEY,
  context VARCHAR(255) NOT NULL,
  ctime INTEGER NOT NULL,
  atime INTEGER NOT NULL,
  itime INTEGER NOT NULL,
  authtype VARCHAR(20),
  principal VARCHAR(255),
  data BLOB
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


/* ------------------------------------------------------------ Initial Data */


/*
 * Defaults
 */
INSERT INTO mmonit (schemaversion, welcome, purgeevents, purgeanalytics, skew, programtimeout, auditdefaultpasswords, auditmd5passwords, checkmonitversion, checkmmonitversion) VALUES (24, 1, 11, 10, 3, 300, 1, 1, 0, 0);

/*
 * Access control
 */
INSERT INTO users (id, uname, password, fullname, title) VALUES (1, 'admin', '#25c25e73e69a57ccf78abd32f29ac9d8#da091173a92116fc7b86990368647f99228cd0b5d993e93248b501e059674b7e', 'Administrator', 'M/Monit Administrator');
INSERT INTO users (id, uname, password, fullname, title) VALUES (3, 'monit', '#f04af79fc22894afe51eb26d5a13006b#9b594557f02a0084bcd10cbb160406618312ce6612aeb8da86e57b2929fa1465', 'Monit', 'Collector');

/* Admin role: built-in role with full permissions and user management. It is protected and cannot be deleted */
INSERT INTO roles (id, role, description, admin, active, builtin) VALUES (4, 'admin', 'The Administrator role', 1, 1, 1);
INSERT INTO userroles (userid, roleid) VALUES (1, 4);
INSERT INTO rolerow (id, roleid) VALUES (8, 4);
INSERT INTO rolerowpermission (rolerowid, permission) VALUES (8, 1); /* Collector */
INSERT INTO rolerowpermission (rolerowid, permission) VALUES (8, 2); /* View */
INSERT INTO rolerowpermission (rolerowid, permission) VALUES (8, 4); /* Service Actions */

/* Normal user role: view and service control for all hosts */
INSERT INTO roles (id, role, description, admin, active, builtin) VALUES (5, 'GUI', 'The user role for GUI access', 0, 1, 0);
INSERT INTO userroles (userid, roleid) VALUES (3, 5);
INSERT INTO rolerow (id, roleid) VALUES (9, 5);
INSERT INTO rolerowpermission (rolerowid, permission) VALUES (9, 2); /* View */
INSERT INTO rolerowpermission (rolerowid, permission) VALUES (9, 4); /* Service Actions */

/* Collector role: Update all hosts via collector only (no view nor services control) */
INSERT INTO roles (id, role, description, admin, active, builtin) VALUES (6, 'collector', 'Role for posting status and events to M/Monit', 0, 1, 1);
INSERT INTO userroles (userid, roleid) VALUES (3, 6);
INSERT INTO rolerow (id, roleid) VALUES (10, 6);
INSERT INTO rolerowpermission (rolerowid, permission) VALUES (10, 1); /* Update host status via collector */

/*
 * Messaging
 */
INSERT INTO messageformat (id, description, sendername, senderaddress, subjectsingle, subjectmulti, txtbody, txtfooter, htmlheader, htmlbody, htmlfooter, contenttype, isdefault) VALUES (
1,
'Default',
'M/Monit',
'mmonit@$HOST',
'M/Monit report ($HOST: $EVENT $SERVICE on $DATE)',
'M/Monit report ($COUNT events)',
'Date:        $DATE
Host:        $HOST
Service:     $SERVICE
Action:      $ACTION
Description: $DESCRIPTION

',
'
Your faithful employee,
M/Monit',
'<html>
    <table style="border-collapse:collapse;border:1px solid #eee; padding:5px;">
        <tr>
            <th style="border: 1px solid #eee; padding:5px;"><b>Date</b></th>
            <th style="border: 1px solid #eee; padding:5px;"><b>Host</b></th>
            <th style="border: 1px solid #eee; padding:5px;"><b>Service</b></th>
            <th style="border: 1px solid #eee; padding:5px;"><b>Action</b></th>
            <th style="border: 1px solid #eee; padding:5px;"><b>Description</b></th>
        </tr>
',
'        <tr>
            <td style="border: 1px solid #eee; padding:5px;">$DATE</td>
            <td style="border: 1px solid #eee; padding:5px;">$HOST</td>
            <td style="border: 1px solid #eee; padding:5px;">$SERVICE</td>
            <td style="border: 1px solid #eee; padding:5px;">$ACTION</td>
            <td style="border: 1px solid #eee; padding:5px;">$DESCRIPTION</td>
        </tr>
',
'    </table>
    <p>
        Your faithful employee,<br>
        M/Monit
    </p>
</html>',
0,
1);
INSERT INTO messageformat (id, description, sendername, senderaddress, subjectsingle, txtbody, contenttype, isdefault) VALUES (
2,
'Test',
'M/Monit',
'mmonit@$HOST',
'A test message from M/Monit',
'If you can read this, then I can send you alerts.

Your faithful employee,
M/Monit',
1,
0);
INSERT INTO messageformat (id, description, sendername, senderaddress, subjectsingle, subjectmulti, txtbody, contenttype, isdefault) VALUES (
3,
'Message limit reached',
'M/Monit',
'mmonit@$HOST',
'M/Monit report ($HOST: $EVENT $SERVICE on $DATE)',
'M/Monit report ($COUNT events)',
'Message size limit reached, please see the M/Monit events log.

Your faithful employee,
M/Monit',
1,
0);
INSERT INTO messagequeue (deferredsize, retry, minbackoff, maxbackoff, flush, maxmsgsize, maxmsgevents) VALUES (100, 10, 60, 3600, 30, 1048576, 100);

/* Slack Alert Service --------------------------------------------------- */
INSERT INTO alertservice(id, name, description, script, expanded, created_at)
VALUES(1, 'Slack Alert', 'A Service for sending Slack Alerts', CONCAT(
'# Generate the Slack message payload
generate_payload() {
  printf ''',
  '{
  "channel": "%s",
  "text": "Alert from M/Monit",
  "blocks": [
    {
      "type": "section",
      "text": {
        "type": "mrkdwn",
        "text": "*Alert from M/Monit*"
      }
    },
    {
      "type": "section",
      "fields": [
        {
          "type": "mrkdwn",
          "text": "*Date:*\\\\n%s"
        },
        {
          "type": "mrkdwn",
          "text": "*Host:*\\\\n%s"
        },
        {
          "type": "mrkdwn",
          "text": "*Service:*\\\\n%s"
        },
        {
          "type": "mrkdwn",
          "text": "*Action:*\\\\n%s"
        }
      ]
    },
    {
      "type": "section",
      "fields": [
        {
          "type": "mrkdwn",
          "text": "*Event:*\\\\n%s"
        },
        {
          "type": "mrkdwn",
          "text": "*Description:*\\\\n%s"
        }
      ]
    }
  ]
}'' "$ENDPOINT" "$MONIT_DATE" "$MONIT_HOST" "$MONIT_SERVICE" "$MONIT_ACTION" "$MONIT_EVENT" "$MONIT_DESCRIPTION"
}
# Generate and send the payload
payload=$(generate_payload)
curl -s -X POST \\
  -H "Authorization: Bearer $APIKEY" \\
  -H "Content-type: application/json" \\
  --data "$payload" \\
  https://slack.com/api/chat.postMessage'
), 'noop', 1723456800);

/* Discord Alert Service --------------------------------------------------- */
INSERT INTO alertservice(id, name, description, script, expanded, created_at)
VALUES(2, 'Discord Alert', 'A Service for sending Discord Alerts', CONCAT(
'# Generate the Discord message payload
generate_payload() {
  printf ''',
  '{
  "content": "Alert from M/Monit",
  "embeds": [{
    "title": "M/Monit Alert",
    "color": 15158332,
    "fields": [
      { "name": "Date", "value": "%s", "inline": true },
      { "name": "Host", "value": "%s", "inline": true },
      { "name": "Service", "value": "%s", "inline": true },
      { "name": "Action", "value": "%s", "inline": true },
      { "name": "Event", "value": "%s", "inline": false },
      { "name": "Description", "value": "%s", "inline": false }
    ]
  }]
}'' "$MONIT_DATE" "$MONIT_HOST" "$MONIT_SERVICE" "$MONIT_ACTION" "$MONIT_EVENT" "$MONIT_DESCRIPTION"
}

# Generate and send the payload
payload=$(generate_payload)
curl -H "Content-Type: application/json" -d "$payload" "$ENDPOINT"'
), 'noop', 1723456800);

/* PagerDuty Alert Service --------------------------------------------------- */
INSERT INTO alertservice(id, name, description, script, expanded, created_at)
VALUES(3, 'PagerDuty Alert', 'A Service for sending PagerDuty Alerts', CONCAT(
'# The Integration Key should be set in the API Key field in the service configuration
INTEGRATION_KEY="$APIKEY"

# Generate the PagerDuty event payload
generate_payload() {
  printf ''',
  '{
  "routing_key": "%s",
  "event_action": "trigger",
  "payload": {
    "summary": "M/Monit Alert: %s on %s",
    "source": "M/Monit",
    "severity": "critical",
    "custom_details": {
      "date": "%s",
      "host": "%s",
      "service": "%s",
      "action": "%s",
      "event": "%s",
      "description": "%s"
    }
  }
}'' "$INTEGRATION_KEY" "$MONIT_EVENT" "$MONIT_HOST" "$MONIT_DATE" "$MONIT_HOST" "$MONIT_SERVICE" "$MONIT_ACTION" "$MONIT_EVENT" "$MONIT_DESCRIPTION"
}

# Generate and send the payload
payload=$(generate_payload)
curl -s -X POST -H "Content-Type: application/json" -d "$payload" \\
  https://events.pagerduty.com/v2/enqueue'
), 'noop', 1723456800);
