#!/usr/bin/env bash
# Copyright © SixtyFPS GmbH <info@slint.dev>
# SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0

#MISE description="Run trailing WS fix on all files"
# Touches every text file, so don't run concurrently with the other fixers
#MISE wait_for=["fix:cpp:format", "fix:legal:copyright", "fix:pnpm:dedupe", "fix:pnpm:lock", "fix:python:format", "fix:rust:format:all", "fix:toml:format", "fix:ts:biome", "fix:ts:format"]

# cSpell: ignore OSTYPE INPLACE dedupe

set -e

if [[ "$OSTYPE" == "darwin"* ]]; then
    SED_INPLACE="sed -i ''"
else
    SED_INPLACE="sed -i"
fi

# crlf-* test files must keep their CRLF line terminators, which sed would
# strip as trailing whitespace.
if git rev-parse --git-dir >/dev/null 2>&1 ; then
    git grep -I -l -O"$SED_INPLACE \"s/[[:space:]]*$//\"" -e '' -- ':!*.patch' ':!*crlf-*'
else
    while IFS= read -r -d '' -u 9
    do
        if [[ "$REPLY" == *crlf-* ]]
        then
            continue
        fi
        if [[ "$(file -bs --mime-type -- "$REPLY")" = text/* ]]
        then
            $SED_INPLACE "s/[[:space:]]*$//" -- "$REPLY"
        fi
    done 9< <(fd -0)
fi
