# SPDX-License-Identifier: GPL-2.0-only
########################################################################
#
# (C) Copyright 2020, 2021, Alejandro Colomar
# These functions are free software; you can redistribute them and/or
# modify them under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2.
#
# These functions are distributed in the hope that they will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details
# (http://www.gnu.org/licenses/gpl-2.0.html).
#
########################################################################

########################################################################
#	Exit status

EX_OK=0;
EX_USAGE=64;

########################################################################
#	C

#  sed_rm_ccomments()  removes C comments.
# It can't handle multiple comments in a single line correctly,
# nor mixed or embedded //... and /*...*/ comments.
# Use as a filter (see man_lsfunc() in this file).

function sed_rm_ccomments()
{
	sed 's%/\*.*\*/%%' \
	|sed -E '\%/\*%,\%\*/%{\%(\*/|/\*)%!d; s%/\*.*%%; s%.*\*/%%;}' \
	|sed 's%//.*%%';
}

########################################################################
#	Linux kernel

#  grep_syscall()  finds the prototype of a syscall in the kernel sources,
# printing the filename, line number, and the prototype.
# It should be run from the root of the linux kernel source tree.
# Usage example:  .../linux$ grep_syscall openat2;

function grep_syscall()
{
	if (($# != 1)); then
		>&2 echo "Usage: ${FUNCNAME[0]} <syscall>";
		return ${EX_USAGE};
	fi

	find * -type f \
	|grep '\.c$' \
	|sort \
	|xargs pcregrep -Mn "(?s)^\w*SYSCALL_DEFINE.\(${1},.*?\)" \
	|sed -E 's/^[^:]+:[0-9]+:/&\n/';

	find * -type f \
	|grep '\.[ch]$' \
	|sort \
	|xargs pcregrep -Mn "(?s)^asmlinkage\s+[\w\s]+\**sys_${1}\s*\(.*?\)" \
	|sed -E 's/^[^:]+:[0-9]+:/&\n/';
}

#  grep_syscall_def()  finds the definition of a syscall in the kernel sources,
# printing the filename, line number, and the function definition.
# It should be run from the root of the linux kernel source tree.
# Usage example:  .../linux$ grep_syscall_def openat2;

function grep_syscall_def()
{
	if (($# != 1)); then
		>&2 echo "Usage: ${FUNCNAME[0]} <syscall>";
		return ${EX_USAGE};
	fi

	find * -type f \
	|grep '\.c$' \
	|sort \
	|xargs pcregrep -Mn "(?s)^\w*SYSCALL_DEFINE.\(${1},.*?^}" \
	|sed -E 's/^[^:]+:[0-9]+:/&\n/';
}

########################################################################
#	Linux man-pages

#  man_section()  prints specific manual page sections (DESCRIPTION, SYNOPSIS,
# ...) of all manual pages in a directory (or in a single manual page file).
# Usage example:  .../man-pages$ man_section man2 SYNOPSIS 'CONFORMING TO';

function man_section()
{
	if (($# < 2)); then
		>&2 echo "Usage: ${FUNCNAME[0]} <dir> <section>...";
		return ${EX_USAGE};
	fi

	local page="$1";
	shift;
	local sect="$@";

	find "${page}" -type f \
	|xargs wc -l \
	|grep -v -e '\b1 ' -e '\btotal\b' \
	|awk '{ print $2 }' \
	|sort \
	|while read -r manpage; do
		cat \
		<(<${manpage} sed -n '/^\.TH/,/^\.SH/{/^\.SH/!p}') \
		<(for s in ${sect}; do
			<${manpage} \
			sed -n \
				-e "/^\.SH ${s}/p" \
				-e "/^\.SH ${s}/,/^\.SH/{/^\.SH/!p}"; \
		  done;) \
		|man -P cat -l - 2>/dev/null;
	done;
}

#  man_lsfunc()  prints the name of all C functions declared in the SYNOPSIS
# of all manual pages in a directory (or in a single manual page file).
# Each name is printed in a separate line
# Usage example:  .../man-pages$ man_lsfunc man2;

function man_lsfunc()
{
	if (($# < 1)); then
		>&2 echo "Usage: ${FUNCNAME[0]} <manpage|manNdir>...";
		return ${EX_USAGE};
	fi

	for arg in "$@"; do
		man_section "${arg}" 'SYNOPSIS';
	done \
	|sed_rm_ccomments \
	|pcregrep -Mn '(?s)^ [\w ]+ \**\w+\([\w\s(,)[\]*]+?(...)?\s*\); *$' \
	|grep '^[0-9]' \
	|sed    's/syscall(SYS_\(\w*\),/\1(/' \
	|sed -E 's/^[^(]+ \**(\w+)\(.*/\1/' \
	|uniq;
}

#  man_lsvar()  prints the name of all C variables declared in the SYNOPSIS
# of all manual pages in a directory (or in a single manual page file).
# Each name is printed in a separate line
# Usage example:  .../man-pages$ man_lsvar man3;

function man_lsvar()
{
	if (($# < 1)); then
		>&2 echo "Usage: ${FUNCNAME[0]} <manpage|manNdir>...";
		return ${EX_USAGE};
	fi

	for arg in "$@"; do
		man_section "${arg}" 'SYNOPSIS';
	done \
	|sed_rm_ccomments \
	|pcregrep -Mv '(?s)^ [\w ]+ \**\w+\([\w\s(,)[\]*]+?(...)?\s*\); *$' \
	|pcregrep -Mn \
	  -e '(?s)^ +extern [\w ]+ \**\(\*+[\w ]+\)\([\w\s(,)[\]*]+?\s*\); *$' \
	  -e '^ +extern [\w ]+ \**[\w ]+; *$' \
	|grep '^[0-9]' \
	|grep -v 'typedef' \
	|sed -E 's/^[0-9]+: +extern [^(]+ \**\(\*+(\w* )?(\w+)\)\(.*/\2/' \
	|sed    's/^[0-9]\+: \+extern .* \**\(\w\+\); */\1/' \
	|uniq;
}

#  pdfman()  renders a manual page in PDF
# Usage example:  .../man-pages$ pdfman man2/membarrier.2;

function pdfman()
{
	if (($# != 1)); then
		>&2 echo "Usage: ${FUNCNAME[0]} <man-page.n>";
		return ${EX_USAGE};
	fi;

	local tmp="$(mktemp -t "${1##*/}.XXXXXX")";

	<${1} \
	man -Tps -l - \
	|ps2pdf - - \
	>${tmp};
	xdg-open ${tmp};
}

#  man_gitstaged  prints a list of all files with changes staged for commit
# (basename only if the files are within <man?/>), separated by ", ".
# Usage example:  .../man-pages$ git commit -m "$(man_gitstaged): msg";

function man_gitstaged()
{
	git diff --staged --name-only					\
	|sed "s/$/, /"							\
	|sed "s%man[1-9]/%%"						\
	|tr -d '\n'							\
	|sed "s/, $//"
}

########################################################################
#	Glibc

#  grep_glibc_prototype()  finds a function prototype in the glibc sources,
# printing the filename, line number, and the prototype.
# It should be run from the root of the glibc source tree.
# Usage example:  .../glibc$ grep_glibc_prototype printf;

function grep_glibc_prototype()
{
	if (($# != 1)); then
		>&2 echo "Usage: ${FUNCNAME[0]} <func>";
		return ${EX_USAGE};
	fi

	find * -type f \
	|grep '\.h$' \
	|sort \
	|xargs pcregrep -Mn \
	  "(?s)^[\w[][\w\s(,)[:\]]+\s+\**${1}\s*\([\w\s(,)[\]*]+?(...)?\)[\w\s(,)[:\]]*;" \
	|sed -E 's/^[^:]+:[0-9]+:/&\n/';
}
