#!/usr/bin/env python3

from os import listdir
from os.path import isfile, join
import argparse
import configparser
import re
import subprocess
import sys


# ------------------------------------------------------------------------
# Display the POD from the end of this file

def display_pod():
    subprocess.call(['/usr/bin/pod2text', sys.argv[0]])
    return


class remctl_help:

    # -----------------------------------------------------------
    # Initialization: Read the config file and bind to the directory

    def __init__(self, conf=None, override=None):
        conf_file = '/etc/remctl-help.conf'

        # Read list of any commands to be hidden
        self.hide = {}
        if isfile(conf_file):
            conf = configparser.ConfigParser()
            conf.read(conf_file)
            hide_str = conf.get('global', 'hide')
            hide_list = hide_str.split(',')

            # Read list of any commands to be hidden
            for h in hide_list:
                self.hide[h.strip()] = 1

        a_path = '/etc/remctl/conf.d/'
        file_list = [f for f in listdir(a_path) if isfile(join(a_path, f))]

        # Read the configuration files and unfold the command defintions.
        continued_pattern = re.compile(r'(.*?)\\\s*$')
        remark_pattern = re.compile(r'^\s*#')
        remctl_lines = []
        for conf_file in file_list:
            conf_path = a_path + conf_file
            f = open(conf_path, 'r')
            unfolded_line = ''
            for line in f:
                if remark_pattern.match(line):
                    continue
                this_line = line.strip()
                if continued_pattern.search(this_line):
                    m = continued_pattern.search(this_line)
                    if len(unfolded_line) > 0:
                        unfolded_line += ' '
                    unfolded_line += m.group(1).strip()
                    continue
                if len(unfolded_line) > 0:
                    unfolded_line += ' ' + this_line
                    remctl_lines.append(unfolded_line)
                    unfolded_line = ''
                    continue
                remctl_lines.append(this_line)
            if unfolded_line:
                remctl_lines.append(unfolded_line)
            f.close()

        # Pull a list of help commands from the configuration lines using
        # a dictionary to eliminate duplicates.
        self.prog_list = {}
        for aline_raw in remctl_lines:
            aline = re.sub(r'\s\s+', ' ', aline_raw).strip()
            toks = aline.split(' ')
            if len(toks) > 2:
                cmd = toks.pop(0)
                sub_cmd = toks.pop(0)
                cmd_exe = toks.pop(0)
                if sub_cmd == 'ALL' or sub_cmd == 'help':
                    if isfile(cmd_exe):
                        if cmd not in self.prog_list:
                            self.prog_list[cmd] = {}
                        self.prog_list[cmd]['exe'] = cmd_exe
                        for acl in toks:
                            if ':' not in acl and acl != 'ANYUSER':
                                acl_id = 'file:{}'.format(acl)
                            else:
                                acl_id = acl
                            if 'acl' not in self.prog_list[cmd]:
                                self.prog_list[cmd]['acl'] = {}
                            self.prog_list[cmd]['acl'][acl_id] = acl

        return

    # ------------------------------------------------------------------------
    # Run help commands

    def display_verbose(self, fragment):
        cnt = 0
        for cmd in sorted(self.prog_list):
            if cmd in self.hide:
                continue
            if fragment is None or fragment in cmd:
                cnt = cnt + 1
                script = self.prog_list[cmd]['exe']
                proc = subprocess.Popen([script, 'help'],
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE)
                tmp = proc.stdout.read()
                tmp_out = tmp.decode('utf8')
                err = proc.stderr.read()
                err_out = err.decode('utf8')
                print('---------------------------------------------------')
                print('remctl Command: {}'.format(cmd))
                print('')
                if tmp_out is not None:
                    print(tmp_out)
                if err_out is not None:
                    print(err_out)
        if cnt == 0:
            print('No matching commands found')
        return

    # ------------------------------------------------------------------------
    # Just display help command

    def display_help(self, fragment):
        print('Available commands:')
        print('')
        print('  {}'.format('Command'))
        print('  {}'.format('-'*16))
        cnt = 0
        for cmd in sorted(self.prog_list):
            if cmd in self.hide:
                continue
            if fragment is None or fragment in cmd:
                cnt = cnt + 1
                print('  {}'.format(cmd))
        if cnt == 0:
            print('No matching commands found')
        else:
            print('')
        return

    # ------------------------------------------------------------------------
    # Display ACLs by command

    def display_acl(self, fragment, expand):
        cnt = 0
        print('Available Commands and their ACLs:')
        print('')
        print('  {}'.format('Command'))
        print('  {}'.format('-'*16))
        for cmd in sorted(self.prog_list):
            if fragment is None or fragment in cmd:
                cnt = cnt + 1
                if cmd in self.hide:
                    continue
                print('  {}'.format(cmd))
                for acl in sorted(self.prog_list[cmd]['acl']):
                    print('    {}'.format(acl))
                    if expand and acl.startswith('file:'):
                        acl_path = acl[len('file:'):]
                        if isfile(acl_path):
                            with open(acl_path, mode='r') as acl_file:
                                lines = acl_file.readlines()
                            for aline in lines:
                                if aline.startswith('#'):
                                    continue
                                print('      {}'.format(aline.strip()))
                print('')
        if cnt == 0:
            print('No matching commands found')
        return


##############################################################################
# Main Routine
##############################################################################

# Command line arguments
parser = argparse.ArgumentParser(
    description='Tool to display available remctl commands')
parser.add_argument('action',
                    nargs='?',
                    choices=['acl', 'help', 'verbose', None],
                    help='Valid actions are acl or help or verbose or empty',
                    default=None)
parser.add_argument('fragment',
                    help='Command Fragment',
                    nargs='?',
                    default=None)
parser.add_argument('--manual',
                    action='store_true',
                    help='Documentation for help script')
parser.add_argument('--expand',
                    action='store_true',
                    help='Display extended remctl help')

args = parser.parse_args()
if args.manual:
    print(display_pod())
    sys.exit(0)

rh = remctl_help()

if args.action == 'acl':
    rh.display_acl(args.fragment, args.expand)
elif args.action == 'verbose':
    rh.display_verbose(args.fragment)
else:
    rh.display_help(args.fragment)

sys.exit()

doc = '''

=head1 NAME

remctl_help - list remctl commands and ACLs installed on a host

=head1 SYNOPSIS

remctl_help [help [fragment]] [--help] [--manual]
remctl_help acl [fragment] [--expand] [--help] [--manual]
remctl_help verbose [fragment] [--help] [--manual]

=head1 DESCRIPTION

This script reads all of the files in /etc/remctl/conf.d and
generates a list of all commands that have a subcommand of 'ALL'
or 'help' and for which the executable exists. The default action
of the script is to display the list of commands.

Note, this script displays help for all commands whether or not
the user has access to run the command.

=head1 ACTIONS

=over 4

=item help [fragment]

Display a list of remctl commands supported by the host.

=item acl [fragment]

Display a list of remctl commands and the ACLs that control access
to the command.

=item verbose [fragment]

Display a list of remctl commands and the ACLs that control access
to the command.

=back

=head1 SWITCHES

=over 4

=item --expand

How the principals in the ACL files.

=item --help

Display a usage message for the help command itself.

=item --manual

This documentation.

=back

=head1 AUTHOR

Bill MacAllister <whm@stanford.edu>

=head1 COPYRIGHT

Copyright 2016, 2019-2022 Dropbox

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

=cut
'''
