#!/bin/bash

traefikSetupLoginCredentials()
{
	local protectionauth_file="$containers_dir/traefik/etc/dynamic/middlewears/protectionauth.yml"
    if [ -f "$protectionauth_file" ]; then
		# Refuse to write empty/placeholder credentials — htpasswd -Bbn "" ""
		# silently produces a hash that effectively allows blank-credential
		# logins, which would leave the dashboard unprotected.
		if [[ -z "$CFG_TRAEFIK_USER" || -z "$CFG_TRAEFIK_PASS" \
			|| "$CFG_TRAEFIK_PASS" == RANDOMIZEDPASSWORD* ]]; then
			isError "Traefik dashboard credentials are not set (CFG_TRAEFIK_USER / CFG_TRAEFIK_PASS). Skipping auth middleware write — refusing to leave dashboard unprotected."
			return 1
		fi

		# Setup BasicAuth credentials
		local login_credentials=$(htpasswd -Bbn "$CFG_TRAEFIK_USER" "$CFG_TRAEFIK_PASS")

        local result=$(runFileOp sed -i '/#protection credentials/d' "$protectionauth_file")
        checkSuccess "Delete the line containing protection credentials"
        local result=$(runFileOp sed -i "/users:/a\\          - '$login_credentials' #protection credentials" "$protectionauth_file")
        checkSuccess "Add the new line with new protection credentials"
	fi
}