1# Written by Aleksey Cheusov <vle@gmx.net>, public domain
2#
3# This awk module is a part of RunAWK distribution,
4#        http://sourceforge.net/projects/runawk
5#
6############################################################
7
8# =head2 init_getopt.awk
9#
10# Initialization step for power_getopt.awk module.  In some cases it
11# makes sense to process options in a while() loop.  This module
12# allows doing this.  See the documentation about how options are
13# initialized in power_getopt.awk module.
14#
15# =over 2
16#
17# =item I<print_help ()>
18#
19# display help message.
20#
21# =back
22#
23
24#use "alt_getopt.awk"
25#use "embed_str.awk"
26
27function print_help (            i){
28	for (i = 1; i <= _help_msg_cnt; ++i){
29		if (_help_msg_arr [i] ~ /^[ \t]*=/){
30			sub(/=/, "-", _help_msg_arr [i])
31		}
32		print _help_msg_arr [i] > "/dev/stderr"
33	}
34}
35
36BEGIN {
37	if ("help" in EMBED_STR){
38		_help_msg = EMBED_STR ["help"]
39		_help_msg_cnt = split(_help_msg, _help_msg_arr, /\n/)
40		for (i = 1; i <= _help_msg_cnt; ++i){
41			if (match(_help_msg_arr [i], /^[ \t]*[-=][^ \t]+/)){
42				_opt = substr(_help_msg_arr [i], RSTART, RLENGTH)
43				sub(/^[ \t]+/, "", _opt)
44
45				if (_opt ~ /^-.[|]--.+$/){
46					# -h|--help
47					_sopt = substr(_opt, 1, 2)
48					_lopt = substr(_opt, 4)
49				}else if (_opt ~ /^=.[|]--.+$/){
50					# =h|--help
51					_sopt = substr(_opt, 1, 2)
52					_lopt = "=" substr(_opt, 5)
53				}else if (_opt ~ /^[-=].$/){
54					# -h or =h
55				_sopt = _opt
56					_lopt = ""
57				}else if (_opt ~ /^[-=]-.+$/){
58					# --help or =-help
59					_sopt = ""
60					_lopt = _opt
61				}
62
63				if (_sopt ~ /^-.$/){
64					# -h
65					short_opts = short_opts substr(_sopt, 2, 1)
66				}else if (_sopt ~ /^=.$/){
67					# =F
68					short_opts = short_opts substr(_sopt, 2, 1) ":"
69				}
70
71				sub(/^[-=]/, "", _sopt)
72
73				if (_lopt ~ /^--.+$/){
74					# --help
75					long_opts [substr(_lopt, 3)] = _sopt
76				}else if (_lopt ~ /^=-.+$/){
77					# =-FLAG
78					if (_sopt != "")
79						long_opts [substr(_lopt, 3)] = _sopt
80					else
81						long_opts [substr(_lopt, 3)] = takes_arg
82				}
83			}
84		}
85	}
86}
87