# platform = multi_platform_ubuntu

ssh_approved_macs='(bash-populate ssh_approved_macs)'


main_config="/etc/ssh/ssh_config"
include_directory="/etc/ssh/ssh_config.d"

sed -i '/^\s*MACs.*/d' "$main_config" "$include_directory"/*.conf || true

if ! grep -qE '^[Hh]ost\s+\*$' /etc/ssh/ssh_config.d/00-mac-list.conf; then
  echo 'Host *' >> /etc/ssh/ssh_config.d/00-mac-list.conf
fi

if [ -e "/etc/ssh/ssh_config.d/00-mac-list.conf" ] ; then
    
    LC_ALL=C sed -i "/^\s*MACs\s\+/d" "/etc/ssh/ssh_config.d/00-mac-list.conf"
else
    touch "/etc/ssh/ssh_config.d/00-mac-list.conf"
fi
# make sure file has newline at the end
sed -i -e '$a\' "/etc/ssh/ssh_config.d/00-mac-list.conf"

cp "/etc/ssh/ssh_config.d/00-mac-list.conf" "/etc/ssh/ssh_config.d/00-mac-list.conf.bak"
# Insert after the line matching the regex '^Host\s+\*$'
line_number="$(LC_ALL=C grep -n "^Host\s+\*$" "/etc/ssh/ssh_config.d/00-mac-list.conf.bak" | LC_ALL=C sed 's/:.*//g')"
if [ -z "$line_number" ]; then
    # There was no match of '^Host\s+\*$', insert at
    # the end of the file.
    printf '%s\n' "MACs $ssh_approved_macs" >> "/etc/ssh/ssh_config.d/00-mac-list.conf"
else
    head -n "$(( line_number ))" "/etc/ssh/ssh_config.d/00-mac-list.conf.bak" > "/etc/ssh/ssh_config.d/00-mac-list.conf"
    printf '%s\n' "MACs $ssh_approved_macs" >> "/etc/ssh/ssh_config.d/00-mac-list.conf"
    tail -n "+$(( line_number + 1 ))" "/etc/ssh/ssh_config.d/00-mac-list.conf.bak" >> "/etc/ssh/ssh_config.d/00-mac-list.conf"
fi
# Clean up after ourselves.
rm "/etc/ssh/ssh_config.d/00-mac-list.conf.bak"