import os, time
from stem.control import Controller

onion = 'onion'
loc = input('Enter installed path of Tor Browser : ')

if loc == '':
    # loc = fr'C:\Users\Vicky\Desktop\Repository\Host-Onion\Tor Browser'
    loc = fr'C:/Users/{os.getlogin()}/Desktop/Tor Browser'
loc_ = loc.replace('\\', '/')

torrc = f'''
# This file was generated by Tor; if you edit it, comments will not be preserved
# The old torrc file was renamed to torrc.orig.1, and Tor will ignore it

ClientOnionAuthDir {loc}\Browser\TorBrowser\Data\Tor\onion-auth
DataDirectory {loc}\Browser\TorBrowser\Data\Tor
GeoIPFile {loc}\Browser\TorBrowser\Data\Tor\geoip
GeoIPv6File {loc}\Browser\TorBrowser\Data\Tor\geoip6
HiddenServiceDir {os.path.join(os.getcwd(), onion)}
HiddenServicePort 80 127.0.0.1:9151
'''

with open(loc_ + '/Browser/TorBrowser/Data/Tor/torrc', 'w') as f:
    f.write(torrc)

try: os.mkdir(onion)
except: pass

port = 5000
host = "127.0.0.1"
hidden_svc_dir = os.path.join(os.getcwd(), onion).replace('\\', '/')

firefox = loc + r'\Browser\firefox.exe'
os.startfile(firefox)
time.sleep(10)

print (" * Getting controller")
controller = Controller.from_port(address=host, port=9151)

try:
    controller.authenticate(password="")
    controller.set_options([
        ("HiddenServiceDir", hidden_svc_dir),
        ("HiddenServicePort", "80 %s:%s" % (host, str(port)))
        ]
    )
    svc_name = open(hidden_svc_dir + "/hostname", "r").read().strip()
    print (f" * Created host: {svc_name}")

except Exception as e:
    print(e)
