<%

# Note that this file is not a valid *.html file!
# It is intended to be a bottlepy - style template
# used for the scripting part of TheOnionBox!

import os
import psutil


# from tob.configcollector import ConfigCollector
# cfgcoll = ConfigCollector(tor)

configs_used = get('configs_used', [])
configs_all = []

try:
    # get all valid configuration names (only and drop attached information)
    config_names = tor.get_info('config/names')
    # print(config_names)
    names_with_values = config_names.splitlines()
    config_params = {}
    for line in names_with_values:
        # print(line)
        config = line.split(' ')

        try:
            c0 = config[0]
            c1 = config[1]

            # https://trac.torproject.org/projects/tor/ticket/20956
            # see as well configcollector.py
            if 'Port' in c0 and c1 in ['Dependent', 'Dependant', 'Virtual']:  # special handling for ...Port's !
                c1 = 'LineList'
            end

            config_params[c0] = c1
        except:
            pass
        end
    end
except:
    pass
end

enable_print = False
if enable_print is True:
    print(tor.get_info('config/defaults'))
    print('-----')
    print(tor.get_info('config/names'))
    print('-----')
    print(tor.get_info('config-text'))
end

%>

{{!header_row('Tor', 'Configuration', 'config')}}

<%
    cmd_line = []

    if tor.is_localhost():
        try:
            pid = tor.get_pid()
            p = psutil.Process(pid)
            cmd_line = p.cmdline()  # This returns a list!
        except:
            pass
        end
    end

    if len(cmd_line) > 0:
%>
        <div class = "row">
            <div class="{{box_datum_grid}}">
                <div class="option_hover truncate ">
                    <a href="manpage.html#_command_line_options" target="manpage_window">#</a> Commandline
                </div>
            </div>
            <div class="{{box_value_grid}} box_value_margin">
                <%
                out = ''
                # HCP detection!!
                hcp = 0
                for cmd in cmd_line:
                    if len(out):
                        out += ' '
                    end
                    if (hcp % 2 > 0) and cmd[:3] == '16:':
                        cmd = cmd[:12] + '...'  # no need to transmit this completely!
                        hcp += 1
                    end
                    if "HashedControlPassword" in cmd or "HashedControlSessionPassword" in cmd:
                        hcp += 1
                    end
                    out += cmd
                end
                %>
                {{out}}
                % if hcp > 1:
                    <div style="font-size: 70%; color: lightgray; display: block;">
                        The HashedControl(Session)Password was truncated for safety reasons.
                    </div>
                % end
            </div>
            <div class="{{box_right_grid}}"></div>
        </div>
%   end

<div class = "row">
    <div class="{{box_datum_grid}}">
        <div class='truncate' style='color: lightgrey; '>Configuration Files</div>
    </div>
    <div class="{{box_value_grid}} box_value_margin">
        <div class='config_group' style='color: lightgrey; '></div>
    </div>
    <div class="{{box_right_grid}}"></div>
</div>

<div class = "row">
    <div class="{{box_datum_grid}}">
        torrc
    </div>
    <div class="{{box_value_grid}} box_value_margin">
        {{!tor.get_info('config-file')}}
    </div>
    <div class="{{box_right_grid}}"></div>
</div>

<div class = "row">
    <div class="{{box_datum_grid}}">
        torrc.defaults
    </div>
    <div class="{{box_value_grid}} box_value_margin">
        {{!tor.get_info('config-defaults-file')}}
    </div>
    <div class="{{box_right_grid}}"></div>
</div>
<%

    # configs_used = cfgcoll.collect_configs_used()

    manpg = get('manpage', None)

    mp_groups = manpg.get_groups()
    if mp_groups:
        for group in mp_groups:
            if group == 'HIDDEN SERVICE OPTIONS':
                continue
            end
            headr = False
            options = manpg.get_options(group)
            if options:
                for option in options:
                    if option in configs_used:
                        if headr is False:
%>
                            <div class = "row">
                                <div class="{{box_datum_grid}}">
                                    <div class='truncate' style='color: lightgrey; '>{{group.title()}}</div>
                                </div>
                                <div class="{{box_value_grid}} box_value_margin">
                                    <div class='config_group' style='color: lightgrey; '></div>
                                </div>
                                <div class="{{box_right_grid}}"></div>
                            </div>
                            % headr = True
                        % end

                        <div class = "row">
                            <div class="{{box_datum_grid}}">
                                <div class="option_hover truncate ">
                                    % if option[:2] != '__' and option[:3] != '___':
                                        <a href="manpage.html#{{option}}" target="manpage_window">#</a> {{option}}
                                    % else:
                                        % if option[-4:] == 'Port':
                                            <a href="manpage.html#_non_persistent_options" target="manpage_window">#</a> {{option}}
                                        % else:
                                            {{option}}
                                        % end
                                    % end
                                </div>
                            </div>
                            <div class="{{box_value_grid}} box_value_margin">
                                <%
                                    pt = config_params[option] # pt => parameter-type

                                    #optngrp = {'ControlPort': 'CONTROL',
                                    #           'DirPort': 'DIR',
                                    #           'ORPort': 'OR',
                                    #           'SocksPort': 'SOCKS'}

                                    values = []

                                    #if option in optngrp:
                                    #    port_tuples = tor.get_listeners(optngrp[option], '')
                                    #    values = [prt[0] + ':' + str(prt[1]) for prt in port_tuples]
                                    #end

                                    if len(values) == 0:
                                        values = configs_used[option]
                                    end
                                %>
                                % if pt == 'Boolean':
                                    {{values[0] == '1'}}
                                <%
                                  elif pt == 'DataSize':
                                    out = pretty_number(int(values[0]), calc = 'iec')

                                    # These are options that use the 'DataSize' type
                                    # yet define data without time reference (/s)
                                    # Therefore: Don't add a '/s' when indicating this value!
                                    datasize_no_s = {'AccountingMax', 'ConstrainedSockSize', 'MaxMemInQueues'}

                                    if option not in datasize_no_s:
                                        out += '/s'
                                    end
                                %>
                                    {{out}}
                                <%
                                  elif pt in ['LineList', 'RouterList']:
                                    sep = '<br>'
                                    # if option == 'ExitPolicy':
                                    #     sep = ' | '
                                    # end
                                    out = ''
                                    trunc_msg = '<div style="font-size: 70%; color: lightgray; display: block;">This value was truncated for safety reasons.</div>'
                                    # print(values)
                                    for value in values:
                                        if option in ['HashedControlPassword', '__HashedControlSessionPassword']:
                                            value = value[:12] + '...'  # no need to transmit this completely!
                                            value += trunc_msg
                                        elif option in ['HidServAuth']:
                                            vs = value.split(' ')
                                            if len(vs) == 2:
                                                value = vs[0] + ' '
                                                if len(vs[1]) > 4:
                                                    value += vs[1][:5]
                                                end
                                                value += '...'
                                                value += trunc_msg
                                            end
                                        end
                                        if len(out) > 0:
                                            out += sep
                                        end
                                        out += value
                                    end
                                %>
                                    {{!out}}
                                % elif len(pt) > 0:
                                %   if values is not None and len(values) > 0:
                                        {{values[0]}}
                                %   else:
                                        <code>none</code>
                                %   end
                                % else:
                                    <code>Error</code>
                                % end
                            </div>
                            <div class="{{box_right_grid}}"></div>
                        </div>
    <%
                    end
                end
            end

        end
    end
%>

<div class = "row">
    <div class="{{box_datum_grid}}">
    </div>
    <div class="{{box_value_grid}} box_value_margin">
        <div class='config_group' style='color: lightgrey; '></div>
    </div>
    <div class="{{box_right_grid}}"></div>
</div>


<div class = "row">
    <div class="{{box_datum_grid}}">
       <div style='color: lightgrey;'>Remark</div>
    </div>
    <div class="{{box_value_grid}} box_value_margin">
        <div style='color: lightgrey;'>Any configuration option not displayed above is set to its default value.</div>
    </div>
    <div class="{{box_right_grid}}"></div>
</div>


<hr>