#!/bin/sh

runKtlint () {
    # Following code was generated automatically by running ./gradlew addKtlintFormatGitPreCommitHook
    # for reference, see https://github.com/JLLeitschuh/ktlint-gradle#additional-helper-tasks
    # and for the implementation, https://github.com/JLLeitschuh/ktlint-gradle/blob/master/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/GitHook.kt
    # The only change made are:
    # * replacing "exit" for "return", as this is running inside a function
    # * aborting with stderr guidance if restoring unstaged changes fails
    # * renaming `diff` variable to `diff_path`.
    # * changing the path of the diff file (to ensure in case of failure that we don't overwrite the file)
    # * storing the diff under `git rev-parse --git-dir` so worktrees work; abort if stash fails
    # * never deleting the recovery patch after a failed stash/restore (see #17593)
    ######## KTLINT-GRADLE HOOK START ########

    CHANGED_FILES="$(git --no-pager diff --name-status --no-color --cached | awk '$1 != "D" && $NF ~ /\.kts?$/ { print $NF }')"

    if [ -z "$CHANGED_FILES" ]; then
        echo "No Kotlin staged files."
        return 0
    fi;

    echo "Running ktlint over these files:"
    echo "$CHANGED_FILES"

    # Snapshot unstaged work before ktlint mutates the tree. Keep that patch on any
    # stash/restore failure: #17593 lost hours of in-flight edits when an earlier
    # hook version discarded the only recovery copy after a partial apply.
    git_dir=$(git rev-parse --git-dir)
    date=$(date +%y%m%d_%H%M%S)
    diff_path="$git_dir/unstaged-ktlint-git-hook-$date.diff"
    if ! git diff --color=never > "$diff_path"; then
        echo "Failed to save unstaged changes before ktlint." >&2
        echo "Commit aborted. Any partial snapshot is kept at: $diff_path" >&2
        return 1
    fi
    if [ -s "$diff_path" ]; then
        if ! git apply -R "$diff_path"; then
            # Intentionally keep $diff_path: git apply -R can delete files before
            # failing (e.g. unwritable paths), and removing the patch then destroys
            # the only recovery copy — the #17593 failure mode.
            echo "Failed to stash unstaged changes before ktlint." >&2
            echo "Commit aborted. Your unstaged edits are still saved in: $diff_path" >&2
            echo "Reapply with: git apply --ignore-whitespace \"$diff_path\"" >&2
            return 1
        fi
    fi

    ./gradlew --quiet ktlintFormat -PinternalKtlintGitFilter="$CHANGED_FILES"
    gradle_command_exit_code=$?

    echo "Completed ktlint run."

    echo "$CHANGED_FILES" | while read -r file; do
        if [ -f $file ]; then
            git add $file
        fi
    done


    if [ -s "$diff_path" ]; then
        if ! git apply --ignore-whitespace "$diff_path"; then
            echo "git apply failed when restoring unstaged changes." >&2
            echo "Commit aborted. Ktlint-formatted files remain staged (see: git diff --cached)." >&2
            echo "Your unstaged edits are saved in: $diff_path" >&2
            echo "Reapply with: git apply --ignore-whitespace \"$diff_path\"" >&2
            return 1
        fi
        rm -f "$diff_path"
    else
        rm -f "$diff_path"
    fi
    unset diff_path git_dir

    echo "Completed ktlint hook."
    return $gradle_command_exit_code
    ######## KTLINT-GRADLE HOOK END ########
}

runPrettier () {
    # check if npx is installed, else skip runPrettier
    if ! command -v npx &> /dev/null
    then
        echo "npx could not be found. Hence, skipping pre-commit Prettier run."
        return 0
    fi

    CHANGED_JS_FILES="$(git --no-pager diff --name-status --no-color --cached | awk '$1 != "D" && $2 ~ /\.js/ { print $2 }')"
        if [ -z "$CHANGED_JS_FILES" ]; then
            echo "No Javascript staged files. Hence, skipping pre-commit Prettier run."
            return 0
        fi;

    # Prettify changed files
    echo "$CHANGED_JS_FILES" | xargs npx prettier --ignore-unknown --write

    echo "Completed npx prettier run."
    echo "$CHANGED_JS_FILES" | while read -r file; do
        if [ -f "$file" ]; then
            git add "$file"
        fi
    done
}

runKtlint
ktlint_exit_code=$?
if [ $ktlint_exit_code -ne 0 ]; then
    echo "ktlint failed"
    exit $ktlint_exit_code
fi
runPrettier || :; # || to avoid cancelling the commit if there is an error with Prettier
prettier_exit_code=$?
if [ $prettier_exit_code -ne 0 ]; then
    exit $prettier_exit_code
fi;
echo "Completed the pre-commit hook."
