#!/usr/bin/env python
import os
import sys
import shutil
from subprocess import call
from os.path import join as pj

def download(url, target):
    import urllib
    urlp = urllib.urlopen(url)
    with open(target, 'w') as localfile:
        localfile.write(urlp.read())
    urlp.close()

def mkdir(dirname):
    print
    print '*** mkdir  ', dirname
    os.mkdir(dirname)

class VirtualEnv(object):

    def __init__(self, venv_dir):
        self.bin_dir = pj(venv_dir, 'bin')

    def call_bin(self, script_name, args):
        call([pj(self.bin_dir, script_name)] + list(args))

    def pip(self, *args):
        self.call_bin('pip', list(args))

    def python(self, *args):
        self.call_bin('python', args)

    def python_oneliner(self, snippet):
        self.python('-c', snippet)

def main(args):
    if len(args) != 2:
        print 'bootstrape accepts exactly one argument <ape root dir>.'
        print 'The directory must not exist already.'
        sys.exit(1)

    ape_root_dir = os.path.abspath(args[1])

    if os.path.exists(ape_root_dir):
        print 'ape root dir already exists: ', ape_root_dir
        print 'aborted'
        sys.exit(1)

    if not os.path.isdir(os.path.dirname(ape_root_dir)):
        print 'parent directory not found: ', os.path.dirname(ape_root_dir)
        print 'aborted'
        sys.exit(1)

    mkdir(ape_root_dir)
    _ape_dir = pj(ape_root_dir, '_ape')
    mkdir(_ape_dir)

    venv_dir = pj(_ape_dir, 'venv')
    print '*** creating virtualenv ', venv_dir
    print
    call(['virtualenv', venv_dir, '--no-site-packages'])

    venv = VirtualEnv(venv_dir)
    print
    print '*** installing ape into virtualenv'
    print
    venv.pip('install', 'ape')

    print 
    print '*** creating _ape/activape script'
    #get the activape_template from inside the ape package installed in venv
    activape_dst = pj(_ape_dir, 'activape')
    venv.python_oneliner(
        'import os, shutil, pkg_resources;'
        'shutil.copyfile(os.path.abspath('
        'pkg_resources.resource_filename('
        '"ape", "resources/activape_template"'
        ')), "%s")'
         % activape_dst
    )

    if not os.path.isfile(activape_dst):
        print '!!Error creating activape script!!'
        print 'aborted'
        sys.exit(1)

    print
    print '*** ape container mode setup complete'

if __name__ == '__main__':
    main(sys.argv)
