Changed formatting, added escaping and executable

to prevent here document variable expansion, ‘$’ signs in front of
variable names (in the script to be written to a file) have to be
escaped…
also, to preserve formatting, indentation has to be done with tabs
(just for the here document)
added code to set the written scripts executable flag