#!/usr/bin/env bash
# Copyright (c) The mldsa-native project authors
# SPDX-License-Identifier: Apache-2.0 OR ISC OR MIT

set -o errexit
set -o errtrace
set -o nounset
set -o pipefail

# consts
ROOT="$(realpath "$(dirname "$0")"/../)"

# Standard color definitions
GREEN="\033[32m"
RED="\033[31m"
BLUE="\033[94m"
BOLD="\033[1m"
NORMAL="\033[0m"

# utility
info()
{
  printf "%b %b\n" "${GREEN}info" "${NORMAL}${*}"
}

error()
{
  printf "%b %b\n" "${RED}error" "${NORMAL}${*}"
}

info "Formatting nix files"
if ! command -v nixpkgs-fmt 2>&1 >/dev/null; then
  error "nixpkgs-fmt not found. Are you running in a nix shell? See CONTRIBUTING.md."
  exit 1
fi

nixpkgs-fmt "$ROOT"

info "Formatting shell scripts"
if ! command -v shfmt 2>&1 >/dev/null; then
  error "shfmt not found. Are you running in a nix shell? See CONTRIBUTING.md."
  exit 1
fi
shfmt -s -w -l -i 2 -ci -fn $(shfmt -f $(git grep -l '' :/))

info "Formatting python scripts"
if ! command -v black 2>&1 >/dev/null; then
  error "black not found. Are you running in a nix shell? See CONTRIBUTING.md."
  exit 1
fi
black --include "(scripts/tests|scripts/simpasm|scripts/cfify|scripts/autogen|scripts/check-namespace|\.py$)" "$ROOT"

info "Formatting c files"
if ! command -v clang-format 2>&1 >/dev/null; then
  error "clang-format not found. Are you running in a nix shell? See CONTRIBUTING.md."
  exit 1
fi

nproc=$(getconf _NPROCESSORS_ONLN || echo 1)

git ls-files -- ":/*.c" ":/*.h" | xargs -P $nproc -I {} sh -c '
  # Ignore symlinks
  if [[ ! -L {} ]]; then
    clang-format -i {}
  fi'

info "Checking for eol"
check-eol()
{
  git ls-files -- ":/" ":/!:*.png" | xargs -P $nproc -I {} sh -c '
    # Ignore symlinks
    if [[ ! -L {} && $(tail -c1 "{}" | wc -l) == 0 ]]; then
      echo "" >>"{}"
      echo "{}"
    fi'
}
check-eol
