#!/usr/bin/env bash
set -euo pipefail

# Run this as the SITE user (e.g. su - spille)
OMD_ROOT="${OMD_ROOT:?OMD_ROOT not set (are you inside the site shell?)}"

AGENT_USER="push_agent_register"

gen_secret() {
  openssl rand -hex 32
}

ensure_htpasswd_user() {
  local user="$1"
  local secret="$2"
  # -B = bcrypt (recommended), -b = batch
  htpasswd -B -b "${OMD_ROOT}/etc/htpasswd" "${user}" "${secret}" >/dev/null
}

ensure_automation_secret_file() {
  local user="$1"
  local secret="$2"
  local dir="${OMD_ROOT}/var/check_mk/web/${user}"
  install -d -m 0700 "${dir}"
  umask 0077
  printf '%s\n' "${secret}" > "${dir}/automation.secret"
  chmod 0600 "${dir}/automation.secret"
}

cat << EOF > ~/etc/check_mk/multisite.d/wato/roles.mk 
# Written by Checkmk store

roles.update({'user': {'alias': 'Normal monitoring user', 'permissions': {}, 'builtin': True, 'two_factor': False}, 'admin': {'alias': 'Administrator', 'permissions': {}, 'builtin': True, 'two_factor': False}, 'guest': {'alias': 'Guest user', 'permissions': {}, 'builtin': True, 'two_factor': False}, 'agent_registration': {'alias': 'Agent registration user', 'permissions': {}, 'builtin': True, 'two_factor': False}, 'no_permissions': {'alias': 'Empty template for least privilege roles', 'permissions': {}, 'builtin': True, 'two_factor': False}, 'push_agent': {'alias': 'push_agent', 'permissions': {'wato.edit': True, 'wato.activate': True, 'wato.activateforeign': True, 'wato.manage_hosts': True, 'wato.manage_folders': True, 'wato.see_all_folders': True, 'wato.all_folders': True}, 'builtin': False, 'two_factor': False, 'basedon': 'agent_registration'}})
EOF

cat << EOF > ~/etc/check_mk/multisite.d/wato/groups.mk 
# Created by WATO

multisite_hostgroups = \
{}

multisite_servicegroups = \
{}

multisite_contactgroups = \
{'all': {}, 'cmk_push_agent': {'inventory_paths': 'allow_all'}}

EOF

cat << EOF > ~/etc/check_mk/conf.d/wato/groups.mk 
# Created by WATO

define_hostgroups = \
{}

define_servicegroups = \
{}

define_contactgroups = \
{'all': 'Everything', 'cmk_push_agent': 'cmk_push_agent'}
EOF

cat << EOF >  ~/etc/check_mk/conf.d/wato/.wato
{'__id': '1631f55c6ca04bfb9ab5a9a9abe0d9d5', 'title': 'Main', 'attributes': {'contactgroups': {'groups': ['cmk_push_agent'], 'recurse_perms': True, 'use': False, 'use_for_services': False, 'recurse_use': False}, 'meta_data': {'created_at': 1766087299.3927488, 'created_by': None, 'updated_at': 1766087299.3927488}}, 'num_hosts': 0, 'lock': False, 'lock_subfolders': False}
EOF

cat << EOF > ~/etc/check_mk/multisite.d/wato/users.mk 
## Written by Checkmk store

multisite_users.update({'cmkadmin': {'alias': 'cmkadmin', 'roles': ['admin'], 'locked': False, 'connector': 'htpasswd'}, 'agent_registration': {'alias': 'Check_MK Agent Registration - used for agent registration', 'roles': ['agent_registration'], 'locked': False, 'language': 'en', 'connector': 'htpasswd'}, 'push_agent_register': {'alias': 'push_agent_register', 'connector': 'htpasswd', 'locked': False, 'roles': ['push_agent'], 'temperature_unit': None, 'force_authuser': False, 'nav_hide_icons_title': None, 'icons_per_item': None, 'show_mode': None, 'contextual_help_icon': None}})
EOF

cat << EOF > ~/etc/check_mk/conf.d/wato/rules.mk
# Written by Checkmk store


active_checks.setdefault('cmk_inv', [])

active_checks['cmk_inv'] = [
{'id': '7ba2ac2a-5a49-47ce-bc3c-1630fb191c7f', 'value': {'status_data_inventory': True}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/docker_object:node')])]}, 'options': {'description': 'Factory default. Required for the shipped dashboards.'}},
{'id': 'b4b151f9-c7cc-4127-87a6-9539931fcd73', 'value': {'status_data_inventory': True}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes')])]}, 'options': {'description': 'Factory default. Required for the shipped dashboards.'}},
{'id': '2527cb37-e9da-4a15-a7d9-80825a7f6661', 'value': {'status_data_inventory': True}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/kubernetes:yes')])]}, 'options': {'description': 'Factory default. Required for the shipped dashboards.'}},
{'id': 'bea23477-f13a-4e9f-a472-08be507aac9e', 'value': {'status_data_inventory': True}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/rmk/node_type:local')])]}, 'options': {'description': 'Factory default. Required for the shipped dashboards.'}},
] + active_checks['cmk_inv']


globals().setdefault('bulkwalk_hosts', [])

bulkwalk_hosts = [
{'id': 'b92a5406-1d57-4f1d-953d-225b111239e5', 'value': True, 'condition': {'host_tags': {'snmp': 'snmp', 'snmp_ds': {'\$ne': 'snmp-v1'}}}, 'options': {'description': 'Hosts with the tag "snmp-v1" must not use bulkwalk'}},
] + bulkwalk_hosts


globals().setdefault('datasource_programs', [])

datasource_programs = [
{'id': 'e0e676ef-4917-4b3d-82b1-b10e0b58502b', 'value': '/usr/bin/cmk-push-agent-read \$HOSTNAME$', 'condition': {}, 'options': {'disabled': False, 'description': 'Push Agent'}},
] + datasource_programs


extra_host_conf.setdefault('notification_options', [])

extra_host_conf['notification_options'] = [
{'id': '814bf932-6341-4f96-983d-283525b5416d', 'value': 'd,r,f,s', 'condition': {}},
] + extra_host_conf['notification_options']


extra_service_conf.setdefault('check_interval', [])

extra_service_conf['check_interval'] = [
{'id': 'b3847203-84b3-4f5b-ac67-0f06d4403905', 'value': 1440, 'condition': {'service_description': [{'\$regex': 'Check_MK HW/SW Inventory$'}]}, 'options': {'description': 'Restrict HW/SW Inventory to once a day'}},
] + extra_service_conf['check_interval']


globals().setdefault('host_check_commands', [])

host_check_commands = [
{'id': '24da4ccd-0d1b-40e3-af87-0097df8668f2', 'value': ('service', 'Docker container status'), 'condition': {'host_label_groups': [('and', [('and', 'cmk/docker_object:container')])]}, 'options': {'description': 'Make all docker container host states base on the "Docker container status" service'}},
{'id': '63e9f568-3239-4c5a-9edd-339f69bb5ce6', 'value': ('custom', '/usr/share/cmk-push-server/check_hostfile_freshness --hostname \$HOSTNAME$ --warn 1800 --crit 3600'), 'condition': {}, 'options': {'disabled': False, 'description': 'Push Agent Freshess'}},
] + host_check_commands


globals().setdefault('host_contactgroups', [])

host_contactgroups = [
{'id': 'efd67dab-68f8-4d3c-a417-9f7e29ab48d5', 'value': 'all', 'condition': {}, 'options': {'description': 'Put all hosts into the contact group "all"'}},
] + host_contactgroups


globals().setdefault('inventory_df_rules', [])

inventory_df_rules = [
{'id': 'b0ee8a51-703c-47e4-aec4-76430281604d', 'value': {'ignore_fs_types': ['tmpfs', 'nfs', 'smbfs', 'cifs', 'iso9660'], 'never_ignore_mountpoints': ['~.*/omd/sites/[^/]+/tmp$']}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}},
] + inventory_df_rules


globals().setdefault('inventory_processes_rules', [])

inventory_processes_rules = [
{'id': '94a0ead4-a9d8-428d-8b06-10b9f3b5fe26', 'value': {'descr': '%u active check helpers', 'match': '~/omd/sites/[^/]+/lib/cmc/checkhelper', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites active check helpers', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
{'id': '94190e27-2836-488a-b6b4-e13f694a455e', 'value': {'descr': '%u agent receiver', 'match': '~gunicorn:.*cmk.agent_receiver', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites agent receiver', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
{'id': '6b3a78b3-b4e9-4aca-b427-2f656809bf49', 'value': {'descr': '%u alert helper', 'match': '~python3 /omd/sites/[^/]+/bin/cmk --handle-alerts', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites alert helper', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
{'id': '7eda3d76-62ff-4ff6-b84b-a26ce202c577', 'value': {'descr': '%u apache', 'match': '~.*/omd/sites/[^/]+/etc/apache/apache.conf$', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites apache', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
{'id': '94190e27-2836-488a-b6b4-f23f694a455e', 'value': {'descr': '%u automation helpers', 'match': '~gunicorn:.*automation-helper', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites automation helpers', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
{'id': 'feaa2248-08b8-47a3-bc3c-a5502d2b9f3a', 'value': {'descr': '%u checker helpers', 'match': '~python3 /omd/sites/[^/]+/bin/cmk .*--checker', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites checker helpers', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
{'id': '9440a0b2-5eb2-4f52-ac4b-17c6ddecd1f2', 'value': {'descr': '%u cmc', 'match': '~/omd/sites/[^/]+/bin/cmc', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites cmc', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
{'id': 'f56e8b7a-98f0-4597-a030-1f1f6dc2347d', 'value': {'descr': '%u dcd', 'match': '~dcd', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites dcd', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
{'id': '2105c8a7-5672-4242-98f6-fd6ce8b8f3a7', 'value': {'descr': '%u event console', 'match': '~python3 /omd/sites/[^/]+/bin/mkeventd$', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites event console', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
{'id': '0846dd4c-cc62-4adf-9400-7f20a651f996', 'value': {'descr': '%u fetcher helpers', 'match': '~python3 /omd/sites/[^/]+/bin/fetcher', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites fetcher helpers', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
{'id': '9e123cf5-3717-47a1-ba7a-b00f9ede3435', 'value': {'descr': '%u jaeger', 'match': '~/omd/sites/[^/]+/bin/jaeger', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites jaeger', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
{'id': 'df8832aa-3054-4a62-96b8-d960381e6726', 'value': {'descr': '%u livestatus proxy', 'match': '~liveproxyd', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites livestatus proxy', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
{'id': 'f64f23d9-55c5-490c-a7dd-b38a108155e2', 'value': {'descr': '%u notification spooler', 'match': '~python3 /omd/sites/[^/]+/bin/mknotifyd$', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites notification spooler', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
{'id': '459dd81c-cd2c-40bb-ac43-d25440778e7a', 'value': {'descr': '%u notify helper', 'match': '~python3 /omd/sites/[^/]+/bin/cmk --notify --keepalive$', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites notify helper', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
{'id': 'aa86dbc4-c390-48f7-b0ed-44231aa79b7c', 'value': {'descr': '%u piggyback hub', 'match': '~python3 /omd/sites/[^/]+/bin/cmk-piggyback-hub', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites piggyback hub', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
{'id': '65a3dca4-8d71-45d8-8887-53ef0c63d06f', 'value': {'descr': '%u rabbitmq', 'match': '~(?:.*bin/rabbitmq-server)', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites rabbitmq', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
{'id': 'b0d6dc83-fd0e-4382-921b-94415b353eaf', 'value': {'descr': '%u real-time helper', 'match': '~python3 /omd/sites/[^/]+/bin/cmk --real-time-checks', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites real-time helper', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
{'id': '33e44415-a74c-4146-a6c7-65473eff71ca', 'value': {'descr': '%u redis-server', 'match': '~/omd/sites/[^/]+/bin/redis-server', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites redis-server', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
{'id': '0bd2b6cc-bc5c-4244-9658-928870f68f35', 'value': {'descr': '%u rrd helper', 'match': '~python3 /omd/sites/[^/]+/bin/cmk( -)?-create-rrd', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites rrd helper', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
{'id': 'bf1601b9-69bb-4f1d-8384-e5e057069656', 'value': {'descr': '%u rrdcached', 'match': '~/omd/sites/[^/]+/bin/rrdcached', 'user': False, 'default_params': {'cpu_rescale_max': True}}, 'condition': {'host_label_groups': [('and', [('and', 'cmk/check_mk_server:yes'), ('and', '')])]}, 'options': {'disabled': False, 'description': 'Shipped rule to monitor sites rrdcached', 'comment': 'This rule is shipped with Checkmk. It is added to give insights on the resource usage of Checkmk servers. If you do not want these services, consider disabling this rule, rather than deleting it. If you delete all of these rules, they might come back after an update.\n'}},
] + inventory_processes_rules


globals().setdefault('management_bulkwalk_hosts', [])

management_bulkwalk_hosts = [
{'id': '59d84cde-ee3a-4f8d-8bec-fce35a2b0d15', 'value': True, 'condition': {}, 'options': {'description': 'All management boards use SNMPv2 and bulk walk'}},
] + management_bulkwalk_hosts


globals().setdefault('only_hosts', [])

if only_hosts is None:
    only_hosts = []

only_hosts = [
{'id': '10843c55-11ea-4eb2-bfbc-bce65cd2ae22', 'value': True, 'condition': {'host_tags': {'criticality': {'\$ne': 'offline'}}}, 'options': {'description': 'Do not monitor hosts with the tag "offline"'}},
] + only_hosts


globals().setdefault('periodic_discovery', [])

periodic_discovery = [
{'id': '95a56ffc-f17e-44e7-a162-be656f19bedf', 'value': {'severity_unmonitored': 1, 'severity_changed_service_labels': 0, 'severity_changed_service_params': 0, 'severity_vanished': 0, 'severity_new_host_label': 1, 'check_interval': 120.0}, 'condition': {}, 'options': {'description': 'Perform every two hours a service discovery'}},
] + periodic_discovery


globals().setdefault('ping_levels', [])

ping_levels = [
{'id': '0365b634-30bf-40a3-8516-08e86051508e', 'value': {'loss': (80.0, 100.0), 'packets': 6, 'timeout': 20, 'rta': (1500.0, 3000.0)}, 'condition': {'host_tags': {'networking': 'wan'}}, 'options': {'description': 'Allow longer round trip times when pinging WAN hosts'}},
] + ping_levels

EOF

agent_secret="$(gen_secret)"

# Agent registration user (initially admin; tighten later)
ensure_htpasswd_user "${AGENT_USER}" "${agent_secret}"
ensure_automation_secret_file "${AGENT_USER}" "${agent_secret}"

# Reload config / web
cmk -R

cat << EOF > ~/.credentials
AGENT_USER=${AGENT_USER}
AGENT_SECRET=${agent_secret}
EOF

install -d -o $(whoami) -g $(whoami) -m 0755 ${OMD_ROOT}/local/lib/nagios/plugins
ln -sf /usr/share/cmk-push-server/check_hostfile_freshness ${OMD_ROOT}/local/lib/nagios/plugins