#!/bin/bash
# @copyright 2021 Network RADIUS SAS (legal@networkradius.com)
# Author: Jorge Pereira <jorge@freeradius.org>
##

if [ -e "/etc/freeradius/3.0/mods-config/files/authorize" ]; then
	raddb="/etc/freeradius/3.0"
elif [ -e "/etc/freeradius/mods-config/files/authorize" ]; then
	raddb="/etc/freeradius"
elif [ -e "/etc/raddb/mods-config/files/authorize" ]; then
	raddb="/etc/raddb"
else
	echo "$0: ERROR: We did not find the /etc/freeradius/mods-config/files/authorize or /etc/freeradius/3.0/mods-config/files/authorize"
	exit 123
fi

radiusd="/usr/sbin/freeradius"

if [ -z "$CI_TEST_USER" ]; then
	echo "$0: ERROR: Missing the env CI_TEST_USER"
	exit 1
fi

if [ -z "$CI_TEST_PASS" ]; then
	echo "$0: ERROR: Missing the env CI_TEST_PASS"
	exit 1
fi

# Setup the basic user setting
cat > ${raddb}/mods-config/files/authorize <<EOF
# Generated by $0
$CI_TEST_USER     Cleartext-Password := "$CI_TEST_PASS"
		Reply-Message := "Hello, %{User-Name}"

EOF

cat > ${raddb}/sites-enabled/default <<EOF
# Generated by $0
server default {
	listen {
		type = auth
		ipv6addr = ::
		ipaddr = *
		port = 0
		limit {
			max_connections = 16
			lifetime = 0
			idle_timeout = 30
		}
	}

	listen {
		ipaddr = *
		ipv6addr = ::
		port = 0
		type = acct
		limit {

		}
	}

	listen {
		type = auth
		ipv6addr = ::	# any.  ::1 == localhost
		port = 0
		limit {
			max_connections = 16
			lifetime = 0
			idle_timeout = 30
		}
	}

	listen {
		ipv6addr = ::
		port = 0
		type = acct
		limit {

		}
	}

	authorize {
		files
		pap
	}

	authenticate {
		Auth-Type PAP {
			pap
		}
	}
}
EOF

# Override default clients.conf, requiring Message-Authenticator
cat > ${raddb}/clients.conf <<EOF
# Generated by $0

# clients.conf -- client configuration directives
client localhost {
	ipaddr = 127.0.0.1
	proto = *
	secret = testing123
	require_message_authenticator = yes
	limit {
		max_connections = 16
		lifetime = 0
		idle_timeout = 30
	}
}

# IPv6 Client
client localhost_ipv6 {
	ipv6addr = ::1
	proto = *
	secret = testing123
	require_message_authenticator = yes
	limit {
		max_connections = 16
		lifetime = 0
		idle_timeout = 30
	}
}
EOF

