#!/usr/bin/python3 -u

## Copyright (C) 2018 - 2020 ENCRYPTED SUPPORT LP <adrelanos@riseup.net>
## See the file COPYING for copying conditions.

import os

whonix = os.path.exists('/usr/share/anon-gw-base-files/gateway')
if whonix:
    torrc_file_path = '/usr/local/etc/torrc.d/40_tor_control_panel.conf'
    torrc_user_file_path =  '/usr/local/etc/torrc.d/50_user.conf'
else:
    torrc_file_path = '/etc/torrc.d/40_tor_control_panel.conf'
    torrc_user_file_path = '/etc/torrc.d/50_user.conf'

torrc_text = '# Do not edit this file!\n\
# Please add modifications to the following file instead:\n'

user_text = '# Tor user specific configuration file\n\
#\n\
# Add user modifications below this line:\n\
############################################\n'

'''Guarantee the existence of /etc/torrc.d/
and the existence of /usr/local/etc/torrc.d/ if required.
'''
if not os.path.exists('/etc/torrc.d/'):
    os.makedirs('/etc/torrc.d/')
if whonix and not os.path.exists('/usr/local/etc/torrc.d/'):
    os.makedirs('/usr/local/etc/torrc.d/')

'''Guarantee the existence of:
1. /etc/torrc.d/95_whonix.conf
2. /etc/tor/torrc
3. "%include /etc/torrc.d/95_whonix.conf" line in /etc/tor/torrc file

In addition, we create 40_tor_control_panel.conf
and 50_user.conf here if they do not exist.
'''
whonix_torrcd_path = '/etc/torrc.d/95_whonix.conf'

if not os.path.exists('/etc/tor/torrc'):
    with open('/etc/tor/torrc', "w+") as f:
        if whonix:
            f.write('%include {0}\n'.format(whonix_torrcd_path))
        else:
            f.write('%include {0}\n'.format(torrc_file_path))
            f.write('%include {0}\n'.format(torrc_user_file_path))

else:
    torrcd_line_exists = 'include /etc/torrc.d' in open('/etc/tor/torrc', "r").read()
    if not torrcd_line_exists:
        with open('/etc/tor/torrc', "a") as f:
            if whonix:
                f.write('%include {0}\n'.format(whonix_torrcd_path))
            else:
                f.write('%include {0}\n'.format(torrc_file_path))
                f.write('%include {0}\n'.format(torrc_user_file_path))

if whonix and not os.path.exists(whonix_torrcd_path):
    with open(whonix_torrcd_path, "w+") as f:
        f.write('%include {0}\n'.format(torrc_file_path))
        f.write('%include {0}\n'.format(torrc_user_file_path))

torrc_text = '%s# %s\n' % (torrc_text, torrc_user_file_path)
if not whonix:
    torrc_text = (torrc_text +
        'Log notice file /run/tor/log\n')

if not os.path.exists(torrc_file_path):
    with open(torrc_file_path, "w+") as f:
        f.write(torrc_text)

if not os.path.exists(torrc_user_file_path):
    with open(torrc_user_file_path, "w+") as f:
        f.write(user_text)

