~q3cpma/misc-tools

ref: 0695c6188d0f70c89d8e1757f2463b2e3869a60a misc-tools/build_util.sh -rw-r--r-- 16.6 KiB
0695c618q3cpma htmldecode: move to root, use genhtab instead of lex 11 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
# Various utilities for other POSIX sh scripts
#
# Portability:
#     xargsnl: GNU, *BSD, MacOS, Illumos
#
# +----------+-----+---------+--------+--------------+---------+-------+---------+-------+-----+------+-------+
# | cmd/OS   | GNU | OpenBSD | NetBSD | DragonflyBSD | FreeBSD | MacOS | Illumos | HP-UX | AIX | IRIX | Tru64 |
# +----------+-----+---------+--------+--------------+---------+-------+---------+-------+-----+------+-------+
# | xargs -0 | o   | o       | o      | o            | o       | o     | o       |       |     |      |       |
# +----------+-----+---------+--------+--------------+---------+-------+---------+-------+-----+------+-------+
set -u


# Portable echo, without any option
pecho()
{
	printf '%s\n' "$*"
}

# Print all arguments prefixed by the program name to stderr and exits with
# status 1
die()
{
	pecho "$@" >&2
	exit 1
}

# Returns 0 if $1 matches $2 (as an ERE), 1 otherwise
match()
{
	pecho "$1" | grep -Eqx -- "$2"
}

# Die with an appropriate message if "test $1" returns false for any of the
# remaining argument paths or if one of these doesn't exists
requirefile()
{
	_testarg=$1
	shift
	for _i
	do
		[ ! -L "$_i" ] && [ ! -e "$_i" ] && die "$_i: file not found"
		if [ "$_testarg" != "-e" ] && [ ! "$_testarg" "$_i" ]
		then
			case "$_testarg" in
				-b)    die "$_i: not a block device";;
				-c)    die "$_i: not a character special file";;
				-d)    die "$_i: not a directory";;
				-f)    die "$_i: not a regular file";;
				-g)    die "$_i: not a setgid file";;
				-h|-L) die "$_i: not a symbolic link";;
				-p)    die "$_i: not a FIFO";;
				-r)    die "$_i: not a readable file";;
				-S)    die "$_i: not a socket";;
				-s)    die "$_i: not a non-empty file";;
				-u)    die "$_i: not a setuid file";;
				-w)    die "$_i: not a writeable file";;
				-x)    die "$_i: not a executable file";;
			esac
		fi
	done
}

checkbin()
{
	command -v "$1" >/dev/null
}

# For each argument, check for executable presence; use a,b,c... for alternatives
requirebin()
{
	for _i
	do
		if match "$_i" '.*|.*'
		then
			_i=$(pecho "$_i" | tr ',' ' ')
			_success=false
			for _j in $_i
			do
				if checkbin "$_j"
				then
					_success=true
				fi
			done
			if ! $_success
			then
				pecho "At least one executable amongst `$_i` required"
				return 1
			fi
		elif ! checkbin "$_i"
		then
			pecho "$_i: executable not found"
			return 1
		fi
	done
}

# Die with an appropriate message if one of the argument paths exists
forbidfile()
{
	for _i
	do
		if [ -L "$_i" ] || [ -e "$_i" ]
		then
			die "$_i: file already exists"
		fi
	done
}

# Output all arguments separated by '\n'. If there is no argument or the only
# argument is '-', output stdin instead
readargs()
{
	if [ $# -eq 0 ] || ([ $# -eq 1 ] && [ "$1" = "-" ])
	then
		cat
	else
		printf '%s\n' "$@"
	fi
}

# Quote all arguments
quote()
{
	pecho "$1" | sed "s#'#'\\\\''#g; s#^#'#; s#\$#'#"
}

# Double quote $1 $2 times (defaults to 1)
dquote()
{
	_cnt=${2:-1}
	_res=$1
	while [ $_cnt -ne 0 ]
	do
		_res=$(pecho "$_res" | sed 's#"#\\"#g; s#^#"#; s#$#"#')
		_cnt=$((_cnt - 1))
	done
	pecho "$_res"
}

# Escape all BRE metacharacters in $1
bre_escape()
{
	pecho "$1" | sed 's#[[^$*.\\-]#\\&#g'
}

# Escape all BRE metacharacters in $1
ere_escape()
{
	pecho "$1" | sed 's#[()|{}+?[^$*.\\-]#\\&#g'
}

# Escape all sed substitute metacharacters in $1
sed_repl_escape()
{
	pecho "$1" | sed 's#[\\&]#\\&#g'
}

# Escape all globbing metacharacters in $1
glob_escape()
{
    pecho "$1" | sed 's#[[*?]#\\&#g'
}

# List the absolute path of all files in $1 separated by \n. The remaining
# arguments are passed to find.
listfiles()
{
	_dir=$1
	shift
	_esc=$(glob_escape "$_dir")
	find -- "$_dir" \( ! -path "$_esc" -prune \) "$@"
}

# xargs -d'\n' for *BSD/GNU/Solaris
xargsnl()
{
	tr '\n' '\000' | xargs -0 "$@"
}

# Convert all arguments to lowercase
tolower()
{
	readargs "$@" | tr '[:upper:]' '[:lower:]'
}

# Portable head -n-val
headneg()
{
	! match "$1" '[[:digit:]]+' && return 1
	awk -varg=$1 '{if(NR > arg) print buf[NR % arg]; buf[NR % arg] = $0}'
}

# Format stdin so that __foo_bar__ is underlined and **foo*bar** is emboldened
text_format()
{
	if [ -t 1 ]
	then
		set +e
		_sgr0=$(tput sgr0)
		_bold=$(tput bold)
		_smul=$(tput smul)
		_rmul=$(tput rmul)
		set -e
	else
		_sgr0=
		_bold=
		_smul=
		_rmul=
	fi
	sed -E \
		-e ":a; s#([^_]|^)__(([^_]*(_[^_])*[^_]*)+)__([^_]|\$)#\1$_smul\2$_rmul\5#; ta" \
		-e ":b; s#([^*]|^)\*\*(([^\*]*(\*[^*])*[^*]*)+)\*\*([^*]|\$)#\1$_bold\2$_sgr0\5#; tb"
}

# Extract the extension of a filename (only works for the last extension,
# e.g. "foo.tar.gz" returns "gz")
file_ext()
{
	pecho "$1" | sed -n 's#.*[^/]\.\([^.]*\)$#\1#p'
}

# Print the mimetype of $1
mimetype()
{
	file --dereference --brief --mime-type -- "$1"
}

# Extract the basename of a filename (minus the extension)
file_base()
{
	_tmp=$(basename -- "$1")
	_base=${_tmp%.*}
	if [ ! "$_base" ]
	then
		pecho "$_tmp"
	else
		pecho "$_base"
	fi
}

# Read a password securely into variable $2 using $1 as a prompt
read_password()
{
	printf '%s ' "$1"
	stty -echo
	read -r "$2"
	stty echo
	pecho
}

# Takes argv ("$@") as argument and determines if the help option is called
is_help()
{
	[ $# -eq 1 ] && ([ "$1" = "-h" ] || [ "$1" = "--help" ])
}

# Print stdin lines as a pretty list: "line1, line2, ..."
list_join()
{
	_sep=${1:-, }
	sed ':a; N; $!ba; s#\n#'"$(sed_repl_escape "$_sep")"'#g'
}

# Execute $@ with sh then outputs the number of seconds it took
ptime()
{
	command time -p sh -c '{ "$@";} 2>&3 >/dev/null' dummy "$@" 3>&2 2>&1 | \
		sed -n 's#^real ##p'
}

# prints a random unsigned number of $1 bytes
rand()
{
	requirefile -c /dev/urandom
	od -An -N$1 -t u$1 /dev/urandom | tr -d '[:blank:]'
}

# IFS split $1 into the variables $2, $3, ...
read_split()
{
	_str=$1
	shift
	read -r "$@" <<-EOF
		$_str
EOF
}

# Something a bit like select. The selection is read on stdin and the result is
# printed to stdout
pselect()
{
	_in=$(cat)
	_len=$(pecho "$_in" | wc -l)
	while true
	do
		pecho "$_in" | awk '{printf "%d) %s\n", NR, $0}' >&2
		printf '\n#?' >&2
		read -r _choice </dev/tty
		if ! match "$_choice" '[0-9]+' || [ $_choice -gt $_len ]
		then
			printf '%s: invalid value\n' "$_choice" >&2
			continue
		fi
	    pecho "$_in" | sed -n "$_choice"'{p; q}'
		break
	done
}

# GNU parallel handling nested instances
parallel()
{
	if [ "${PARALLEL_PID:-}" ]
	then
		command env PARALLEL=$(pecho "$PARALLEL" | sed 's#--eta##g') \
			parallel -j1 "$@"
	else
		command parallel "$@"
	fi
}

# Like the usual tac(1), print lines in reverse
tac()
{
	awk '{line[NR] = $0} END {for (i = NR; i; --i) {print line[i]}}' "$@"
}

# Recursively delete empty directories
rmdir_recursive()
{
	for i
	do
		find -- "$i" -type d | awk -F/ '{print NF, $0}' | sort -k1 -n | rev | \
			cut -d' ' -f2- | xargsnl rmdir --
	done
}

# Simple portable seq without fancy options (use list_join to get -s)
seq()
{
	_incr=1
	_first=1
	case $# in
		1)  _last=$1;;
		2)
			_first=$1
			_last=$2
			;;
		3)
			_first=$1
			_incr=$2
			_last=$3
			;;
	esac
	while [ $_first -le $_last ]
	do
		pecho "$_first"
		_first=$((_first + _incr))
	done
}

# URL decode input or arguments
urldecode()
{
	readargs "$@" | sed 's#+# #g; s#%#\\x#g' | xargsnl printf '%b\n'
}

# Portable to Linux, *BSD and Mac
numcpu()
{
	getconf _NPROCESSORS_ONLN
}

if command readlink --version 2>/dev/null | grep -qF '^readlink (GNU coreutils)'
then
	alias readlinkf='readlink -f --'
elif checkbin greadlink
then
	alias readlinkf='greadlink -f --'
else
	# Portable readlink -f using GNU's semantics (last component need not exist)
	# Currently passes the tests from https://github.com/ko1nksm/readlinkf
	# except loop detection (`getconf SYMLOOP_MAX` is undefined here, anyway)
	readlinkf()
	{
		[ $# -eq 0 ] && return 1
		_status=0
		_pwd=$(pwd -P)
		for _i
		do
			! [ "$_i" ] && { _status=1; continue; }
			if [ -d "$_i" ]
			then
				CDPATH= cd -P -- "$_i" >/dev/null 2>&1 || return 1
				pwd -P
			else
				case "$_i" in */) [ -e "${_i%/}" ] && return 1;; esac
				while true
				do
					CDPATH= cd -P -- "$(dirname -- "$_i")" >/dev/null 2>&1 || return 1
					base=${_i%/}
					base=${base##*/}
					if [ -L "$base" ]
					then
						_i=$(ls -l -- "$base")
						_i=${_i#*"$base -> "}
					else
						dir=$(pwd -P)
						dir=${dir%/}
						printf '%s/%s\n' "$dir" "$base"
						break
					fi
				done
			fi
			cd -- "$_pwd"
		done
		return $_status
	}
fi

# Portable mktemp implementing only the -p option
pmktemp()
{
	case $# in
		0)  pecho "mkstemp(${TMPDIR:-/tmp}/tmp.XXXXXX)" | m4;;
		1)  pecho "mkstemp($1)" | m4;;
		3)
		    [ "$1" != -p ] && echo "Usage: pmktemp [-p TMPDIR] [TEMPLATE]" >&2 && return 1
		    pecho "mkstemp($2/$3)" | m4
		    ;;
		*)  return 1;;
	esac
}

                       ##################################
                       # posix-build specific functions #
                       ##################################

# Like atexit(3), a way to stack EXIT traps
_atexit_cmd=
atexit_eval()
{
	eval "$_atexit_cmd"
}
atexit()
{
	[ "$_atexit_cmd" ] && _atexit_cmd="$_atexit_cmd; $1" || _atexit_cmd=$1
}
trap 'exit 1' HUP INT QUIT ABRT ALRM TERM
trap 'atexit_eval' EXIT

# Like rm, but echo what's going on too
rmv()
{
	pecho rm $@
	rm $@
}

# Call before rewrite_paths() to setup said paths
set_rpaths()
{
	_rpath_script=$(pmktemp)
	atexit 'rm -- "$_rpath_script"'
	for i
	do
		_key=$(bre_escape "rpath_${i%%=*}")
		_val=${i#*=}
		_val=$(sed_repl_escape "$(quote "${_val%/}")")
		pecho "s#^$_key=.*#$_key=$_val#"
	done >"$_rpath_script"
}

# Copy $1 to $2 while rewriting runtime paths of the form ^rpath_*=val$
cp_rewrite_rpaths()
{
	! [ "${_rpath_script:-}" ] &&
		die "set_rpaths must be called before cp_rewrite_rpaths"
	sed -f "$_rpath_script" -- "$1" >"$2"
}

# Fetch URL $1 into path $2 (optional)
pb_fetch()
{
	if checkbin curl
	then
		curl -OL ${2:+-o "$2"} -- "$1"
	elif checkbin wget
	then
		wget ${2:+-O "$2"} -- "$1"
	elif checkbin fetch
	then
		fetch ${2:+-o "$2"} "$1"
	else
		pecho "Need curl, wget or fetch!" >&2
		return 1
	fi
}

pb_install_usage()
{
	cat <<EOF
SYNOPSIS
    pb_install [-qr] [-m MODE] DIRECTORY/ FILE...
    pb_install [-qr] [-m MODE] DESTFILE FILE

DESCRIPTION
    Copy the FILEs to their destination (DIRECTORY with the important / at the
    end or DESTFILE for single FILEs).

OPTIONS
    -m MODE
        Run chmod MODE on the copied FILEs.

    -r
        Use cp_rewrite_rpaths instead of cp(1).

    -q
        Quiet mode.

EOF
	exit 1
}

# See above
pb_install()
{
	_mode=
	_rpath=false
	_quiet=false
	while getopts "m:rq" OPT
	do
		case "$OPT" in
			m)  _mode=$OPTARG;;
			r)  _rpath=true;;
			q)  _quiet=true;;
			\?) pb_install_usage;;
		esac
	done
	shift $((OPTIND - 1))
	[ $# -lt 2 ] && pb_install_usage
	_dest=$1
	shift

	# Check filetypes for FILE...
	for i
	do
		[ ! -L "$i" ] && [ ! -e "$i" ] && die "$i: file not found"
		[ ! -f "$i" ] && die "$i: not a regular file"
	done

	# Create destination if needed
	if [ "${_dest%/}" != "$_dest" ]
	then
		_dest=${_dest%/}
		mkdir -p -- "$_dest"
	else
		[ $# -gt 1 ] && die "Target $_dest must be a directory"
		mkdir -p -- "$(dirname -- "$_dest")"
	fi

	# The actual copy with rpath rewriting and chmod
	if [ ! -e "$_dest" ] || [ -f "$_dest" ]
	then
		[ $# -gt 1 ] && die "Target $_dest must be a directory"
		! "$_quiet" && pecho "Installing $1 to $_dest"
		if "$_rpath"
		then
			cp_rewrite_rpaths "$1" "$_dest"
		else
			cp -- "$1" "$_dest"
		fi
		[ "$_mode" ] && chmod "$_mode" -- "$_dest"
	elif [ -d "$_dest" ]
	then
		_destdir=$_dest
		for i
		do
			_dest=$_destdir/$(basename -- "$i")
			! "$_quiet" && pecho "Installing $i into $_dest"
			if "$_rpath"
			then
				cp_rewrite_rpaths "$i" "$_dest"
			else
				cp -- "$i" "$_dest"
			fi
			[ "$_mode" ] && chmod "$_mode" -- "$_dest"
		done
	fi
}

# remove files and empty directories leftover
uninstall()
{
	for i
	do
		rm -- "$i"
		set +e
		rmdir -p -- "$(dirname -- "$i")" >/dev/null
		set -e
	done
}

# Get the git version with or without git installed. $1 is the repository
# root directory
git_version()
{
	_repo_root=${1%/}
	if command -v git >/dev/null
	then
		set +e
		git rev-parse --verify --quiet HEAD
		_status=$?
		set -e
	else
		if [ ! -f "$_repo_root"/.git/HEAD ]
		then
			_status=1
		else
			_ref=$(cut -d' ' -f2 "$_repo_root"/.git/HEAD)
			if [ ! -f "$_ref" ]
			then
				_status=1
			else
				_status=0
				cat -- "$1"/.git/"$_ref"
			fi
		fi
	fi
	if [ "$_status" -ne 0 ]
	then
		pecho "No git version available"
	fi
}

# General build.sh usage
pb_usage()
{
	cat <<EOF
SYNOPSIS
    $(basename -- "$0") [ACTION]
    PGO=true $(basename -- "$0") CMD [ARGS]

DESCRIPTION
    Build script getting its configuration from the environment and accepting
    the following ACTIONs:
        * clean
        * install
        * uninstall
        * help

    When no ACTION is given, the program is built.
    When PGO is selected through the environment, CMD [ARGS] is run to profile
    the program before rebuilding.

    This notice is generic, read the README for possibly more.

ENVIRONMENT
    CC
        C compiler to use. Defaults to c99(1p).

    LD
        Linker passed to CC via -fuse-ld if this option is available.

    CFLAGS
        Additional flags passed to CC when compiling sources files into
        objects.

    LDFLAGS
        Additional flags passed to CC when linking the objects into the final
        executable.

    PREFIX and DESTDIR
        The program and its files are installed into or uninstalled from
        "\$DESTDIR\$PREFIX/". PREFIX defaults to "/usr/local" and DESTDIR to
        empty.

    MAKE
        Executable to use as make(1p). Defaults to "make".

    JOBS
        If some steps in the compilation support parallel processing, choose
        the number of parallel jobs to run. Defaults to 1.

    LTO
        Try to use link-time optimization when value is "true". Defaults to
        "false".

    PGO
        Try to use profile-guided optimization using the arguments as a command
        to run to profile the program when value is "true". Defaults to "false".

    STATIC
        Try to link statically when value is "true". Defaults to "false".

    NATIVE
        Try to enable optimizations specific to the host CPU when value is
        "true". Defaults to "false".

    CONFIG
        Choose a flag preset corresponding to a build type. Available values
        are "release", "debug" and "profile". Defaults to "release".

EOF
	exit $1
}

# Convert a make compatible source list (no whitespaces, space delimited) to
# its object counterpart
src2obj()
{
	pecho "${1:-$SRC}" | sed 's#\.c\([[:blank:]]*\)#.o\1#g' | paste -sd' '
}

# C build.sh cleanup function
# Also remove "$@"
cclean()
{
	cd -- "$(dirname -- "$BIN")"
	listfiles . -name '*.gperf' -o -name '*.lex' | \
		sed 's#\.lex$#.c#; s#\.gperf$#.c#' | while IFS= read -r i
	do
		rmv -f -- "${i#./}"
	done

	rmv -f -- "$(basename -- "$BIN")" $(src2obj) *.profraw default.profdata *.gcda
	if [ $# -ne 0 ]
	then
		rmv -f -- "$@"
	fi
	cd - >/dev/null
}

# Compiler flag testing functions
cctest_setup()
{
	_sampledir=$(mktemp -d)
	_samplec=$_sampledir/sample.c
	_sampleo=$_sampledir/sample.o
	atexit 'rm -r -- "$_sampledir"'
	pecho "int main(void){}" >"$_samplec"
	"$CC" -c -o "$_sampleo" "$_samplec"
}

test_cflag()
{
	[ ! "${_samplec:-}" ] && cctest_setup
	"$CC" -c -o /dev/null "$@" "$_samplec" >/dev/null 2>&1
}
xtest_cflag()
{
	test_cflag "$@" || die "$CC doesn't support $*"
}
append_cflag()
{
	CFLAGS="${CFLAGS:-} $*"
}

test_append_cflag()
{
	test_cflag "$@" && append_cflag "$@"
}
xtest_append_cflag()
{
	test_append_cflag "$@" || die "$CC doesn't support $*"
}

test_ldflag()
{
	[ ! "${_sampleo:-}" ] && cctest_setup
	"$CC" -o /dev/null "$@" "$_sampleo" >/dev/null 2>&1
}

xtest_ldflag()
{
	test_ldflag "$@" || die "$CC doesn't support $*"
}

append_ldflag()
{
	LDFLAGS="${LDFLAGS:-} $*"
}

test_append_ldflag()
{
	test_ldflag "$@" && append_ldflag "$@"
}

xtest_append_ldflag()
{
	test_append_ldflag "$@" || die "$CC doesn't support $*"
}

append_cppflag()
{
	CPPFLAGS="${CPPFLAGS:-} $*"
}

# Make wrapper for C projects, only mandatory variables are SRC as
# whitespace/newline delimited list of source files, BIN as
# output binary name and CC as compiler name
#
# If JOBS is set to something other than 1, the -j make option will be used
# If $1 is -, stdin is appended to the makefile content
# $@ (except $1 if it is -) is passed as arguments to make
pb_make()
{
	_append_stdin=false
	if [ $# -ge 1 ] && [ "$1" = - ]
	then
		_append_stdin=true
		shift
	fi
	[ "${JOBS:-}" = 1 ] && JOBS=
	{ cat <<'EOF'; $_append_stdin && cat; } | \
		"${MAKE:-make}" ${JOBS:+-j $JOBS} -f - \
		OBJ="$(src2obj)" CC="$CC" BIN="$BIN" CFLAGS="${CFLAGS:-}" CPPFLAGS="${CPPFLAGS:-}" \
		LDFLAGS="${LDFLAGS:-}" LDLIBS="${LDLIBS:-}" "$@"
.POSIX:
.SUFFIXES:
.SUFFIXES: .c .o .gperf .lex

.gperf.c:
	gperf -- $< >$@

.lex.c:
	$(LEX) $(LFLAGS) -t -- $< >$@

.c.o:
	$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ -c $<

$(BIN): $(OBJ)
	$(CC) $(LDFLAGS) $(OBJ) -o $@ $(LDLIBS)

EOF
}