class pantin::postgresql {
	# We choose ext4 because historically XFS has relied on the underlying
	# hardware to properly implement write barriers. Since we run in the
	# cloud, we can make no assumptions on how hardware/power is handled
	# and thus pick the safest option (ext4).
	exec { 'lvm-postgresql':
		command => 'lvcreate -L1G -y -n postgresql sys && mkfs.ext4 /dev/sys/postgresql',
		creates => '/dev/sys/postgresql',
	} ->
	file { '/var/lib/postgresql':
		mode => '0755',
		owner => 'root',
		group => 'root',
		ensure => directory,
	} ->
	mount { '/var/lib/postgresql':
		ensure => 'mounted',
		device => '/dev/sys/postgresql',
		fstype => 'ext4',
		options => 'defaults,noatime',
		remounts => true,
	} ->
	package { [ 'postgresql', 'pgtop' ]:
		ensure => present,
	} ->
	file { '/var/backups-staging/postgresql':
		mode => '0700',
		owner => 'postgres',
		group => 'postgres',
		ensure => directory,
	} ->
	file { '/etc/cron.d/pgdump':
		owner => 'root',
		group => 'root',
		mode => '0644',
		content => "10 1 * * * postgres /usr/bin/pg_dumpall | gzip -c > /var/backups-staging/postgresql/sql.gz\n",
	}

	file { '/etc/postgresql/17/main/postgresql.conf':
		mode => '0644',
		owner => 'postgres',
		group => 'postgres',
		content => template('pantin/etc/postgresql/17/main/postgresql.conf.erb')
	}

	define hba_user(
		$ensure = 'present',
		$username = $name,
		$type = 'local',
		$database = 'template1',
		$method = 'peer',
	) {
		augeas { "pg_hba-user-$username-$database":
			context => '/files/etc/postgresql/17/main/pg_hba.conf',
			changes => [
				"ins 0 after 1",
				"set 0/type $type",
				"set 0/database $database",
				"set 0/user $username",
				"set 0/method $method",
			],
			onlyif => "match *[type = '$type'][database = '$database'][user = '$username'][method = '$method'] size == 0",
			notify => Service['postgresql'],
		}
	}

	service { 'postgresql':
		ensure => 'running',
		enable => true,
		subscribe => [
			File['/etc/postgresql/17/main/postgresql.conf'],
		],
		require => Package['postgresql'],
	}
}
