[Tex/LaTex] Remove headsepline if no text is displayed on the header

header-footerscrlayer-scrpage

I'm new here and I got a problem I can't solve myself despite Google and Co.

By far I created a header which consist of the current chapter name on the left side of a twoside document and the section name on the right page with a header separation line.

The code below show the used KomaOptions for the \usepackage{scrlayer-scrpage}

\KOMAoptions{automark
    headsepline=true,   % header line
    footsepline=false,          % footer line
    cleardoublepage=plain,  % set empty pages to style 'plain'
    plainheadsepline=false, % activate header line for plain pages
    plainfootsepline=false} % activate footer line for plain pages


\pagestyle{scrheadings}
\clearscrheadfoot

\lehead{\headmark{}}
\rohead{\headmark{}}
\ofoot*{\pagemark}

However, how to get rid of the head separation line if no section name on the left page of the document isn't printed?
The following pictures shall illustrate the issue.

The first one is fine, as it contains a section name at least.

Perfect

The second picture, prints the head separation line. How to remove it?

Not perfect

Here the MWE

\documentclass[twoside]{scrbook}

\usepackage{lipsum}
\usepackage[automark]{scrlayer-scrpage} % Koma header and footer package

\KOMAoptions{headsepline=true,  % header line
    footsepline=false,          % footer line
    cleardoublepage=plain,  % set empty pages to style 'plain'
    plainheadsepline=false, % activate header line for plain pages
    plainfootsepline=false} % activate footer line for plain pages


\pagestyle{scrheadings}
\clearscrheadfoot

\lehead{\headmark{}}
\rohead{\headmark{}}
\ofoot*{\pagemark}


\begin{document}
\chapter{Test}
\lipsum
\lipsum
\chapter{Anhang}
\lipsum
\section{Infos}
\lipsum
\end{document}

Best Answer

The following checks whether \headmark has the width of 0pt, and if so, changes the color of the headsepline to white:

\documentclass[twoside]{scrbook}

\usepackage[automark]{scrlayer-scrpage}
\usepackage{xcolor}

\KOMAoptions{%
    headsepline=true,   % header line
    footsepline=false,          % footer line
    cleardoublepage=plain,  % set empty pages to style 'plain'
    plainheadsepline=false, % activate header line for plain pages
    plainfootsepline=false} % activate footer line for plain pages


\pagestyle{scrheadings}
\clearscrheadfoot

\newcommand*{\specialheadmark}{%
    \setbox0\hbox{\headmark}%
    \ifdim\wd0=0pt\relax%
        \global\setkomafont{headsepline}{\color{white}}%
    \else%
        \global\setkomafont{headsepline}{\color{black}}%
    \fi%
    \unhbox0%
}

\lehead{\specialheadmark}
\rohead{\specialheadmark}
\ofoot*{\pagemark}

\usepackage{blindtext}


\begin{document}
\blinddocument
\chapter{Foo}
\clearpage
\blindtext
\clearpage
\blindtext
\clearpage
\blindtext
\end{document}

Pages 6 and 7:

enter image description here