# platform = multi_platform_ubuntu

ssh_approved_ciphers="aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes128-ctr"

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

sed -i '/^\s*[Cc]iphers.*/d' "$main_config" "$include_directory"/*.conf || true

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

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

cp "/etc/ssh/ssh_config.d/00-cipher-list.conf" "/etc/ssh/ssh_config.d/00-cipher-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-cipher-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' "Ciphers $ssh_approved_ciphers" >> "/etc/ssh/ssh_config.d/00-cipher-list.conf"
else
    head -n "$(( line_number ))" "/etc/ssh/ssh_config.d/00-cipher-list.conf.bak" > "/etc/ssh/ssh_config.d/00-cipher-list.conf"
    printf '%s\n' "Ciphers $ssh_approved_ciphers" >> "/etc/ssh/ssh_config.d/00-cipher-list.conf"
    tail -n "+$(( line_number + 1 ))" "/etc/ssh/ssh_config.d/00-cipher-list.conf.bak" >> "/etc/ssh/ssh_config.d/00-cipher-list.conf"
fi
# Clean up after ourselves.
rm "/etc/ssh/ssh_config.d/00-cipher-list.conf.bak"