1#!/usr/bin/env python3
2
3r"""
4See help text for details.
5"""
6
7import sys
8import subprocess
9import re
10
11save_dir_path = sys.path.pop(0)
12
13modules = ['gen_arg', 'gen_print', 'gen_valid', 'gen_misc', 'gen_cmd', 'var_funcs']
14for module in modules:
15    exec("from " + module + " import *")
16
17sys.path.insert(0, save_dir_path)
18
19parser = argparse.ArgumentParser(
20    usage='%(prog)s [OPTIONS]',
21    description="%(prog)s will create a status file path name adhering to the"
22                + " following pattern: <status dir path>/<prefix>.yymmdd."
23                + "hhmmss.status.  It will then run the command string and"
24                + " direct its stdout/stderr to the status file and optionally"
25                + " to stdout.  This dual output streaming will be"
26                + " accomplished using either the \"script\" or the \"tee\""
27                + " program.  %(prog)s will also set and export environment"
28                + " variable \"AUTO_STATUS_FILE_PATH\" for the benefit of"
29                + " child programs.",
30    formatter_class=argparse.ArgumentDefaultsHelpFormatter,
31    prefix_chars='-+')
32
33parser.add_argument(
34    '--status_dir_path',
35    default='',
36    help="The path to the directory where the status file will be created."
37         + "%(default)s The default value is obtained from environment"
38         + " variable \"${STATUS_DIR_PATH}\", if set or from \"${HOME}/"
39         + "status/\".")
40
41parser.add_argument(
42    '--prefix',
43    default='',
44    help="The prefix for the generated file name.%(default)s The default value"
45         + " is the command portion (i.e. the first token) of the command"
46         + " string.")
47
48parser.add_argument(
49    '--status_file_name',
50    default='',
51    help="This allows the user to explicitly specify the status file name.  If"
52         + " this argument is not used, %(prog)s composes a status file name."
53         + "  If this argument is specified, the \"--prefix\" argument is"
54         + " ignored.")
55
56parser.add_argument(
57    '--stdout',
58    default=1,
59    type=int,
60    choices=[1, 0],
61    help="Indicates that stdout/stderr from the command string execution"
62         + " should be written to stdout as well as to the status file.")
63
64parser.add_argument(
65    '--tee',
66    default=1,
67    type=int,
68    choices=[1, 0],
69    help="Indicates that \"tee\" rather than \"script\" should be used.")
70
71parser.add_argument(
72    '--show_url',
73    default=0,
74    type=int,
75    choices=[1, 0],
76    help="Indicates that the status file path shown should be shown in the"
77         + " form of a url.  If the output is to be viewed from a browser,"
78         + " this may well become a clickable link.  Note that the"
79         + " get_file_path_url.py program must be found in the \"PATH\""
80         + " environment variable for this argument to be effective.")
81
82parser.add_argument(
83    'command_string',
84    default='',
85    nargs='*',
86    help="The command string to be run.%(default)s")
87
88# Populate stock_list with options we want.
89stock_list = [("test_mode", 0), ("quiet", 1), ("debug", 0)]
90
91
92def validate_parms():
93    r"""
94    Validate program parameters, etc.
95    """
96
97    global status_dir_path
98    global command_string
99
100    # Convert command_string from list to string.
101    command_string = " ".join(command_string)
102    set_pgm_arg(command_string)
103    valid_value(command_string)
104
105    if status_dir_path == "":
106        status_dir_path = \
107            os.environ.get("STATUS_DIR_PATH",
108                           os.environ.get("HOME") + "/status/")
109    status_dir_path = add_trailing_slash(status_dir_path)
110    set_pgm_arg(status_dir_path)
111    valid_dir_path(status_dir_path)
112
113    global prefix
114    global status_file_name
115    if status_file_name == "":
116        if prefix == "":
117            prefix = command_string.split(" ")[0]
118            # File extensions (e.g. ".sh", ".py", .etc), look clumsy in status file names.
119            extension_regex = "\\.[a-zA-Z0-9]{1,3}$"
120            prefix = re.sub(extension_regex, "", prefix)
121            set_pgm_arg(prefix)
122        status_file_name = prefix + "." + file_date_time_stamp() + ".status"
123        set_pgm_arg(status_file_name)
124
125    global status_file_path
126
127    status_file_path = status_dir_path + status_file_name
128    # Set environment variable for the benefit of child programs.
129    os.environ['AUTO_STATUS_FILE_PATH'] = status_file_path
130    # Set deprecated but still used AUTOSCRIPT_STATUS_FILE_PATH value.
131    os.environ['AUTOSCRIPT_STATUS_FILE_PATH'] = status_file_path
132
133
134def script_func(command_string, status_file_path):
135    r"""
136    Run the command string producing both stdout and file output via the script command and return the
137    shell_rc.
138
139    Description of argument(s):
140    command_string                  The command string to be run.
141    status_file_path                The path to the status file which is to contain a copy of all stdout.
142    """
143
144    cmd_buf = "script -a -q -f " + status_file_path + " -c '" \
145        + escape_bash_quotes(command_string) + " ; printf \"\\n" \
146        + sprint_varx(ret_code_str, "${?}").rstrip("\n") + "\\n\"'"
147    qprint_issuing(cmd_buf)
148    sub_proc = subprocess.Popen(cmd_buf, shell=True)
149    sub_proc.communicate()
150    shell_rc = sub_proc.returncode
151
152    # Retrieve return code by examining ret_code_str output statement from status file.
153    # Example text to be analyzed.
154    # auto_status_file_ret_code:                        127
155    cmd_buf = "tail -n 10 " + status_file_path + " | egrep -a \"" \
156        + ret_code_str + ":[ ]+\""
157    rc, output = shell_cmd(cmd_buf)
158    key, value = parse_key_value(output)
159    shell_rc = int(value)
160
161    return shell_rc
162
163
164def tee_func(command_string, status_file_path):
165    r"""
166    Run the command string producing both stdout and file output via the tee command and return the shell_rc.
167
168    Description of argument(s):
169    command_string                  The command string to be run.
170    status_file_path                The path to the status file which is to contain a copy of all stdout.
171    """
172
173    cmd_buf = "set -o pipefail ; " + command_string + " 2>&1 | tee -a " \
174        + status_file_path
175    qprint_issuing(cmd_buf)
176    sub_proc = subprocess.Popen(cmd_buf, shell=True)
177    sub_proc.communicate()
178    shell_rc = sub_proc.returncode
179
180    print
181    print_varx(ret_code_str, shell_rc)
182    with open(status_file_path, "a") as status_file:
183        # Append ret code string and status_file_path to end of status file.
184        status_file.write("\n" + sprint_varx(ret_code_str, shell_rc))
185
186    return shell_rc
187
188
189def main():
190
191    gen_setup()
192
193    set_term_options(term_requests={'pgm_names': [command_string.split(" ")[0]]})
194
195    global ret_code_str
196    ret_code_str = re.sub("\\.py$", "", pgm_name) + "_ret_code"
197
198    global show_url
199    if show_url:
200        shell_rc, output = shell_cmd("which get_file_path_url.py", show_err=0)
201        if shell_rc != 0:
202            show_url = 0
203            set_pgm_arg(show_url)
204        else:
205            shell_rc, status_file_url = shell_cmd("get_file_path_url.py "
206                                                  + status_file_path)
207            status_file_url = status_file_url.rstrip("\n")
208
209    # Print status file path/url to stdout and to status file.
210    with open(status_file_path, "w+") as status_file:
211        if show_url:
212            print_var(status_file_url)
213            status_file.write(sprint_var(status_file_url))
214        else:
215            print_var(status_file_path)
216            status_file.write(sprint_var(status_file_path))
217
218    if stdout:
219        if tee:
220            shell_rc = tee_func(command_string, status_file_path)
221        else:
222            shell_rc = script_func(command_string, status_file_path)
223        if show_url:
224            print_var(status_file_url)
225        else:
226            print_var(status_file_path)
227    else:
228        cmd_buf = command_string + " >> " + status_file_path + " 2>&1"
229        shell_rc, output = shell_cmd(cmd_buf, show_err=0)
230        with open(status_file_path, "a") as status_file:
231            # Append ret code string and status_file_path to end of status
232            # file.
233            status_file.write("\n" + sprint_varx(ret_code_str, shell_rc))
234
235    # Append status_file_path print statement to end of status file.
236    with open(status_file_path, "a") as status_file:
237        if show_url:
238            status_file.write(sprint_var(status_file_url))
239        else:
240            status_file.write(sprint_var(status_file_path))
241    exit(shell_rc)
242
243
244main()
245