#!/bin/zsh -Ndfgku
#
# Scripts/lint
# mas
#
# Copyright © 2025 mas-cli. All rights reserved.
#
# Reports style violations without making any modifications to the code.
#
# Please keep in sync with Scripts/format.
#

# shellcheck disable=SC1036,SC1056,SC1072
. "${0:A:h}/_setup_script"

print_notice '🚨 Linting' "${@}"

ensure_command_available actionlint git markdownlint-cli2 shellcheck swiftformat swiftlint yamllint || exit
[[ "$(/usr/bin/arch)" = arm64 && "${$(sw_vers -productVersion)%%.*}" -ge 15 ]]
integer -r can_use_periphery="$((! ?))"
# shellcheck disable=SC1073,SC1083
((can_use_periphery)) && { ensure_command_available periphery || exit }

zmodload zsh/zutil
zparseopts -D -A received_flag P

export -r MAS_DISTRIBUTION=lint

integer exit_status=0

printf -- $'--> 🕊​ SwiftFormat\n'
script -q /dev/null swiftformat --lint --markdown-files format-strict . |
 (grep -vxE '(?:\^D\x08{2})?Running SwiftFormat\.{3}\r|\(lint mode - no files will be changed\.\)\r|Reading (?:config|swift-version) file at .*|\x1b\[32mSwiftFormat completed in \d+(?:\.\d+)?s\.\x1b\[0m\r|0/\d+ files require formatting\.\r|Source input did not pass lint check\.\r' || true)
((exit_status |= ${?}))

printf -- $'--> 🦅 SwiftLint\n'
swiftlint --strict --quiet --reporter relative-path
((exit_status |= ${?}))

if ((can_use_periphery)) && ! [[ -v 'received_flag[-P]' ]]; then
	printf -- $'--> 🌀 Periphery\n'
	periphery scan --exclude-tests |
	 (grep -vxE '(?:\x1b\[0;1;32m|\^D\x08{2})\* (?:\x1b\[0;0m\x1b\[0;1m)?No unused code detected\.(?:\x1b\[0;0m)?\r?' || true)
	((exit_status |= ${?}))

	printf -- $'--> 🌀 Periphery Tests\n'
	periphery scan |
	 (grep -vxE '(?:\x1b\[0;1;32m|\^D\x08{2})\* (?:\x1b\[0;0m\x1b\[0;1m)?No unused code detected\.(?:\x1b\[0;0m)?\r?' || true)
	((exit_status |= ${?}))
fi

printf -- $'--> 〽️ Markdown\n'
markdownlint-cli2 -- ***/*.md(.)
((exit_status |= ${?}))

printf -- $'--> 📝 YAML\n'
yamllint -s .
((exit_status |= ${?}))

printf -- $'--> 🌳 Git\n'
git diff --check
((exit_status |= ${?}))

printf -- $'--> 💤 Zsh\n'
for script in Scripts/***/*(.); do
	/bin/zsh -n "${script}"
	((exit_status |= ${?}))
done

printf -- $'--> 🐙 ActionLint\n'
actionlint -shellcheck shellcheck
((exit_status |= ${?}))

printf -- $'--> 🐚 ShellCheck\n'
shellcheck -s bash -o all -e SC1009,SC1088,SC2296,SC2298,SC2299,SC2300,SC2301,SC2312 -a -P SCRIPTDIR Scripts/***/*(.)
((exit_status |= ${?}))

printf -- $'--> 🚷 Non-Executables\n'
readonly -a non_executables=(Scripts/***/*(N.^f+111))
if (("${#non_executables[@]}")); then
	printf $'%s\n' "${non_executables[@]}"
	((exit_status |= 1))
fi

exit "${exit_status}"
