#!/bin/bash

read -r -d '' new_license <<'EOF'
//
// SPDX-License-Identifier: Zlib
//
// This siHAL software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//    claim that you wrote the original software. If you use this software
//    in a product, an acknowledgment in the product documentation would be
//    appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//    misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
EOF

set -euo pipefail

source="./tmp/si32Hal"
destination="./si32Hal"

if [ -d "$destination" ]; then
    rm -r "$destination"
fi

cp -r "$source" "$destination"

# These have an incompatible license but we don't need them because we have
# modules/hal/cmsis.
rm -r "$destination/CPU"

# These have an incompatible license but we don't need them.
rm "$destination"/*/linker_*
rm "$destination"/*/startup_*

new_license_escaped=$(echo "$new_license" | sed -e 's/[\/&]/\\&/g' | perl -pe 's/\n/\\r\\n/')

replace_copyright() {
    local path="$1"

    perl -i -0p \
        -e '$s = s/(^\/\/[-]+\r\n)\/\/ Copyright \(c\) (201\d) by Silicon Laboratories.*?\r\n(?:\/\/.*?\r\n)*?(^\/\/[-]+\r\n)/\1\/\/ Copyright \2 (c) Silicon Laboratories Inc.\r\n'"$new_license_escaped"'\3/smg;' \
        -e 'END { die "No copyright header found" if $s != 1 }' \
        "$path"
}

export -f replace_copyright
export new_license_escaped
fd . si32Hal/ --type file -x bash -c 'replace_copyright "$0"'
