\set ON_ERROR_STOP true

INSERT INTO "roles" ("name", "description") VALUES
('admin', 'Admin role'),
('cf_remoteagent',  'Allow execution of cf-runagent')
 ON CONFLICT DO NOTHING;

-- In case of an upgrade postinstall will generate a new key.
DELETE FROM oauth_clients WHERE client_id = 'MP';
INSERT INTO oauth_clients VALUES ('MP', 'CFE_CLIENT_SECRET_KEY', '', 'password refresh_token', NULL, NULL);

--- ENT-4093  NULLs are converted to empty strings in variable table ---
UPDATE scheduledreports SET query = regexp_replace(query, 'variablevalue(\s+)IS(\s+)NULL', 'variablevalue = ''''', 'ig');
UPDATE scheduledreports SET query = regexp_replace(query, 'variablevalue(\s+)IS(\s+)NOT(\s+)NULL', 'variablevalue != ''''', 'ig');

--- ENT-4139 Insert RBAC permissions

INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
('inventory.post', 'Get inventory report', 'Inventory API', 'true', '', 'API'),
('variablesDictionary.get', 'Get inventory attributes', 'Inventory API', 'true', '', 'API'),
('variablesDictionaryUpdate.post', 'Update inventory attributes', 'Inventory API', 'true', '', 'API'),
('changesPolicyV2.get', 'Get changes', 'Changes API', 'true', '', 'API'),
('changesPolicyCountV2.get', 'Get changes policy count', 'Changes API', 'true', '', 'API'),
('eventList.get', 'Get event list', 'Events API', 'true', '', 'API'),
('event.get', 'Get event', 'Events API', 'true', '', 'API'),
('event.delete', 'Delete event', 'Events API', 'false', '', 'API'),
('eventBatchDelete.delete', 'Batch delete', 'Events API', 'false', '', 'API'),
('host-vital.get', 'Get host vital', 'Hosts', 'true', '', 'API'),
('host-context-list.get', 'Get host classes', 'Hosts', 'false', '', 'API'),
('host-vital-list.get', 'Get host vital list', 'Hosts', 'true', '', 'API'),
('host.get', 'View host', 'Hosts', 'true', '', 'API'),
('host.delete', 'Delete', 'Hosts', 'false', '', 'API'),
('hostlist.get', 'Host list', 'Hosts', 'true', '', 'API'),
('host-count.post', 'Get host count', 'Hosts', 'true', '', 'API'),
('policyBrowser.get', 'Get file and directory lists', 'Policy analyzer', 'false', '', 'API'),
('policyContent.get', 'Get policy content', 'Policy analyzer', 'false', '', 'API'),
('queryAsyncId.get', 'Get async query status', 'Query API', 'true', '', 'API'),
('queryAsyncId.delete', 'Abort async query', 'Query API', 'true', '', 'API'),
('queryAsync.post', 'Create async query', 'Query API', 'true', '', 'API'),
('query.post', 'Run query', 'Query API', 'true', '', 'API'),
('rbacPermissionList.get', 'Get permission list', 'RBAC', 'false', '', 'API'),
('role.get', 'View role', 'Roles', 'false', '', 'API'),
('role.create', 'Create role', 'Roles', 'false', '', 'API'),
('role.update', 'Update role', 'Roles', 'false', '', 'API'),
('role.delete', 'Delete role', 'Roles', 'false', '', 'API'),
('role.list', 'Role list', 'Roles', 'false', '', 'API'),
('default-role.get', 'View default role', 'Roles', 'false', '', 'API'),
('default-role.post', 'Change default role', 'Roles', 'false', '', 'API'),
('rolePermission.get', 'Get role permissions', 'RBAC', 'false', '', 'API'),
('rolePermission.update', 'Assign permissions to role', 'RBAC', 'false', '', 'API'),
('rolePermission.delete', 'Revoke permissions from role', 'RBAC', 'false', '', 'API'),
('settings.get', 'View settings', 'Settings', 'true', '', 'API'),
('settings.update', 'Update settings', 'Settings', 'false', '', 'API'),
('userSubscriptionQuery.get', 'View report', 'Scheduled reports', 'true', '', 'API'),
('userSubscriptionQuery.put', 'Create report', 'Scheduled reports', 'true', '', 'API'),
('userSubscriptionQuery.delete', 'Delete report', 'Scheduled reports', 'true', '', 'API'),
('userSubscriptionQueryList.get', 'View report list', 'Scheduled reports', 'true', '', 'API'),
('user.get', 'View users info', 'User', 'true', '', 'API'),
('user.put', 'Create user', 'User', 'false', '', 'API'),
('user.post', 'Update user', 'User', 'false', '', 'API'),
('user.delete', 'Delete user', 'User', 'false', '', 'API'),
('userList.get', 'User list', 'User', 'true', '', 'API'),
('vcs.get', 'View VCS settings', 'Version control system', 'false', '', 'API'),
('vcs.post', 'Update VCS settings', 'Version control system', 'false', '', 'API'),
('vcs.delete', 'Delete VCS settings', 'Version control system', 'false', '', 'API'),
('apps.index', 'View application list', 'Application management', 'false', '', 'Mission portal'),
('apps.save', 'Save application settings', 'Application management', 'false', 'change order and enable/disable', 'Mission portal'),
('apps.apprefresh', 'Refresh app list', 'Application management', 'false', '', 'Mission portal'),
('auth.admin_page', 'View settings page', 'User/Role management', 'false', '', 'Mission portal'),
('auth.change_password', 'Change password', 'User/Role management', 'false', '', 'Mission portal'),
('auth.create_user', 'Create user', 'User/Role management', 'false', '', 'Mission portal'),
('auth.edit_user', 'Edit user', 'User/Role management', 'false', '', 'Mission portal'),
('auth.manage_role', 'Create role', 'User/Role management', 'false', '', 'Mission portal'),
('auth.setDefaultRole', 'Set default role', 'User/Role management', 'false', '', 'Mission portal'),
('auth.delete_user', 'Delete user', 'User/Role management', 'false', '', 'Mission portal'),
('auth.delete_role', 'Delete role', 'User/Role management', 'false', '', 'Mission portal'),
('events.viewAllEvents', 'View whole system events', 'Events', 'false', 'otherwise user will be able to see only their events', 'Mission portal'),
('rbac.index', 'View settings page', 'Role base access control', 'false', '', 'Mission portal'),
('rbac.edit', 'Edit role permissions', 'Role base access control', 'false', '', 'Mission portal'),
('settings.manage', 'Preferences', 'Settings', 'false', '', 'Mission portal'),
('settings.systemIdentifier', 'Host identifier', 'Settings', 'false', '', 'Mission portal'),
('settings.vcs', 'Version control repository', 'Settings', 'false', '', 'Mission portal'),
('settings.vcsReset', 'Reset version control repository', 'Settings', 'false', '', 'Mission portal'),
('settings.online_users', 'Active tokens', 'Settings', 'false', '', 'Mission portal'),
('settings.revoke_token', 'Revoke tokens', 'Settings', 'false', '', 'Mission portal'),
('settings.notification_scripts', 'View', 'Notification scripts', 'false', '', 'Mission portal'),
('settings.notification_scripts_delete', 'Delete', 'Notification scripts', 'false', '', 'Mission portal'),
('settings.notification_scripts_update', 'Create', 'Notification scripts', 'false', '', 'Mission portal'),
('settings.mail', 'Update mail settings', 'Settings', 'false', '', 'Mission portal'),
('settings.sendTestEmail', 'Send test mail', 'Settings', 'false', '', 'Mission portal'),
('settings.ldap_api_settings', 'Update LDAP auth settings', 'Settings', 'false', '', 'Mission portal'),
('settings.saveAuthenticationMethod', 'Change authentication method', 'Settings', 'false', '', 'Mission portal'),
('reports.admin', 'Modify all users'' reports', 'Reports', 'false', 'View, Update, Delete', 'Mission portal'),
('widgets.alerts_admin', 'Modify all users'' alert', 'Widgets', 'false', 'View, Update, Delete', 'Mission portal'),
('widgets.rules_admin', 'Modify all users'' rules', 'Widgets', 'false', 'View, Update, Delete', 'Mission portal'),
('data_transfer_api.admin_permissions', 'Allow to export and import system settings', 'Data transfer', 'false', '', 'Mission portal'),
('data_transfer_api.export_get', 'API: Export', 'Data transfer', 'true', '', 'Mission portal'),
('data_transfer_api.exportItems_get', 'API: Get export categories', 'Data transfer', 'true', '', 'Mission portal'),
('data_transfer_api.import_post', 'API: Import', 'Data transfer', 'true', '', 'Mission portal'),
('data_transfer_api.analyzeImportFile_post', 'API: Analyze import file', 'Data transfer', 'true', '', 'Mission portal'),
('data_transfer_api.download_get', 'API: Download export file', 'Data transfer', 'true', '', 'Mission portal'),
('data_transfer.index', 'View data transfer page', 'Data transfer', 'true', '', 'Mission portal'),
('analyzer.index', 'View policy analyzer page', 'Policy analyzer', 'false', '', 'Mission portal'),
('analyzer.enableCopying_get', 'Enable policy analyzer', 'Policy analyzer', 'false', 'allow copying masterfiles directory', 'Mission portal')
ON CONFLICT (alias)  DO NOTHING;


INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
('admin', 'inventory.post'),
('admin', 'variablesDictionary.get'),
('admin', 'variablesDictionaryUpdate.post'),
('admin', 'changesPolicyV2.get'),
('admin', 'changesPolicyCountV2.get'),
('admin', 'eventList.get'),
('admin', 'event.get'),
('admin', 'event.delete'),
('admin', 'eventBatchDelete.delete'),
('admin', 'host-vital.get'),
('admin', 'host-context-list.get'),
('admin', 'host-vital-list.get'),
('admin', 'host.get'),
('admin', 'host.delete'),
('admin', 'hostlist.get'),
('admin', 'host-count.post'),
('admin', 'policyBrowser.get'),
('admin', 'policyContent.get'),
('admin', 'queryAsyncId.get'),
('admin', 'queryAsyncId.delete'),
('admin', 'queryAsync.post'),
('admin', 'query.post'),
('admin', 'rbacPermissionList.get'),
('admin', 'role.get'),
('admin', 'role.create'),
('admin', 'role.update'),
('admin', 'role.delete'),
('admin', 'role.list'),
('admin', 'default-role.get'),
('admin', 'default-role.post'),
('admin', 'rolePermission.get'),
('admin', 'rolePermission.update'),
('admin', 'rolePermission.delete'),
('admin', 'settings.get'),
('admin', 'settings.update'),
('admin', 'userSubscriptionQuery.get'),
('admin', 'userSubscriptionQuery.put'),
('admin', 'userSubscriptionQuery.delete'),
('admin', 'userSubscriptionQueryList.get'),
('admin', 'user.get'),
('admin', 'user.put'),
('admin', 'user.post'),
('admin', 'user.delete'),
('admin', 'userList.get'),
('admin', 'vcs.get'),
('admin', 'vcs.post'),
('admin', 'vcs.delete'),
('admin', 'apps.index'),
('admin', 'apps.save'),
('admin', 'apps.apprefresh'),
('admin', 'auth.admin_page'),
('admin', 'auth.change_password'),
('admin', 'auth.create_user'),
('admin', 'auth.edit_user'),
('admin', 'auth.manage_role'),
('admin', 'auth.setDefaultRole'),
('admin', 'auth.delete_user'),
('admin', 'auth.delete_role'),
('admin', 'events.viewAllEvents'),
('admin', 'rbac.index'),
('admin', 'rbac.edit'),
('admin', 'settings.manage'),
('admin', 'settings.systemIdentifier'),
('admin', 'settings.vcs'),
('admin', 'settings.vcsReset'),
('admin', 'settings.online_users'),
('admin', 'settings.revoke_token'),
('admin', 'settings.notification_scripts'),
('admin', 'settings.notification_scripts_delete'),
('admin', 'settings.notification_scripts_update'),
('admin', 'settings.mail'),
('admin', 'settings.sendTestEmail'),
('admin', 'settings.ldap_api_settings'),
('admin', 'settings.saveAuthenticationMethod'),
('admin', 'reports.admin'),
('admin', 'widgets.alerts_admin'),
('admin', 'widgets.rules_admin'),
('admin', 'data_transfer_api.admin_permissions'),
('admin', 'data_transfer_api.export_get'),
('admin', 'data_transfer_api.exportItems_get'),
('admin', 'data_transfer_api.import_post'),
('admin', 'data_transfer_api.analyzeImportFile_post'),
('admin', 'data_transfer_api.download_get'),
('admin', 'data_transfer.index'),
('admin', 'analyzer.index'),
('admin', 'analyzer.enableCopying_get')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;

-- cf_remoteagent role permissions --
INSERT INTO "rbac_role_permission" ("role_id", "permission_alias") VALUES
('cf_remoteagent',	'changesPolicyV2.get'),
('cf_remoteagent',	'changesPolicyCountV2.get'),
('cf_remoteagent',	'eventBatchDelete.delete'),
('cf_remoteagent',	'event.delete'),
('cf_remoteagent',	'event.get'),
('cf_remoteagent',	'eventList.get'),
('cf_remoteagent',	'host-context-list.get'),
('cf_remoteagent',	'host-count.post'),
('cf_remoteagent',	'host-vital.get'),
('cf_remoteagent',	'host-vital-list.get'),
('cf_remoteagent',	'hostlist.get'),
('cf_remoteagent',	'host.get'),
('cf_remoteagent',	'variablesDictionary.get'),
('cf_remoteagent',	'inventory.post'),
('cf_remoteagent',	'variablesDictionaryUpdate.post'),
('cf_remoteagent',	'queryAsyncId.delete'),
('cf_remoteagent',	'queryAsync.post'),
('cf_remoteagent',	'queryAsyncId.get'),
('cf_remoteagent',	'query.post'),
('cf_remoteagent',	'rbacPermissionList.get'),
('cf_remoteagent',	'role.list'),
('cf_remoteagent',	'userSubscriptionQuery.get'),
('cf_remoteagent',	'userSubscriptionQueryList.get'),
('cf_remoteagent',	'userList.get'),
('cf_remoteagent',	'user.get')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;

-- ENT-4513 To reduce access level remove admin role for CFE_ROBOT user --
UPDATE users SET roles = '{cf_remoteagent}' WHERE username = 'CFE_ROBOT';

--- Federated reporting RBAC rules ---
INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
('federationConfig.post', 'Generate federation config file', 'Federation report API', 'false', 'from information previously stored in database', 'API'),
('federationConfig.delete', 'Delete federation config file', 'Federation report API', 'false', '', 'API'),
('remoteHub.list', 'Remote hubs list', 'Remote hub API', 'false', '', 'API'),
('remoteHub.create', 'Create remote hub', 'Remote hub API', 'false', '', 'API'),
('remoteHub.get', 'Get remote hub', 'Remote hub API', 'false', '', 'API'),
('remoteHub.update', 'Update remote hub', 'Remote hub API', 'false', '', 'API'),
('remoteHub.delete', 'Delete remote hub', 'Remote hub API', 'false', '', 'API'),
('setupHub.enable', 'Enable hub', 'Federation report API', 'false', '', 'API'),
('hubStatus.get', 'Get hub status', 'Federation report API', 'false', '', 'API')
ON CONFLICT (alias)  DO NOTHING;


INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
('admin', 'federationConfig.post'),
('admin', 'federationConfig.delete'),
('admin', 'remoteHub.list'),
('admin', 'remoteHub.create'),
('admin', 'remoteHub.get'),
('admin', 'remoteHub.update'),
('admin', 'remoteHub.delete'),
('admin', 'setupHub.enable'),
('admin', 'hubStatus.get')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;


INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
('hubState.post', 'Change hub target state', 'Federation report API', 'false', '', 'API')
ON CONFLICT (alias)  DO NOTHING;


INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
('admin', 'hubState.post')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;

INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
('customization', 'Customization', 'Settings', 'false', '', 'Mission Portal')
ON CONFLICT (alias)  DO NOTHING;

INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
('admin', 'customization')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;

INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
('fileChanges.files', 'Get files list', 'File changes API', 'true', '', 'API')
ON CONFLICT (alias)  DO NOTHING;

INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
('admin', 'fileChanges.files')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;

UPDATE rbac_permissions SET "application" = 'Mission Portal' WHERE "application" = 'Mission portal';

UPDATE rbac_permissions SET "allowed_by_default" = 'true' WHERE "alias" = 'role.list';
UPDATE rbac_permissions SET "allowed_by_default" = 'true' WHERE "alias" = 'host-context-list.get';

INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
('unfiltered-host-count.get', 'Get unfiltered hosts count', 'Hosts', 'false', 'Hosts count information with no RBAC applied', 'API')
ON CONFLICT (alias)  DO NOTHING;


INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
('admin', 'unfiltered-host-count.get')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;

-- Added RBAC permission to access `hosts never collected from` report --
INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
('HostsNeverCollectedReport.post', 'Access to `hosts never collected from` report', 'Health Diagnostic', 'false', '', 'API')
ON CONFLICT (alias)  DO NOTHING;
-- By default admin is able to access `hosts never collected from` report --
INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
('admin', 'HostsNeverCollectedReport.post')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;

INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
('actions.report_collection', 'Report collection', 'Actions', 'true', 'Triggering report collection by a host key', 'API'),
('actions.agent_run', 'Agent run', 'Actions', 'true', 'Triggering agent run with cf-runagent', 'API')
ON CONFLICT (alias)  DO NOTHING;

INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
('admin', 'actions.report_collection'),
('admin', 'actions.agent_run')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;

INSERT INTO inventory_aliases ("inventory_attribute", "alias")
VALUES
('Kernel', 'os type'),
('Kernel Release', 'os kernel')
ON CONFLICT ("inventory_attribute", "alias")  DO NOTHING;

-- CMDB RBAC permissions --
INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
('cmdb.list', 'Get configs list', 'CMDB', 'true', '', 'API'),
('cmdb.batch_create', 'Batch create', 'CMDB', 'false', '', 'API'),
('cmdb.get', 'Get config', 'CMDB', 'true', '', 'API'),
('cmdb.create', 'Create config', 'CMDB', 'false', '', 'API'),
('cmdb.delete', 'Delete config', 'CMDB', 'false', '', 'API'),
('cmdb.update', 'Update config', 'CMDB', 'false', '', 'API')
ON CONFLICT (alias)  DO NOTHING;


INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
('admin', 'cmdb.list'),
('cf_remoteagent', 'cmdb.list'),
('admin', 'cmdb.batch_create'),
('admin', 'cmdb.get'),
('cf_remoteagent', 'cmdb.get'),
('admin', 'cmdb.create'),
('admin', 'cmdb.delete'),
('admin', 'cmdb.update')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;

-- allow getting hub status by default to disable CMDB in case of superhub enabled and configured
UPDATE rbac_permissions SET "allowed_by_default" = 'true' WHERE "alias" = 'hubStatus.get';

-- allow getting deleted hosts list with no DB RBAC applied
INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
('hosts-deleted.get', 'Get deleted hosts list', 'Hosts', 'false', 'No RBAC applied', 'API')
ON CONFLICT (alias)  DO NOTHING;


INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
('admin', 'hosts-deleted.get'),
('cf_remoteagent', 'hosts-deleted.get')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;

INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
('build.projects.get', 'Get project', 'Build Projects API', 'false', '', 'API'),
('build.projects.create', 'Create project', 'Build Projects API', 'false', '', 'API'),
('build.projects.update', 'Update project', 'Build Projects API', 'false', '', 'API'),
('build.projects.delete', 'Delete project', 'Build Projects API', 'false', '', 'API')
ON CONFLICT (alias)  DO NOTHING;


INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
('admin', 'build.projects.get'),
('admin', 'build.projects.create'),
('admin', 'build.projects.update'),
('admin', 'build.projects.delete')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;

INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
('build.modules-list.get', 'Get modules list', 'Modules List API', 'true', '', 'API'),
('build.modules-list.update', 'Update modules list', 'Modules List API', 'true', '', 'API'),
('build.module.get', 'Get module by name', 'Modules List API', 'true', '', 'API'),
('build.project-modules.get', 'Get modules added to project', 'Build Projects API', 'false', '', 'API'),
('build.projects.sync', 'Sync project changes', 'Build Projects API', 'false', '', 'API'),
('build.project-modules.post', 'Add module to project', 'Build Projects API', 'false', '', 'API'),
('build.project-modules.delete', 'Remove module from project', 'Build Projects API', 'false', '', 'API'),
('build.project-modules.patch', 'Update module version', 'Build Projects API', 'false', '', 'API'),
('build.projects.refresh', 'Refresh project', 'Build Projects API', 'false', '', 'API'),
('ssh.get', 'SSH keys list', 'Generate SSH API', 'false', '', 'API'),
('ssh.delete', 'Remove SSH key', 'Generate SSH API', 'false', '', 'API'),
('ssh.post', 'Generate SSH key', 'Generate SSH API', 'false', '', 'API'),
('build.projects.local_deploy', 'Deploy project locally', 'Build Projects API', 'false', '', 'API'),
('build.module.input.get', 'Get module input', 'Build Projects API', 'false', '', 'API'),
('build.module.input.set', 'Set module input', 'Build Projects API', 'false', '', 'API')
ON CONFLICT (alias)  DO NOTHING;


INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
('admin', 'build.modules-list.get'),
('admin', 'build.modules-list.update'),
('admin', 'build.module.get'),
('admin', 'build.project-modules.get'),
('admin', 'build.projects.sync'),
('admin', 'build.project-modules.post'),
('admin', 'build.project-modules.delete'),
('admin', 'build.project-modules.patch'),
('admin', 'build.projects.refresh'),
('admin', 'ssh.get'),
('admin', 'ssh.delete'),
('admin', 'ssh.post'),
('admin', 'build.projects.local_deploy'),
('admin', 'build.module.input.get'),
('admin', 'build.module.input.set')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;


INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
    ('host-groups-personal.get', 'Get personal host groups', 'Personal Host Groups API', 'true', '', 'API'),
    ('host-groups-personal.post', 'Create personal host groups', 'Personal Host Groups API', 'true', '', 'API'),
    ('host-groups-personal.patch', 'Update personal host groups', 'Personal Host Groups API', 'true', 'Update filter and name, excluding group data', 'API'),
    ('host-groups-personal.delete', 'Delete personal host groups', 'Personal Host Groups API', 'true', '', 'API'),
    ('host-groups-shared.get', 'Get shared host groups', 'Shared Host Groups API', 'true', '', 'API'),
    ('host-groups-shared.post', 'Create shared host groups', 'Shared Host Groups API', 'false', '', 'API'),
    ('host-groups-shared.patch', 'Update shared host groups', 'Shared Host Groups API', 'false', 'Update filter and name, excluding group data', 'API'),
    ('host-groups-shared.delete', 'Delete shared host groups', 'Shared Host Groups API', 'false', '', 'API'),
    ('host-groups-personal-favorite.post', 'Add group to favorite', 'Personal Host Groups API', 'true', '', 'API'),
    ('host-groups-personal-favorite.delete', 'Remove group from favorite', 'Personal Host Groups API', 'true', '', 'API'),
    ('host-groups-shared-favorite.post', 'Add group to favorite', 'Shared Host Groups API', 'true', '', 'API'),
    ('host-groups-shared-favorite.delete', 'Remove group from favorite', 'Shared Host Groups API', 'true', '', 'API'),
    ('shared-group-cmdb.get', 'Get data', 'Shared host group configuration management data', 'true', '', 'API'),
    ('shared-group-cmdb.create', 'Create data', 'Shared host group configuration management data', 'false', '', 'API'),
    ('shared-group-cmdb.delete', 'Delete data', 'Shared host group configuration management data', 'false', '', 'API'),
    ('shared-group-cmdb.update', 'Update data', 'Shared host group configuration management data', 'false', '', 'API')
    ON CONFLICT (alias)  DO NOTHING;


INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
    ('admin', 'host-groups-personal.get'),
    ('admin', 'host-groups-personal.post'),
    ('admin', 'host-groups-personal.patch'),
    ('admin', 'host-groups-personal.delete'),
    ('admin', 'host-groups-shared.get'),
    ('admin', 'host-groups-shared.post'),
    ('admin', 'host-groups-shared.patch'),
    ('admin', 'host-groups-shared.delete'),
    ('admin', 'host-groups-personal-favorite.post'),
    ('admin', 'host-groups-personal-favorite.delete'),
    ('admin', 'host-groups-shared-favorite.post'),
    ('admin', 'host-groups-shared-favorite.delete'),
    ('admin', 'shared-group-cmdb.get'),
    ('admin', 'shared-group-cmdb.create'),
    ('admin', 'shared-group-cmdb.delete'),
    ('admin', 'shared-group-cmdb.update')
    ON CONFLICT (role_id, permission_alias)  DO NOTHING;


INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
    ('any-host.delete', 'Delete any hosts', 'Hosts', 'false', 'Allows to delete any hosts despite database RBAC', 'API')
    ON CONFLICT (alias)  DO NOTHING;

INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES ('admin', 'any-host.delete')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;


INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
    ('cmdb.view-host-json', 'View host specific rendered JSON config', 'CMDB', 'true', '', 'API')
ON CONFLICT (alias)  DO NOTHING;

INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
    ('admin', 'cmdb.view-host-json')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;


DO $$
       DECLARE current_group_ootb_version NUMERIC;
BEGIN
    SELECT get_from_system('groups_ootb_version', to_jsonb(0)) INTO current_group_ootb_version;
    IF current_group_ootb_version < 1 THEN
        INSERT INTO shared_host_groups ("name", "creator", "filter", "filter_sql", "meta_data") VALUES
        ('All', 'CFE_ROBOT', '{}', 'hostkey IS NOT NULL', '{"source": "from CFEngine team"}' ),
        ('Windows', 'CFE_ROBOT', '{"filter": null, "hostFilter": null, "hostContextInclude": ["windows"]}',  'inventory_new.hostkey IN (SELECT v_contextcache.hostkey FROM v_contextcache WHERE ContextVector @@ to_tsquery(''simple'', ''(windows)''))', '{"source": "from CFEngine team"}' ),
        ('Linux', 'CFE_ROBOT', '{"filter": null, "hostFilter": null, "hostContextInclude": ["linux"]}',  'inventory_new.hostkey IN (SELECT v_contextcache.hostkey FROM v_contextcache WHERE ContextVector @@ to_tsquery(''simple'', ''(linux)''))', '{"source": "from CFEngine team"}' ),
        ('Ubuntu', 'CFE_ROBOT', '{"filter": null, "hostFilter": null, "hostContextInclude": ["ubuntu"]}',  'inventory_new.hostkey IN (SELECT v_contextcache.hostkey FROM v_contextcache WHERE ContextVector @@ to_tsquery(''simple'', ''(ubuntu)''))', '{"source": "from CFEngine team"}' ),
        ('RHEL', 'CFE_ROBOT', '{"filter": null, "hostFilter": null, "hostContextInclude": ["redhat_pure"]}',  'inventory_new.hostkey IN (SELECT v_contextcache.hostkey FROM v_contextcache WHERE ContextVector @@ to_tsquery(''simple'', ''(redhat.pure)''))', '{"source": "from CFEngine team"}' ),
        ('CFEngine clients', 'CFE_ROBOT', '{"filter": {"CFEngine roles": {"regex_not_match": "Reporting hub|policy_server"}}, "hostFilter": null, "hostContextInclude": []}', '  COALESCE (values->>''CFEngine roles'', ''　'') !~* ''Reporting hub|policy_server''', '{"source": "from CFEngine team"}' ),
        ('CFEngine hub(s)', 'CFE_ROBOT', '{"filter": {"CFEngine roles": {"regex_matches": "Reporting hub|policy_server"}}, "hostFilter": null, "hostContextInclude": []}', 'COALESCE (values->>''CFEngine roles'', ''　'') ~* ''Reporting hub|policy_server''', '{"source": "from CFEngine team"}' )
        ON CONFLICT (name, deletion_time) DO NOTHING;
        PERFORM inc_system_value('groups_ootb_version');
    END IF;
END $$;


-- ENT-8001: RBAC permissions to query `removed hosts still reporting` view
INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
    ('deletedHostsReportHD.post', 'Access to `removed hosts still reporting` report', 'Health Diagnostic', 'false', '', 'API'),
    ('hosts-undelete.post', 'Restore deleted hosts database entries', 'Hosts', 'false', 'No RBAC applied', 'API'),
    ('hosts-delete-permanently.delete', 'Delete hosts permanently', 'Hosts', 'false', 'No RBAC applied', 'API')
ON CONFLICT (alias)  DO NOTHING;


INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
    ('admin', 'deletedHostsReportHD.post'),
    ('admin', 'hosts-undelete.post'),
    ('admin', 'hosts-delete-permanently.delete')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;

INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
    ('all-users-tokens.revoke', 'Revoke all users auth tokens', 'OAuth', 'false', '', 'API'),
    ('all-users-tokens.get', 'See all users auth tokens', 'OAuth', 'false', '', 'API')
ON CONFLICT (alias)  DO NOTHING;


INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
    ('admin', 'all-users-tokens.revoke'),
    ('admin', 'all-users-tokens.get')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;

-- allowed active tokens menu by default, as it shows only tokens belonged to a current user
UPDATE rbac_permissions SET allowed_by_default = true WHERE alias = 'settings.online_users';
UPDATE rbac_permissions SET allowed_by_default = true WHERE alias = 'settings.revoke_token';


INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
    ('2fa.any-user.disable', 'Disable 2FA for any user', 'Two-factor authentication', 'false', '', 'API'),
    ('user.unlock', 'Unlock user', 'User', 'false', 'Allows unlocking a user account that was locked due to not setting up two-factor authentication after enforcement', 'API')
ON CONFLICT (alias)  DO NOTHING;

INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
    ('admin', '2fa.any-user.disable'),
    ('admin', 'user.unlock')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;


INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
    ('audit-log.view', 'View audit log', 'Audit log', 'false', '', 'API')
ON CONFLICT (alias)  DO NOTHING;

INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
    ('admin', 'audit-log.view')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;

-- ENT-12185 --
-- Insert 'is_setup_complete' with FALSE if there are no users in the system
-- This prevents issues with version updates.
INSERT INTO system ("key", "value")
SELECT 'is_setup_complete', 'false'
WHERE NOT EXISTS (SELECT 1 FROM users LIMIT 1)
ON CONFLICT ("key") DO NOTHING;

INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
('ai-settings.get', 'View AI settings', 'AI settings', 'true', '', 'API'),
('ai-settings.update', 'Update AI settings', 'AI settings', 'false', '', 'API'),
('ai.chat.message', 'Send message to AI chat', 'AI Chat', 'true', '', 'API')
ON CONFLICT (alias)  DO NOTHING;


INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
('admin', 'ai-settings.get'),
('admin', 'ai-settings.update'),
('admin', 'ai.chat.message')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;

DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM rbac_permissions WHERE alias = 'user.update_own_profile') THEN
        DELETE FROM rbac_role_permission WHERE "role_id" != 'admin' AND permission_alias = 'user.post';
        UPDATE rbac_permissions SET allowed_by_default = 'false' WHERE "alias" = 'user.post';

        INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
        VALUES
        ('user.update_own_profile', '', '', 'true', 'Allows users to change their own password or time zone', 'API')
        ON CONFLICT (alias)  DO NOTHING;

        INSERT INTO rbac_role_permission ("role_id", "permission_alias")
        VALUES
        ('admin', 'user.update_own_profile')
        ON CONFLICT (role_id, permission_alias)  DO NOTHING;
    END IF;
END $$;

INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
('autocomplete.get.classes', 'Search classes', 'Autocomplete API', 'true', 'This request bypasses database RBAC and allows seeing any class name in the system', 'API'),
('autocomplete.get.variables', 'Search variables', 'Autocomplete API', 'true', 'This request bypasses database RBAC and allows seeing any variable name in the system', 'API')
ON CONFLICT (alias)  DO NOTHING;

INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
('admin', 'autocomplete.get.classes'),
('admin', 'autocomplete.get.variables')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;

-- ENT-4244 RBAC permissions for hosts cleanup API
INSERT INTO rbac_permissions ("alias", "name", "group", "allowed_by_default", "description", "application")
VALUES
('host.cleanup', 'Host cleanup', 'Hosts', 'false', 'Clean up hosts based on multiple criteria. No RBAC applied.', 'API')
ON CONFLICT (alias)  DO NOTHING;

INSERT INTO rbac_role_permission ("role_id", "permission_alias")
VALUES
('admin', 'host.cleanup'),
('cf_remoteagent', 'host.cleanup')
ON CONFLICT (role_id, permission_alias)  DO NOTHING;
