
-- 3.7.0 introduce user selected dashboard
ALTER TABLE IF EXISTS users
  ADD COLUMN dashboard integer DEFAULT NULL;

-- 3.7.0 introduced dashboardid column to dashboard_widgets for dashboard sharing
ALTER TABLE IF EXISTS dashboard_widgets
  ADD COLUMN dashboardid integer,
  ADD CONSTRAINT dashboard_widgets_dashboardid_fkey FOREIGN KEY (dashboardid)
      REFERENCES dashboard_dashboards (id)  ON DELETE CASCADE;

-- 3.7.0 introduces (username, name, widgetid) unique contraint for dashboard_alerts due to new sharing functionality
ALTER TABLE IF EXISTS dashboard_alerts
  DROP CONSTRAINT dashboard_alerts_uniq,
  ADD CONSTRAINT dashboard_alerts_uniq UNIQUE (username, name, widgetid);

-- Create dashboard from all widgets assigned to each user
INSERT INTO dashboard_dashboards ("name", "username", "public", "widgets")
    SELECT username || '''s dashboard', username, 0, string_agg(id::text, ',')
    FROM dashboard_widgets
    WHERE id > 3
    GROUP BY username;

-- Update each widget with newly assigned dashboard id
UPDATE dashboard_widgets SET dashboardid = (
    SELECT dash_id
    FROM (
        SELECT id as dash_id, unnest(string_to_array(widgets,','))::integer wid_id 
        FROM dashboard_dashboards) as wid
    WHERE dashboard_widgets.id = wid.wid_id);

-- OOTB Changes widget 3.7.0
INSERT INTO "dashboard_widgets" ("id", "name", "type", "username")
  SELECT 0, 'Changes',  'changes',  'admin'
WHERE 
  NOT EXISTS (
    SELECT id 
    FROM dashboard_widgets 
    WHERE name = 'Changes' AND username = 'admin'
  );

-- Default dashboard, 3.7.0
INSERT INTO "dashboard_dashboards" ("name", "username", "public", "widgets")
  SELECT 'Default dashboard', 'admin', '1', '0,1,2,3'
WHERE
  NOT EXISTS (
    SELECT id
    FROM dashboard_dashboards
    WHERE name = 'Default dashboard' AND username = 'admin'
  );


  -- OOTB inventory variables 3.7.0
INSERT INTO "variables_dictionary" ("attribute_name", "category", "readonly", "type", "convert_function") VALUES
('attribute_name=CPU physical cores', 'Hardware', '1', 'int', NULL),
('attribute_name=CPU sockets', 'Hardware', '1', 'int', NULL);