#!/bin/sh

set -e

. /usr/share/openstack-pkg-tools/pkgos_func

supply_baremetal_configure_puppetserver () {
	pkgos_add_section /etc/puppet/puppet.conf main
	pkgos_add_section /etc/puppet/puppet.conf master
	pkgos_add_section /etc/puppet/puppet.conf agent

	pkgos_add_directive /etc/puppet/puppet.conf main server= "# Puppetserver address" $(hostname --fqdn)
	pkgos_add_directive /etc/puppet/puppet.conf master node_terminus= "# Tell what type of ENC" exec
	pkgos_add_directive /etc/puppet/puppet.conf master external_nodes= "# Path to ENC" /usr/bin/supply-enc-baremetal
	pkgos_add_directive /etc/puppet/puppet.conf master hiera_config= "# Path to standard hiera config" /etc/puppet/hiera.yaml
	pkgos_add_directive /etc/puppet/puppet.conf agent fact_value_length_soft_limit= "# This avoid unecessary warnings" 65536
}

supply_baremetal_configure_hiera () {
	if ! [ -e /etc/puppet/hiera.yaml ] ; then
		echo "---
:backends:
  - yaml

# Hiera 5 Global configuration file

version: 3

# defaults:
#   data_hash: yaml_data
hierarchy:
  - common
  - \"nodes/%{::clientcert}\"
  - \"role/%{::supply_role}\"
  - \"osfamily/%{::osfamily}\"

:yaml:
  :datadir: /etc/puppet/code/hiera
" >/etc/puppet/hiera.yaml
	fi

	mkdir -p /etc/puppet/code/hiera/nodes
	mkdir -p /etc/puppet/code/hiera/role
	mkdir -p /etc/puppet/code/hiera/osfamily
	if ! [ -e /etc/puppet/code/hiera/common.yaml ] ; then
		echo "---
classes:
  - files

# Sudoers files for Support L3
files:
  '/etc/sudoers.d/l3-common':
    ensure: 'file'
    owner: 'root'
    group: 'root'
    mode: '0644'
    content: |-
      l3 ALL = (root) NOPASSWD: /usr/sbin/conntrack *
      l3 ALL = (root) NOPASSWD: /usr/sbin/dmidecode *
      l3 ALL = (root) NOPASSWD: /usr/bin/dmesg *
      l3 ALL = (root) NOPASSWD: /usr/bin/ip *
      l3 ALL = (root) NOPASSWD: /usr/bin/ipmitool *
      l3 ALL = (root) NOPASSWD: /usr/sbin/iptables*
      l3 ALL = (root) NOPASSWD: /usr/sbin/ip6tables*
      l3 ALL = (root) NOPASSWD: /usr/sbin/logrotate *
      l3 ALL = (root) NOPASSWD: /usr/sbin/megacli *
      l3 ALL = (root) NOPASSWD: /usr/bin/puppet *
      l3 ALL = (root) NOPASSWD: /usr/sbin/tcpdump *
      l3 ALL = (root) NOPASSWD: /usr/bin/oci-hdd-maint *
      l3 ALL = (root) NOPASSWD: /bin/systemctl daemon-reload
      l3 ALL = (root) NOPASSWD: /usr/sbin/reboot
      # newline mandatory
" >/etc/puppet/code/hiera/common.yaml
	fi
}

supply_baremetal_configure_supply () {
	echo "---> Starting puppetserver"
	systemctl enable puppetserver
	systemctl start puppetserver
}

supply_baremetal_configure_puppetserver
supply_baremetal_configure_hiera
supply_baremetal_configure_supply

#puppet agent --test --detailed-exitcodes --summarize $@
