#!/software/Python/2.7.9/bin/python

import argparse

parser = argparse.ArgumentParser(description="bit, [b]ermunda [i]nformation [t]riangle.\
 bit is a git-based tool for the management of code and data. It uses git for code versioning\
 and ownCloud for storing and exchanging data. It saves storage by avoiding versioning\
 of data while logging changes in associated git wikis.",\
formatter_class = argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-i", "--input", nargs='*', help="Input files")
parser.add_argument("-s", "--subfolder", help="Subfolder to be created.", default=None)
parser.add_argument("-m", "--message",nargs='*', help="Message to write on log file.", default=None)
parser.add_argument("-d", "--pick_a_date", help="Pick an existing date folder to transfer data to/from. Format=YYYY-MM-DD", default=None)
parser.add_argument("-c", "--create_folder", help="Create dropbox folder for user to upload data.", action="store_true")
parser.add_argument("-g", "--getfolder", help="Downloads a folder as zip file. Requires --pick_a_date. Defaults --base_folder=upload:download to download", action="store_true")
parser.add_argument("-t", "--days_to_share", help="Number of days you wish to share this folder further.", default=21)
parser.add_argument("--scripts",help="Needs -i and -m. Simultaneously sync the scripts.user folder when uploading data.", action="store_true")
parser.add_argument("--start", help="Project name of the format. PI_PROJECT_NAME. Initiates a project. This will create the required local folders and respective git repositories.", default=None)
parser.add_argument("--stdfolders",nargs='*', help="Folders to be created in addition to scripts.user and and wiki.user when a project is started.", default=["tmp","slurm_logs"])
parser.add_argument("--adduser",help="Add a user to a project creating his scripts.user and wiki.user folder",action="store_true")
parser.add_argument("--gitssh", help="Use your git SSH keys.",  action="store_true")
parser.add_argument("--config", help="Generate a config file.", action="store_true")
args = parser.parse_args()

import json
import time
import datetime
import owncloud
import os
import sys
import getpass
from os.path import expanduser
from subprocess import Popen, PIPE, STDOUT
import subprocess as sb
import stat

structure="\n\
/file_system_a\n\
    |\n\
    '- data\n\
        |\n\
        '- projects\n\
            |\n\
            |- Company_A\n\
            |   |\n\
            |   |- CA_project_y\n\
            |   |\n\
            |   '- CA_project_x\n\
            |       |\n\
            |       |- results\n\
            |       |- models\n\
            |       |- scripts\n\
            |       |- tmp\n\
            |       |- slurm_logs\n\
            |       '- wiki\n\
            |\n\
            '- Company_B\n\
                |\n\
                '- CB_project_n\n\n\
absolute path to projects =  /file_system_a/data/projects/"

def get_owncloud_address():
    owncloud_address=str(raw_input("Please give in your ownCloud address (eg. http://domain.tld/owncloud): ")) or None
    return owncloud_address

def get_owncloud_upload_folder():
    owncloud_upload_folder=str(raw_input("Please give in the folder in your ownCloud that will be used to deliver data to users.\nYou can share this folder with your colleagues so that everybody delivers data through the same folder. (default: DELIVERY_SERVICE):")) or "DELIVERY_SERVICE"
    return owncloud_upload_folder

def get_owncloud_download_folder():
    owncloud_download_folder=str(raw_input("Please give in the folder in your ownCloud that will be used to retrieve data from users.\nYou can share this folder with your colleagues so that everybody retrieves data through the same folder. (default: DROPBOX):")) or "DROPBOX"
    return owncloud_download_folder

def get_owncloud_user(config_file=None):
    if config_file:
        owncloud_user=str(raw_input("Please give in your ownCloud user name or press Enter if you do not want to save this information on the config file: ")) or None
    else:
        owncloud_user=str(raw_input("Please give in your ownCloud user name: ")) or None
    return owncloud_user

def get_owncloud_pass(config_file=None):
    if config_file:
        owncloud_pass=str(getpass.getpass(prompt="Please give in your ownCloud password or press Enter if you do not want to save this information on the config file: ")) or None
    else:
        owncloud_pass=str(getpass.getpass(prompt="Please give in your ownCloud password: ")) or None
    return owncloud_pass

def get_github_address():
    github_address=str(raw_input("Github server address (default: https://github.com): ") or "https://github.com")
    return github_address

def get_github_organization():
    github_organization=str(raw_input("Your GitHub organization name (eg. mpg-age-bioinformatics for https://github.com/mpg-age-bioinformatics): ")) or None
    return github_organization

def get_github_user(config_file=None,gitssh=args.gitssh):
    if not gitssh:
        if config_file:
            github_user=str(raw_input("Please give in your user name for your github server or press Enter if you do not want to save this information on the config file: ")) or None
        else:
            github_user=str(raw_input("Please give in your user name for your github server: ")) or None
    else:
        github_user=None
    return github_user

def get_github_pass(config_file=None,gitssh=args.gitssh):
    if not gitssh:
        if config_file:
            github_pass=str(getpass.getpass(prompt="Please give in your password for your github server or press Enter if you do not want to save this information on the config file: ")) or None
        else:
            github_pass=str(getpass.getpass(prompt="Please give in your password for your github server: ")) or None
    else:
        github_pass=None
    return github_pass

def get_local_path(structure=structure):
    local_path=str(raw_input("The bermuda information triangle works on the basis that all your projects are located in the same path and have a parent subpath in your local machine ie. %s\n" %structure ) ) or None
    return local_path

def get_github_api(github_address):
    if "github.com" in github_address:
        github_api="https://api.github.com/orgs/"
    else:
        github_api=github_address+"/api/v3/orgs/"
    return github_api

def check_reqs(requirements,configdic,config_file=None, gitssh=args.gitssh):
    if "owncloud_address" in requirements:
        configdic["owncloud_address"]=get_owncloud_address()
    if "owncloud_upload_folder" in requirements:
        configdic["owncloud_upload_folder"]=get_owncloud_upload_folder()
    if "owncloud_download_folder" in requirements:
        configdic["owncloud_download_folder"]=get_owncloud_download_folder()
    if "owncloud_user" in requirements:
        configdic["owncloud_user"]=get_owncloud_user(config_file=config_file)
    if "owncloud_pass" in requirements:
        configdic["owncloud_pass"]=get_owncloud_pass(config_file=config_file)
    if "github_address" in requirements:
        configdic["github_address"]=get_github_address()
    if "github_organization" in requirements:
        configdic["github_organization"]=get_github_organization()
    if "github_user" in requirements:
        configdic["github_user"]=get_github_user(config_file=config_file,gitssh=gitssh )
    if "github_pass" in requirements:
        configdic["github_pass"]=get_github_pass(config_file=config_file,gitssh=gitssh )
    if "local_path" in requirements:
        configdic["local_path"]=get_local_path()
    return configdic

requirements=["owncloud_address","owncloud_upload_folder",\
"owncloud_download_folder","owncloud_user",\
"owncloud_pass","github_address",\
"github_organization","github_user",\
"github_pass","local_path"]

special_reqs=["owncloud_user","owncloud_pass",\
"github_user","github_pass"]

start_reqs=["github_address","github_organization",\
"github_user","github_pass","local_path"]


def git_target(github_address,github_organization,github_repo,github_user=None,github_pass=None,gitssh=args.gitssh,usepw=None):
    url=github_address.split("//")[-1]
    if not args.gitssh:
        git="https://%s:%s@%s/%s/%s.git" %(github_user,github_pass,url,github_organization,github_repo)
    else:
        git="git@%s:%s/%s.git" %(url,github_organization,github_repo)
    if usepw:
        git2="https://%s@%s/%s/%s.git" %(github_user,url,github_organization,github_repo)
        return git, git2
    else:
        return git

def git_clone(local_name,github_address,github_organization,github_repo,github_user=None,github_pass=None,gitssh=args.gitssh):
    git, git2 =git_target(github_address,github_organization,github_repo,github_user=github_user,github_pass=github_pass,gitssh=gitssh,usepw=True)
    if not os.path.exists(local_name):
        os.makedirs(local_name)
    cwd = os.getcwd()
    os.chdir(local_name)
    out=sb.call(['git','init'])
    out=sb.call(['git','config','remote.origin.url',git2])
    out=sb.call(['git','config','branch.master.remote','origin'])
    out=sb.call(['git','config','branch.master.merge','refs/heads/master']) 
    out=sb.call(['git','pull', git])
    os.chdir(cwd)
    return out

def git_fetch(github_address,github_organization,github_repo,github_user=None,github_pass=None,gitssh=args.gitssh):
    git=git_target(github_address,github_organization,github_repo,github_user=github_user,github_pass=github_pass,gitssh=gitssh)
    call=["git","fetch",git]
    out=Popen(call, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
    print out.communicate()[0].rstrip()

def git_merge(message):
    call=["git","merge","FETCH_HEAD","-m",message]
    out=Popen(call, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
    print out.communicate()[0].rstrip()

def git_pull(github_address,github_organization,github_repo,github_user=None,github_pass=None,gitssh=args.gitssh):
    git=git_target(github_address,github_organization,github_repo,github_user=github_user,github_pass=github_pass,gitssh=gitssh)
    call=["git","pull",git]
    out=Popen(call, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
    print out.communicate()[0].rstrip()

def git_add(files_to_add):
    for f in files_to_add:
        call=["git","add",f]
        out=Popen(call, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
        print out.communicate()[0].rstrip()

def git_commit(message):
    call=["git","commit","-m", message]
    out=Popen(call, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
    print out.communicate()[0].rstrip()

def git_push(github_address,github_organization,github_repo,github_user=None,github_pass=None,gitssh=args.gitssh):
    git=git_target(github_address,github_organization,github_repo,github_user=github_user,github_pass=github_pass,gitssh=gitssh)
    call=["git","push",git,"--all"]
    if gitssh:
        out=Popen(call, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
        print out.communicate()[0].rstrip()
    else:
        FNULL = open(os.devnull, 'w')
        out=Popen(call, stdout=FNULL, stdin=PIPE ,stderr=STDOUT) #, stdout=FNULL, stderr=subprocess.STDOUT old: stdout=PIPE, stdin=PIPE, stderr=STDOUT
        out=Popen(["git","push"],stdout=PIPE, stdin=PIPE, stderr=STDOUT)

def git_sync(files_to_add,message,github_address,github_organization,github_repo,github_user=None,github_pass=None,gitssh=args.gitssh):
    git_add(files_to_add)
    git_commit(message)
    git_fetch(github_address,github_organization,github_repo,github_user=github_user,github_pass=github_pass,gitssh=gitssh)
    git_merge(message)
    git_push(github_address,github_organization,github_repo,github_user=github_user,github_pass=github_pass,gitssh=gitssh)

def make_bitconfig(require_func=requirements,special_reqs=special_reqs):
    configdic={}
    configdic=check_reqs(require_func,configdic,config_file=True, gitssh=None)
    uhome=expanduser("~")+"/"
    configfile=open(uhome+".bit_config","w+")
    with open(uhome+".bit_config", 'w') as configfile:
        json.dump(configdic, configfile)
    os.chmod(uhome+".bit_config", stat.S_IRWXU )
    print "Your bit config file as been generated:"
    for c in configdic:
        if "pass" not in c:
            print c, configdic.get(c)
            sys.stdout.flush()
        elif configdic.get(c) == None:
            print c, configdic.get(c)
            sys.stdout.flush()
        else:
            print c, "*"
            sys.stdout.flush()

def read_bitconfig(showit=None):
    uhome=expanduser("~")+"/"
    with open(uhome+".bit_config", 'r') as configfile:
        configdic=json.load(configfile)
    if showit:
        for c in configdic:
            if "pass" not in c:
                print c, configdic.get(c)
                sys.stdout.flush()
            elif configdic.get(c) == None:
                print c, configdic.get(c)
                sys.stdout.flush()
            else:
                print c, "*"
                sys.stdout.flush()
    return configdic

def init_user(path_to_project,github_address,github_organization,github_repo,github_user=None,github_pass=None,gitssh=args.gitssh):
    user_name=getpass.getuser()
    response=git_clone(path_to_project+"/scripts."+user_name , github_address, github_organization, github_repo, github_user=github_user, github_pass=github_pass, gitssh=gitssh)
    response=git_clone(path_to_project+"/wiki."+user_name , github_address, github_organization, github_repo+".wiki", github_user=github_user, github_pass=github_pass, gitssh=gitssh)
    while response == 1:
        raw_input("\n\n*************\n\nThe wiki for this project has not yet been created.\n\n Please go to %s/%s/%s/wiki and click on 'Create the first page' and then 'Save Page'.\n\nPress Enter once you have saved the first wiki page.\n\n*************\n\n" %(github_address,github_organization,github_repo) )
        response=git_clone(path_to_project+"/wiki."+user_name ,github_address,github_organization,github_repo+".wiki",github_user=github_user,github_pass=github_pass,gitssh=gitssh)

def list_upload(base_destination,list_of_files):
    upload_dic={}
    subfolders=[base_destination]
    check=base_destination.split("/")
    for i in range(len(check)):
        c="/".join(check[:i-len(check)])
        subfolders.append(c)

    for f in list_of_files:
        full=os.path.abspath(f)
        if os.path.isdir(full):
            subfol=base_destination+"/"+os.path.basename(full)
            subfolders.append(subfol)
            for root, directories, filenames in os.walk(full):
                bad_dirs=[]
                for directory in directories:
                    if os.path.basename(directory)[0] != ".":
                        subdir=os.path.join(root, directory).split(full)[-1]
                        subdir=subfol+subdir
                        subfolders.append(subdir)
                    else:
                        bad_dirs.append(os.path.basename(directory))
                for filename in filenames:
                    if not any(x in filename for x in bad_dirs):
                        subfile=os.path.join(root,filename)
                        if os.path.isfile(subfile):
                            upload_dic[subfile]=subfol+subfile.split(full)[-1]

        elif os.path.isfile(full):
            upload_dic[full]=base_destination+"/"+os.path.basename(full)

    subfolders=list(set(subfolders))
    subfolders=[ xx for xx in subfolders if len(xx) > 0 ]
    subfolders.sort()

    return upload_dic, subfolders

def get_ownCloud_links(link_info,http):
    link_info=str(link_info)
    store=link_info.split("path=")[1].split(",")[0]
    store=store.split("/")
    store="%2F".join(store)
    link=link_info.split("link=")[1].split(",")[0]
    print "\nYour link:\n%s" %http+"/index.php/apps/files?dir="+store
    print "Public link:\n%s\n" %link
    return http+"/index.php/apps/files?dir="+store

def get_owncloud_base_folder(configdic,project_name):

    if args.getfolder:
        if not args.pick_a_date:
            print "--getfolder implies --pick_a_date.\nPlease use -d in combination with -g.\nThank you!"
            sys.exit()
        else:
            base_folder=configdic["owncloud_download_folder"]
    elif args.create_folder:
        base_folder=configdic["owncloud_download_folder"]
    else:
        base_folder=configdic["owncloud_upload_folder"]

    if args.pick_a_date == None:
        d = str(datetime.date.today())
    else:
        d = str(args.pick_a_date)

    if args.subfolder:
        d = d+"/"+str(args.subfolder)

    base_destination=base_folder+"/"+project_name+"/"+d

    return base_destination

def ownCloud_upload(input_files=args.input,message=args.message):

    if type(message) == list:
        message=[ str(xx) for xx in message ]
        message=" ".join(message)
    else:
        message=str(message)

    configdic=read_bitconfig()
    for r in requirements:
        if not args.gitssh:
            while configdic[r] == None:
                configdic=check_reqs([r],configdic,config_file=None, gitssh=None)
        else:
            if r not in [ "github_user", "github_pass"]:
                while configdic[r] == None:
                    configdic=check_reqs([r],configdic,config_file=None, gitssh=args.gitssh)

    local_path=os.path.abspath(configdic["local_path"])

    # check if files all come from the same project folder
    size_local=len(local_path.split("/"))
    parent_folder=[]
    check_project=[]
    for i in input_files:
        f=os.path.abspath(i)
        parent_folder.append(f.split("/")[size_local])
        check_project.append(f.split("/")[size_local+1])
    check_project=list(set(check_project))
    if len(check_project) > 1:
        print "Found more than one project:\n"
        for p in check_project:
            print p
            sys.stdout.flush()
        sys.exit(0)
    else:
        project_name=check_project[0]
        parent_folder=parent_folder[0]

    target_project=parent_folder+"/"+project_name

    base_destination=get_owncloud_base_folder(configdic,target_project)

    upload_dic, subfolders=list_upload(base_destination,input_files)

    # login to owncloud
    try:
        oc=owncloud.Client(configdic["owncloud_address"])
        oc.login(configdic["owncloud_user"],configdic["owncloud_pass"])
    except:
        print "Could not login to ownCloud.\nPlease make sure you are giving the right address to your owncloud and using the right login credentials."
        sys.exit(0)

    # create required subfolders in ownCloud
    for fold in subfolders:
        try:
            oc.file_info(fold)
        except:
            oc.mkdir(fold)

    # Upload files
    if len(upload_dic)>1:
        print "Uploading %s files.." %str(len(upload_dic))
        sys.stdout.flush()
    else:
        print "Uploading %s file.." %str(len(upload_dic))
        sys.stdout.flush()

    skipped_files=[]
    for f in upload_dic:
        file_handle = open(f, 'r', 8192)
        file_handle.seek(0, os.SEEK_END)
        size = file_handle.tell()
        file_handle.seek(0)
        if size == 0:
            skipped_files.append(os.path.basename(f))
            print "\t%s is empty. Skipping .. " %str(f)
            sys.stdout.flush()
            continue
        if size > 1879048192:
            print "\t%s\t(chunked)" %str(upload_dic[f])
            sys.stdout.flush()
            oc.put_file(upload_dic[f],f)
        else:
            print "\t%s" %str(upload_dic[f])
            sys.stdout.flush()
            oc.put_file(upload_dic[f],f,chunked=False)

    print "Finished uploading."
    # Time stamp for expiration date
    tshare = datetime.date.today()
    tshare = tshare + datetime.timedelta(days=int(args.days_to_share))
    tshare = time.mktime(tshare.timetuple())

    link_info = oc.share_file_with_link(base_destination,expiration=tshare)
    private_link=get_ownCloud_links(link_info,configdic["owncloud_address"])

    oc.logout()

    # Go to wiki folder and make a git sync
    print "Logging changes.."
    sys.stdout.flush()
    user_name=getpass.getuser()
    os.chdir(local_path+"/"+target_project+"/wiki."+user_name)
    files_to_add=os.listdir(local_path+"/"+target_project+"/wiki."+user_name)
    git_sync(files_to_add,"bit sync",configdic["github_address"],configdic["github_organization"],project_name+".wiki",github_user=configdic["github_user"],github_pass=configdic["github_pass"],gitssh=args.gitssh)

    # Write log file
    if len(skipped_files) > 0:
        skipped_files=", ".join(skipped_files)
        skipped_files="\n\n(skipped: %s)" %skipped_files
    else:
        skipped_files=""
    logfile="uploads.md"
    logtext="\n\n#####["+base_destination.split("/")[3]+"\t::\t"+user_name+"]("+private_link+") : "+str(" ".join(args.message))+"\n"+str(datetime.datetime.now()).split(".")[0]+", "+str(", ".join(input_files))+skipped_files
    log=open(logfile,"a")
    log.write(logtext)
    log.close()

    #  push the log
    git_add(["uploads.md"])
    git_commit(message)
    git_push(configdic["github_address"],configdic["github_organization"],project_name+".wiki",github_user=configdic["github_user"],github_pass=configdic["github_pass"],gitssh=args.gitssh)

    if args.scripts:
        print "Syncronizing your code.."
        sys.stdout.flush()
        os.chdir(local_path+"/"+target_project+"/scripts."+user_name)
        files_to_add=os.listdir(local_path+"/"+target_project+"/scripts."+user_name)
        git_sync(files_to_add,message,configdic["github_address"],configdic["github_organization"],project_name,github_user=configdic["github_user"],github_pass=configdic["github_pass"],gitssh=args.gitssh)

downloadreqs=["owncloud_address","owncloud_upload_folder",\
"owncloud_download_folder","owncloud_user",\
"owncloud_pass","local_path"]

def ownCloud_download():
    configdic=read_bitconfig()
    for r in downloadreqs:
        while configdic[r] == None:
            configdic=check_reqs([r],configdic,config_file=None, gitssh=args.gitssh)
    local_path=os.path.abspath(configdic["local_path"])

    size_local=len(local_path.split("/"))

    f=os.path.abspath(str(args.pick_a_date))
    parent_folder=f.split("/")[size_local]
    project_name=f.split("/")[size_local+1]

    target_project=parent_folder+"/"+project_name

    base_destination=get_owncloud_base_folder(configdic,target_project)

    # login to owncloud
    try:
        oc=owncloud.Client(configdic["owncloud_address"] )
        oc.login(configdic["owncloud_user"],configdic["owncloud_pass"])
    except:
        print "Could not login to ownCloud.\nPlease make sure you are giving the right address to your owncloud and using the right login credentials."
        sys.exit(0)

    oc.get_directory_as_zip(base_destination, args.pick_a_date+".zip")
    oc.logout()
    print "Downloaded %s.zip" %args.pick_a_date
    sys.stdout.flush()

def ownCloud_create_folder():
    configdic=read_bitconfig()
    for r in downloadreqs:
        while configdic[r] == None:
            configdic=check_reqs([r],configdic,config_file=None, gitssh=args.gitssh)
    local_path=os.path.abspath(configdic["local_path"])

    size_local=len(local_path.split("/"))

    f=os.path.abspath(str(args.pick_a_date))
    parent_folder=f.split("/")[size_local]
    project_name=f.split("/")[size_local+1]

    target_project=parent_folder+"/"+project_name

    base_destination=get_owncloud_base_folder(configdic,target_project)

    # login to owncloud
    try:
        oc=owncloud.Client(configdic["owncloud_address"] )
        oc.login(configdic["owncloud_user"],configdic["owncloud_pass"])
    except:
        print "Could not login to ownCloud.\nPlease make sure you are giving the right address to your owncloud and using the right login credentials."
        sys.exit(0)

    check=base_destination.split("/")
    print check
    for i in range(len(check)+1):
        c="/".join(check[:i])
        print c
        try:
            oc.file_info(c)
        except:
            oc.mkdir(c)

    # Time stamp for expiration date
    tshare = datetime.date.today()
    tshare = tshare + datetime.timedelta(days=int(args.days_to_share))
    tshare = time.mktime(tshare.timetuple())

    link_info = oc.share_file_with_link(base_destination,expiration=tshare)
    private_link=get_ownCloud_links(link_info,configdic["owncloud_address"])

    oc.logout()

if args.config:
    print "Setting up your config file."
    sys.stdout.flush()
    make_bitconfig()
    sys.exit(0)

# initate a project
if args.start:
    configdic=read_bitconfig()
    for r in start_reqs:
        while configdic[r] == None:
            configdic=check_reqs([r],configdic,config_file=None, gitssh=None)
    local_path=os.path.abspath(configdic["local_path"])
    full_path=os.path.abspath(args.start)
    project_name=os.path.basename(full_path)

    # check format projects_folder/group_head/project_name
    checkf=len(local_path.split("/"))
    if len(full_path.split("/")) != len(local_path.split("/"))+2:
        print "The path (%s) to this project does not obey the structure and/or defined local path (%s). Check the reference structure:\n%s" %(full_path,local_path,structure)
        sys.stdout.flush()
        sys.exit(0)

    # have the user rechecking that the the string for the project name is really correct
    checks=None
    while checks not in ["Y","N"]:
        checks=str(raw_input("Is the label %s in agreement with the structure PF_project_name where PF stands for the initials of the Parent_Folder? (Y/N) " %project_name )) or None
    if checks=="N":
        sys.exit(0)

    # create the repo
    github_api=get_github_api(configdic["github_address"])
    github_api=github_api+configdic["github_organization"]+"/repos"
    create_call=["curl","-u",configdic["github_user"]+":"+configdic["github_pass"],github_api,"-d",'{"name":"'+project_name+'","private": "true","auto_init": true }']
    p = Popen(create_call, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
    print p.communicate()[0].rstrip()
    sys.stdout.flush()

    # clone the repo and the wiki by initiating this user
    raw_input("\n\n*************\n\nPlease go to %s/%s/%s/wiki and click on 'Create the first page' and then 'Save Page'.\n\nPress Enter once you have saved the first wiki page.\n\n*************\n\n" %(configdic["github_address"],configdic["github_organization"],project_name) )

    init_user(full_path,configdic["github_address"],configdic["github_organization"],project_name,github_user=configdic["github_user"],github_pass=configdic["github_pass"],gitssh=args.gitssh)

    # create additional folders
    for f in args.stdfolders:
        if not os.path.exists(full_path+"/"+f):
            os.makedirs(full_path+"/"+f)

    sys.exit(0)

if args.adduser:
    configdic=read_bitconfig()
    for r in start_reqs:
        while configdic[r] == None:
            configdic=check_reqs([r],configdic,config_file=None, gitssh=args.gitssh)
    local_path=os.path.abspath(configdic["local_path"])
    if args.start:
        full_path=os.path.abspath(args.start)
    else:
        full_path=os.path.abspath(os.getcwd())
    project_name=os.path.basename(full_path)

    # check format projects_folder/group_head/project_name
    checkf=len(local_path.split("/"))
    if len(full_path.split("/")) != len(local_path.split("/"))+2:
        print "The path (%s) to this project does not obey the structure and/or defined local path (%s). Check the reference structure:\n%s" %(full_path,local_path,structure)
        sys.stdout.flush()
        sys.exit(0)

    init_user(full_path,configdic["github_address"],configdic["github_organization"],project_name,github_user=configdic["github_user"],github_pass=configdic["github_pass"],gitssh=args.gitssh)
    sys.exit(0)

if args.input:
    if not args.message:
        print "ERROR\nYou need to use -m to leave a message in the logs."
        sys.exit()
    ownCloud_upload()
    sys.exit(0)

if args.create_folder:
    ownCloud_create_folder()
    sys.exit(0)

if args.getfolder:
    if args.pick_a_date == None:
        print "--getfolder implies --pick_a_date.\nPlease use -d in combination with -g.\nThank you!"
        sys.exit(0)
    ownCloud_download()
    sys.exit(0)

sys.exit(0)
