#!/bin/bash

readonly DB_PATH="/var/lib/knot-resolver/leases.db"
readonly DB_USER="knot-resolver"

readonly DHCPD_CONF="/var/ipfire/dhcp/dhcpd.conf"
readonly DHCPD_CONF_LOCAL="/var/ipfire/dhcp/dhcpd.conf.local"
readonly DHCPD_LEASES="/var/state/dhcp/dhcpd.leases"

# dhcpd runs as root, but the resolver opens the database as an
# unprivileged user and needs to be able to access all files of SQLite
fix_permissions() {
	chown "${DB_USER}:${DB_USER}" \
		"${DB_PATH}" "${DB_PATH}-wal" "${DB_PATH}-shm" 2>/dev/null

	return 0
}

# Prints all addresses that are currently in use, either because they have
# an active lease or because they are assigned statically
active_addresses() {
	local now="$(date -u "+%Y/%m/%d %H:%M:%S")"

	# Dynamic leases (the last entry for an address wins)
	if [ -r "${DHCPD_LEASES}" ]; then
		awk -v "now=${now}" '
			$1 == "lease" { address = $2; active = 0; ends = "" }
			$1 == "binding" && $2 == "state" { active = ($3 == "active;") }
			$1 == "ends" {
				ends = ($2 == "never;") ? "never" : $3 " " $4
				sub(/;$/, "", ends)
			}
			$1 == "}" && address != "" {
				state[address] = active && (ends == "never" || ends > now)
				address = ""
			}
			END {
				for (address in state)
					if (state[address])
						print address
			}
		' "${DHCPD_LEASES}"
	fi

	# Static leases
	sed -n -e 's/^[[:space:]]*fixed-address[[:space:]]\+\([0-9.]\+\);.*$/\1/p' \
		"${DHCPD_CONF}" "${DHCPD_CONF_LOCAL}" 2>/dev/null
}

main() {
	# Create the database if it does not exist
	if [ ! -f "${DB_PATH}" ]; then
		if ! sqlite3 "${DB_PATH}" >/dev/null \
				</usr/lib/knot-resolver/leases.schema; then
			echo "${0}: Failed to create database" >&2
			return 1
		fi

		fix_permissions
	fi

	local action="${1}"
	shift

	case "${action}" in
		commit)
			local address
			local hostname
			local domainname

			while [ $# -gt 0 ]; do
				case "${1}" in
					ADDRESS=*)
						address="${1#*=}"
						;;
					HOSTNAME=*)
						hostname="${1#*=}"
						;;
					DOMAINNAME=*)
						domainname="${1#*=}"
						;;
					*)
						# Ignore any unknown arguments
						;;
				esac
				shift
			done

			# Check if we have enough data
			if [ -z "${address}" ]; then
				echo "${0}: Missing ADDRESS=" >&2
				return 2
			elif [ -z "${hostname}" ]; then
				echo "${0}: Missing HOSTNAME=" >&2
				return 2
			elif [ -z "${domainname}" ]; then
				echo "${0}: Missing DOMAINNAME=" >&2
				return 2

			# Validate the address
			elif ! [[ ${address} =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]]; then
				echo "${0}: Invalid address" >&2
				return 2

			# Validate the domain name
			elif ! [[ ${domainname} =~ ^[A-Za-z0-9_.-]+$ ]]; then
				echo "${0}: Invalid domain name" >&2
				return 2

			# Validate the hostname
			elif ! [[ ${hostname} =~ ^[A-Za-z0-9_-]{1,63}$ ]]; then
				echo "${0}: Invalid hostname" >&2
				return 2
			fi

			# Join the hostname together
			hostname="${hostname}.${domainname}."

			# Make the hostname lowercase
			hostname="${hostname,,}"

			# If the hostname is already in use by another address (e.g.
			# because the client has moved), the old entry is replaced.
			if ! sqlite3 "${DB_PATH}" <<-EOF
				-- Set parameters
				.parameter set :address '${address}'
				.parameter set :hostname '${hostname}'

				-- Run statement
				INSERT OR REPLACE INTO
					leases
				(
					address,
					hostname
				)
				VALUES
				(
					:address,
					:hostname
				);
			EOF
			then
				echo "${0}: Failed to store the lease" >&2
				return 1
			fi
			;;

		release|expiry)
			local address

			while [ $# -gt 0 ]; do
				case "${1}" in
					ADDRESS=*)
						address="${1#*=}"
						;;
					*)
						# Ignore any unknown arguments
						;;
				esac
				shift
			done

			# Check if we have enough data
			if [ -z "${address}" ]; then
				echo "${0}: Missing ADDRESS=" >&2
				return 2
			fi

			if ! sqlite3 "${DB_PATH}" <<-EOF
				-- Set parameters
				.parameter set :address '${address}'

				-- Run statement
				DELETE FROM
					leases
				WHERE
					address = :address;
			EOF
			then
				echo "${0}: Failed to remove the lease" >&2
				return 1
			fi
			;;

		# Removes all entries for addresses which are no longer in use. This
		# is necessary because dhcpd does not run any "on expiry" events for
		# leases that have expired while it was not running.
		cleanup)
			local address
			local statements=""

			while read -r address; do
				[[ ${address} =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]] || continue

				statements+="INSERT OR IGNORE INTO keep(address) VALUES('${address}');"$'\n'
			done < <(active_addresses)

			if ! sqlite3 "${DB_PATH}" <<-EOF
				CREATE TEMP TABLE keep(address TEXT PRIMARY KEY);
				${statements}
				DELETE FROM
					leases
				WHERE
					address NOT IN (SELECT address FROM keep);
			EOF
			then
				echo "${0}: Failed to clean up the database" >&2
				return 1
			fi
			;;

		*)
			echo "${0}: Unknown action: ${action}" >&2
			return 2
			;;
	esac

	fix_permissions

	return 0
}

main "$@" || exit $?
