#!/usr/bin/env python3
#
# BOTLIB Framework to program bots
#
# bin/bot-do
#
# Copyright 2017 B.H.J Thate
# 
# 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.
#
# Bart Thate
# Heerhugowaard
# The Netherlands

""" create a distributable tarball of botlib, including all dependancies. """

import os; import sys; sys.path.insert(0, os.getcwd())

import shutil
import urllib
import urllib.parse
import urllib.request

pipurl = "https://bootstrap.pypa.io/get-pip.py"

fname = os.getcwd().split(os.sep)[-1].upper()
installdir = os.path.join(os.getcwd(), fname)

sys.path.insert(0, installdir)

print("setting PYTHONPATH to %s" % installdir)
os.environ['PYTHONPATH'] = installdir

def get_url(url):
    """ fetch data from url. """
    url = urllib.parse.urlunparse(urllib.parse.urlparse(url))
    req = urllib.request.Request(url)
    response = urllib.request.urlopen(req)
    response.data = response.read()
    return response

try:
    shutil.rmtree(installdir)
except:
    pass

try:
    os.mkdir(installdir)
except:
    pass

if not os.path.exists("%s/get-pip.py" % installdir):
    print("downloading pip")
    resp = get_url(pipurl)
    f = open("%s/get-pip.py" % installdir, "w")
    f.write(str(resp.data, "utf-8"))
    f.flush()
    f.close()
    for l in os.popen("python3 %s/get-pip.py -t %s" % (installdir, installdir)).readlines():
        print(l)

try:
    import setuptools
    import setuptools.command
    from setuptools.command.easy_install import main
except ImportError as ex:
    print("setuptools is needed to use bot-nest: %s" % str(ex))
    os._exit(0)


try:
    shutil.rmtree("dist")
except:
    pass

try:
    shutil.rmtree("%s.egg-info" % fname)
except:
    pass

try:
    os.mkdir("dist")
except:
    pass

for line in os.popen("python3 setup.py sdist").readlines():
    print(line.strip())

fns = os.listdir("dist")
target = fname
highest = 0
for fn in fns:
    f = fn.split(".")[0]
    nr = int(f.split("-")[-1])
    if nr > highest:
        highest = nr
        target = fn

if os.path.exists("dist"):
    runstring = '--always-copy --record=install.log --install-dir=%s -a -U -l %s/dist/%s ' % (installdir, os.getcwd(), target)
    main(runstring.split())

#runstring = '--record=install.log --install-dir=%s -a -U sleekxmpp' % installdir
#main(runstring.split())

#runstring = '--record=install.log --install-dir=%s -a -U bs4' % installdir
#main(runstring.split())

#runstring = '--record=install.log --install-dir=%s -a -U pyasn1' % installdir
#main(runstring.split())

#runstring = '--record=install.log --install-dir=%s -a -U pyasn1_modules' % installdir
#main(runstring.split())

#runstring = '--record=install.log --install-dir=%s -a -U feedparser' % installdir
#main(runstring.split())

#runstring = '--record=install.log --install-dir=%s -a -U dnspython' % installdir
#main(runstring.split())

runstring = '--record=install.log --install-dir=%s -a -U setuptools' % installdir
main(runstring.split())

for line in os.popen("tar zcvf %s.tar.gz %s" % (fname.lower(), fname)).readlines():
    print(line.strip())
