#!/usr/bin/python3
import os
import io


def account_type(c):
    if c == 'boinc\n':
        return 0
    elif c == 'accManager\n':
        return 1
    #elif c == 'w':
        #return 2
    else:
        return 3


# DEFAULT Setting
os.chdir('/var/lib/boinc')
account = 3
url = 'https://setiathome.berkeley.edu/'
usr = 'dk16801@163.com'
pwd = 'qwer1234'

# Read account info
if(os.path.exists('account.txt')):
    with io.open('account.txt', 'r') as info:
        lines = info.readlines()
        length = len(lines)
        account = account_type(lines[0])
        if(account != 2):
            url = str(lines[1].strip('\n'))
            usr = str(lines[2].strip('\n'))
            pwd = str(lines[3].strip('\n'))
        else:
            url = str(lines[1].strip('\n'))
            key = str(lines[2].strip('\n'))

os.system('sudo /etc/init.d/boinc-client start')

# Connect to BOINC
# Normal Account
if account == 0:
    f = os.popen('boinccmd --lookup_account '+url+' '+usr+' '+pwd)
    lines = f.readlines()
    length = len(lines)
    line = lines[length-1]
    print(line)
    f.close()
    if(line.startswith("a")):
        key = line[13:]
        print(key)
        os.system('boinccmd --project_attach '+url+' '+key)
    else:
        account = 3
# Account Manager
elif account == 1:
    os.system('boinccmd --acct_mgr detach')
    os.system('boinccmd --acct_mgr attach '+url+' '+usr+' '+pwd)
# Weak Account
'''
elif account == 2:
    name = url
    name = name.lstrip('https://')
    name = name.rstrip('/')
    name = name.replace('/','_')
    name = 'account_'+name+'.xml'
    with open(name, 'w') as conf:
        conf.write('<account>\n')
        conf.write('\t<master_url>' + url + '</master_url>\n')
        conf.write('\t<authenticator>' + key + '</authenticator>\n')
        conf.write('</account>')
        conf.close()
    os.system('boinccmd --project_attach '+url+' '+key)
'''
# Default Account
if account == 3:
    f = os.popen('boinccmd --lookup_account '+url+' '+usr+' '+pwd)
    lines = f.readlines()
    length = len(lines)
    line = lines[length-1]
    f.close()
    if(line.startswith("a")):
        key = line[13:]
        os.system('boinccmd --project_attach ' + url + ' ' + key)

