This file is indexed.

/usr/bin/seaf-cli is in seafile-cli 6.1.5-1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
#! /usr/bin/python

# pylint: disable=E1121

'''

seaf-cli is command line interface for seafile client.

Subcommands:

    init:             create config files for seafile client
    start:            start and run seafile client as daemon
    stop:             stop seafile client
    list:             list local liraries
    status:           show syncing status
    download:         download a library from seafile server
                          (using libary id)
    download-by-name: download a library from seafile server
                          (using library name)
    sync:             synchronize an existing folder with a library in
                          seafile server
    desync:           desynchronize a library with seafile server
    create:           create a new library


Detail
======

Seafile client stores all its configure information in a config dir. The default location is `~/.ccnet`. All the commands below accept an option `-c <config-dir>`.

init
----
Initialize seafile client. This command initializes the config dir. It also creates sub-directories `seafile-data` and `seafile` under `parent-dir`. `seafile-data` is used to store internal data, while `seafile` is used as the default location put downloaded libraries.

    seaf-cli init [-c <config-dir>] -d <parent-dir>

start
-----
Start seafile client. This command start `ccnet` and `seaf-daemon`, `ccnet` is the network part of seafile client, `seaf-daemon` manages the files.

    seaf-cli start [-c <config-dir>]

stop
----
Stop seafile client.

    seaf-cli stop [-c <config-dir>]


Download by id
--------
Download a library from seafile server (using library id)

    seaf-cli download -l <library-id> -s <seahub-server-url> -d <parent-directory> -u <username> -p <password>


Download by name
--------
Download a library from seafile server (using library name)

    seaf-cli download -L <library-name> -s <seahub-server-url> -d <parent-directory> -u <username> -p <password>


sync
----
Synchronize a library with an existing folder.

    seaf-cli sync -l <library-id> -s <seahub-server-url> -d <existing-folder> -u <username> -p <password>

desync
------
Desynchronize a library from seafile server

    seaf-cli desync -d <existing-folder>

create
------
Create a new library

    seaf-cli create -s <seahub-server-url> -n <library-name> -u <username> -p <password> -t <description> [-e <library-password>]

'''

import argparse
import os
import json
import subprocess
import sys
import time
import getpass
import urllib
import urllib2
from urlparse import urlparse

import ccnet
import seafile

if 'HOME' in os.environ:
    DEFAULT_CONF_DIR = "%s/.ccnet" % os.environ['HOME']
else:
    DEFAULT_CONF_DIR = None

seafile_datadir = None
seafile_worktree = None


def _check_seafile():
    ''' Check ccnet and seafile have been installed '''

    dirs = os.environ['PATH'].split(':')
    def exist_in_path(prog):
        ''' Check whether 'prog' exists in system path '''
        for d in dirs:
            if d == '':
                continue
            path = os.path.join(d, prog)
            if os.path.exists(path):
                return True

    progs = [ 'ccnet', 'ccnet-init', 'seaf-daemon' ]

    for prog in progs:
        if not exist_in_path(prog):
            print "%s not found in PATH. Have you installed seafile?" % prog
            sys.exit(1)


def _config_valid(conf):
    ''' Check config directory valid '''

    if not os.path.exists(conf) or not os.path.isdir(conf):
        print "%s not exists" % conf
        return False

    config_conf = conf + "/ccnet.conf"
    seafile_ini = conf + "/seafile.ini"
    if not os.path.exists(config_conf):
        print "Could not load %s" % config_conf
        return False
    if not os.path.exists(seafile_ini):
        print "Could not load %s" % seafile_ini
        return False

    with open(seafile_ini) as f:
        for line in f:
            global seafile_datadir, seafile_worktree
            seafile_datadir = line.strip()
            seafile_worktree = os.path.join(
                os.path.dirname(seafile_datadir), "seafile")
            break

    if not seafile_datadir or not seafile_worktree:
        print "Could not load seafile_datadir and seafile_worktree"
        return False
    return True


def _conf_dir(args):
    ''' Determine and return the value of conf_dir '''
    conf_dir = DEFAULT_CONF_DIR
    if args.confdir:
        conf_dir = args.confdir
    conf_dir = os.path.abspath(conf_dir)

    if not _config_valid(conf_dir):
        print "Invalid config directory"
        sys.exit(1)
    else:
        return conf_dir


def run_argv(argv, cwd=None, env=None, suppress_stdout=False, suppress_stderr=False):
    '''Run a program and wait it to finish, and return its exit code. The
    standard output of this program is supressed.

    '''
    with open(os.devnull, 'w') as devnull:
        if suppress_stdout:
            stdout = devnull
        else:
            stdout = sys.stdout

        if suppress_stderr:
            stderr = devnull
        else:
            stderr = sys.stderr

        proc = subprocess.Popen(argv,
                                cwd=cwd,
                                stdout=stdout,
                                stderr=stderr,
                                env=env)
        return proc.wait()

def get_env():
    env = dict(os.environ)
    ld_library_path = os.environ.get('SEAFILE_LD_LIBRARY_PATH', '')
    if ld_library_path:
        env['LD_LIBRARY_PATH'] = ld_library_path

    return env

def urlopen(url, data=None, headers=None):
    if data:
        data = urllib.urlencode(data)
    headers = headers or {}
    req = urllib2.Request(url, data=data, headers=headers)
    resp = urllib2.urlopen(req)

    return resp.read()

SEAF_CLI_VERSION = ""

def get_peer_id(conf_dir):
    pool = ccnet.ClientPool(conf_dir)
    ccnet_rpc = ccnet.CcnetRpcClient(pool)
    info = ccnet_rpc.get_session_info()
    return info.id

def get_token(url, username, password, conf_dir):
    platform = 'linux'
    device_id = get_peer_id(conf_dir)
    device_name = 'terminal-' + os.uname()[1]
    client_version = SEAF_CLI_VERSION
    platform_version = ''
    data = {
        'username': username,
        'password': password,
        'platform': platform,
        'device_id': device_id,
        'device_name': device_name,
        'client_version': client_version,
        'platform_version': platform_version,
    }
    token_json = urlopen("%s/api2/auth-token/" % url, data=data)
    tmp = json.loads(token_json)
    token = tmp['token']
    return token

def get_repo_download_info(url, token):
    headers = { 'Authorization': 'Token %s' % token }
    repo_info = urlopen(url, headers=headers)
    return json.loads(repo_info)

def seaf_init(args):
    ''' Initialize config directories'''

    ccnet_conf_dir = DEFAULT_CONF_DIR
    if args.confdir:
        ccnet_conf_dir = args.confdir
    if args.dir:
        seafile_path = args.dir
    else:
        print "Must specify the parent path for put seafile-data"
        sys.exit(0)
    seafile_path = os.path.abspath(seafile_path)

    if os.path.exists(ccnet_conf_dir):
        print "%s already exists" % ccnet_conf_dir
        sys.exit(0)

    cmd = [ "ccnet-init", "-c", ccnet_conf_dir, "-n", "anonymous" ]
    if run_argv(cmd, env=get_env()) != 0:
        print "Failed to init ccnet"
        sys.exit(1)

    if not os.path.exists(seafile_path):
        print "%s not exists" % seafile_path
        sys.exit(0)
    seafile_ini = ccnet_conf_dir + "/seafile.ini"
    seafile_data = seafile_path + "/seafile-data"
    fp = open(seafile_ini, 'w')
    fp.write(seafile_data)
    fp.close()
    print "Writen seafile data directory %s to %s" % (seafile_data, seafile_ini)


def seaf_start_all(args):
    ''' Start ccnet and seafile daemon '''

    seaf_start_ccnet(args)
    # wait ccnet process
    time.sleep(1)
    seaf_start_seafile(args)


def seaf_start_ccnet(args):
    ''' Start ccnet daemon '''

    conf_dir = _conf_dir(args)

    print "Starting ccnet daemon ..."

    cmd = [ "ccnet", "--daemon", "-c", conf_dir ]
    if run_argv(cmd, env=get_env()) != 0:
        print "CCNet daemon failed to start."
        sys.exit(1)

    print "Started: ccnet daemon ..."

def seaf_start_seafile(args):
    ''' start seafile daemon '''

    conf_dir = _conf_dir(args)

    print "Starting seafile daemon ..."

    cmd = [ "seaf-daemon", "--daemon", "-c", conf_dir, "-d", seafile_datadir,
            "-w", seafile_worktree ]
    if run_argv(cmd, env=get_env()) != 0:
        print 'Failed to start seafile daemon'
        sys.exit(1)

    print "Started: seafile daemon ..."

def seaf_stop(args):
    '''Stop seafile daemon '''

    conf_dir = _conf_dir(args)

    pool = ccnet.ClientPool(conf_dir)
    client = pool.get_client()
    try:
        client.send_cmd("shutdown")
    except:
        # ignore NetworkError("Failed to read from socket")
        pass


def seaf_list(args):
    '''List local libraries'''

    conf_dir = _conf_dir(args)

    pool = ccnet.ClientPool(conf_dir)
    seafile_rpc = seafile.RpcClient(pool, req_pool=False)

    repos = seafile_rpc.get_repo_list(-1, -1)
    print "Name\tID\tPath"
    for repo in repos:
        print repo.name, repo.id, repo.worktree


def seaf_list_remote(args):
    '''List remote libraries'''

    conf_dir = _conf_dir(args)

    url = args.server
    if not url:
        print "Seafile server url need to be presented"
        sys.exit(1)

    pool = ccnet.ClientPool(conf_dir)
    seafile_rpc = seafile.RpcClient(pool, req_pool=False)

    username = args.username
    if not username:
        username = raw_input("Enter username: ")
    password = args.password
    if not password:
        password = getpass.getpass("Enter password for user %s : " % username)

    # curl -d 'username=<USERNAME>&password=<PASSWORD>' http://127.0.0.1:8000/api2/auth-token
    token = get_token(url, username, password, conf_dir)

    repos = get_repo_download_info("%s/api2/repos/" % (url), token)

    printed = {}

    print "Name\tID"
    for repo in repos:
        if repo['id'] in printed:
            continue

        printed[repo['id']] = repo['id']
        print repo['name'], repo['id']


def get_base_url(url):
    parse_result = urlparse(url)
    scheme = parse_result.scheme
    netloc = parse_result.netloc

    if scheme and netloc:
        return '%s://%s' % (scheme, netloc)

    return None

def seaf_download(args):
    '''Download a library from seafile server '''

    conf_dir = _conf_dir(args)

    repo = args.library
    if not repo:
        print "Library id is required"
        sys.exit(1)

    url = args.server
    if not url:
        print "Seafile server url need to be presented"
        sys.exit(1)

    download_dir = seafile_worktree
    if args.dir:
        download_dir = os.path.abspath(args.dir)


    pool = ccnet.ClientPool(conf_dir)
    seafile_rpc = seafile.RpcClient(pool, req_pool=False)

    username = args.username
    if not username:
        username = raw_input("Enter username: ")
    password = args.password
    if not password:
        password = getpass.getpass("Enter password for user %s : " % username)

    # curl -d 'username=<USERNAME>&password=<PASSWORD>' http://127.0.0.1:8000/api2/auth-token
    token = get_token(url, username, password, conf_dir)

    tmp = get_repo_download_info("%s/api2/repos/%s/download-info/" % (url, repo), token)

    encrypted = tmp['encrypted']
    magic = tmp.get('magic', None)
    enc_version = tmp.get('enc_version', None)
    random_key = tmp.get('random_key', None)

    clone_token = tmp['token']
    relay_id = tmp['relay_id']
    relay_addr = tmp['relay_addr']
    relay_port = str(tmp['relay_port'])
    email = tmp['email']
    repo_name = tmp['repo_name']
    version = tmp.get('repo_version', 0)

    more_info = None
    base_url = get_base_url(url)
    if base_url:
        more_info = json.dumps({'server_url': base_url})

    print "Starting to download ..."
    print "Library %s will be downloaded to %s" % (repo, download_dir)
    if encrypted == 1:
        repo_passwd = args.libpasswd if args.libpasswd else getpass.getpass("Enter password for the library: ")
    else:
        repo_passwd = None

    seafile_rpc.download(repo,
                         version,
                         relay_id,
                         repo_name.encode('utf-8'),
                         download_dir.encode('utf-8'),
                         clone_token,
                         repo_passwd, magic,
                         relay_addr,
                         relay_port,
                         email, random_key, enc_version, more_info)


def seaf_download_by_name(args):
    '''Download a library defined by name from seafile server'''
    id = None

    conf_dir = _conf_dir(args)

    libraryname = args.libraryname
    if not libraryname:
        print "Library name is required"
        sys.exit(1)

    url = args.server
    if not url:
        print "Seafile server url need to be presented"
        sys.exit(1)

    pool = ccnet.ClientPool(conf_dir)
    seafile_rpc = seafile.RpcClient(pool, req_pool=False)

    username = args.username
    if not username:
        username = raw_input("Enter username: ")
        args.username = username
    password = args.password
    if not password:
        password = getpass.getpass("Enter password for user %s : " % username)
        args.password = password

    # curl -d 'username=<USERNAME>&password=<PASSWORD>' http://127.0.0.1:8000/api2/auth-token
    token = get_token(url, username, password, conf_dir)

    tmp = get_repo_download_info("%s/api2/repos/" % (url), token)

    for i in tmp:
        if libraryname == i['name']:
             id = i['id']

    if not id:
        print "Defined library name not found"
        sys.exit(1)

    args.library = id
    seaf_download(args)


def seaf_sync(args):
    ''' synchronize a library from seafile server '''

    conf_dir = _conf_dir(args)

    repo = args.library
    if not repo:
        print "Library id is required"
        sys.exit(1)

    url = args.server
    if not url:
        print "Seafile server url is required"
        sys.exit(1)

    folder = args.folder
    if not folder:
        print "The local directory is required"
        sys.exit(1)

    folder = os.path.abspath(folder)
    if not os.path.exists(folder):
        print "The local directory does not exists"
        sys.exit(1)

    pool = ccnet.ClientPool(conf_dir)
    seafile_rpc = seafile.RpcClient(pool, req_pool=False)

    username = args.username
    if not username:
        username = raw_input("Enter username: ")
    password = args.password
    if not password:
        password = getpass.getpass("Enter password for user %s : " % username)

    token = get_token(url, username, password, conf_dir)
    tmp = get_repo_download_info("%s/api2/repos/%s/download-info/" % (url, repo), token)

    encrypted = tmp['encrypted']
    magic = tmp.get('magic', None)
    enc_version = tmp.get('enc_version', None)
    random_key = tmp.get('random_key', None)

    clone_token = tmp['token']
    relay_id = tmp['relay_id']
    relay_addr = tmp['relay_addr']
    relay_port = str(tmp['relay_port'])
    email = tmp['email']
    repo_name = tmp['repo_name']
    version = tmp.get('repo_version', 0)

    more_info = None
    base_url = get_base_url(url)
    if base_url:
        more_info = json.dumps({'server_url': base_url})

    print "Starting to download ..."
    if encrypted == 1:
        repo_passwd = args.libpasswd if args.libpasswd else getpass.getpass("Enter password for the library: ")
    else:
        repo_passwd = None

    seafile_rpc.clone(repo,
                      version,
                      relay_id,
                      repo_name.encode('utf-8'),
                      folder,
                      clone_token,
                      repo_passwd, magic,
                      relay_addr,
                      relay_port,
                      email, random_key, enc_version, more_info)


def seaf_desync(args):
    '''Desynchronize a library from seafile server'''

    conf_dir = _conf_dir(args)

    repo_path = args.folder
    if not repo_path:
        print "Must specify the local path of the library"
        sys.exit(1)
    repo_path = os.path.abspath(repo_path)

    pool = ccnet.ClientPool(conf_dir)
    seafile_rpc = seafile.RpcClient(pool, req_pool=False)

    repos = seafile_rpc.get_repo_list(-1, -1)
    repo = None
    for r in repos:
        if r.worktree == repo_path.decode('utf-8'):
            repo = r
            break

    if repo:
        print "Desynchronize %s" % repo.name
        seafile_rpc.remove_repo(repo.id)
    else:
        print "%s is not a library" % args.folder


def seaf_config(args):
    '''Configure the seafile client'''

    conf_dir = _conf_dir(args)

    config_key = args.key
    if not config_key:
        print "Must specify configuration key"
        sys.exit(1)

    config_value = args.value

    pool = ccnet.ClientPool(conf_dir)
    seafile_rpc = seafile.RpcClient(pool, req_pool=False)

    if config_value:
        # set configuration key
        seafile_rpc.seafile_set_config(config_key, config_value)
    else:
        # print configuration key
        val = seafile_rpc.seafile_get_config(config_key)
        print "%s = %s" % (config_key, val)


def seaf_status(args):
    '''Show status'''

    conf_dir = _conf_dir(args)

    pool = ccnet.ClientPool(conf_dir)
    ccnet_rpc = ccnet.CcnetRpcClient(pool, req_pool=False)
    seafile_rpc = seafile.RpcClient(pool, req_pool=False)

    tasks = seafile_rpc.get_clone_tasks()
    print "# Name\tStatus\tProgress"
    for task in tasks:
        if task.state == "fetch":
            tx_task = seafile_rpc.find_transfer_task(task.repo_id)
            print "%s\t%s\t%d/%d, %.1fKB/s" % (task.repo_name, "downloading",
                                        tx_task.block_done, tx_task.block_total,
                                        tx_task.rate/1024.0)
        elif task.state == "checkout":
            checkout_task = seafile_rpc.get_checkout_task(task.repo_id)
            print "%s\t%s\t%d/%d" % (task.repo_name, "checkout",
                                   checkout_task.finished_files,
                                   checkout_task.total_files)
        elif task.state == "error":
            tx_task = seafile_rpc.find_transfer_task(task.repo_id)
            if tx_task:
                err = tx_task.error_str
            else:
                err = task.error_str
            print "%s\t%s\t%s" % (task.repo_name, "error", err)
        elif task.state == 'done':
            # will be shown in repo status
            pass
        else:
            print "%s\t%s" % (task.repo_name, "unknown")

    # show repo status
    print ""
    print "# Name\tStatus"
    repos = seafile_rpc.get_repo_list(-1, -1)
    for repo in repos:
        auto_sync_enabled = seafile_rpc.is_auto_sync_enabled()
        if not auto_sync_enabled or not repo.auto_sync:
            print "%s\t%s" % (repo.name, "auto sync disabled")
            continue

        t = seafile_rpc.get_repo_sync_task(repo.id)
        if not t:
            print "%s\twaiting for sync" % repo.name
        elif t.state == "error":
            print "%s\t%s" % (repo.name, t.error)
        else:
            print "%s\t%s" % (repo.name, t.state)

def create_repo(url, token, args):
    headers = { 'Authorization': 'Token %s' % token }
    data = {
        'name': args.name,
        'desc': args.desc,
    }
    if args.libpasswd:
        data['passwd'] = args.libpasswd
    repo_info_json =  urlopen(url, data=data, headers=headers)
    repo_info = json.loads(repo_info_json)
    return repo_info['repo_id']

def seaf_create(args):
    '''Create a library'''
    conf_dir = DEFAULT_CONF_DIR
    if args.confdir:
        conf_dir = args.confdir
    conf_dir = os.path.abspath(conf_dir)

    # check username and password
    username = args.username
    if not username:
        username = raw_input("Enter username: ")
    password = args.password
    if not password:
        password = getpass.getpass("Enter password for user %s " % username)

    # check url
    url = args.server
    if not url:
        print "Seafile server url need to be presented"
        sys.exit(1)

    # curl -d 'username=<USERNAME>&password=<PASSWORD>' http://127.0.0.1:8000/api2/auth-token
    token = get_token(url, username, password, conf_dir)

    repo_id = create_repo("%s/api2/repos/" % (url), token, args)
    print repo_id


def main():
    ''' Main entry '''

    _check_seafile()

    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(title='subcommands', description='')

    confdir_required = DEFAULT_CONF_DIR is None

    # init
    parser_init = subparsers.add_parser('init', help='Initialize config directory')
    parser_init.set_defaults(func=seaf_init)
    parser_init.add_argument('-c', '--confdir', help='the config directory', type=str, required=confdir_required)
    parser_init.add_argument('-d', '--dir', help='the parent directory to put seafile-data', type=str)

    # start
    parser_start = subparsers.add_parser('start',
                                         help='Start ccnet and seafile daemon')
    parser_start.set_defaults(func=seaf_start_all)
    parser_start.add_argument('-c', '--confdir', help='the config directory', type=str, required=confdir_required)

    # stop
    parser_stop = subparsers.add_parser('stop',
                                         help='Stop ccnet and seafile daemon')
    parser_stop.set_defaults(func=seaf_stop)
    parser_stop.add_argument('-c', '--confdir', help='the config directory', type=str, required=confdir_required)

    # list
    parser_list = subparsers.add_parser('list', help='List local libraries')
    parser_list.set_defaults(func=seaf_list)
    parser_list.add_argument('-c', '--confdir', help='the config directory', type=str, required=confdir_required)

    # list-remote
    parser_download = subparsers.add_parser('list-remote', help='List remote libraries')
    parser_download.set_defaults(func=seaf_list_remote)
    parser_download.add_argument('-c', '--confdir', help='the config directory', type=str, required=confdir_required)
    parser_download.add_argument('-s', '--server', help='URL for seafile server', type=str)
    parser_download.add_argument('-u', '--username', help='username', type=str)
    parser_download.add_argument('-p', '--password', help='password', type=str)

    # status
    parser_status = subparsers.add_parser('status', help='Show syncing status')
    parser_status.set_defaults(func=seaf_status)
    parser_status.add_argument('-c', '--confdir', help='the config directory', type=str, required=confdir_required)

    # download
    parser_download = subparsers.add_parser('download',
                                         help='Download a library from seafile server')
    parser_download.set_defaults(func=seaf_download)
    parser_download.add_argument('-c', '--confdir', help='the config directory', type=str, required=confdir_required)
    parser_download.add_argument('-l', '--library', help='library id', type=str)
    parser_download.add_argument('-s', '--server', help='URL for seafile server', type=str)
    parser_download.add_argument('-d', '--dir', help='the directory to put the library', type=str)
    parser_download.add_argument('-u', '--username', help='username', type=str)
    parser_download.add_argument('-p', '--password', help='password', type=str)
    parser_download.add_argument('-e', '--libpasswd', help='library password', type=str)

    # download-by-name
    parser_download = subparsers.add_parser('download-by-name',
                                         help='Download a library defined by name from seafile server')
    parser_download.set_defaults(func=seaf_download_by_name)
    parser_download.add_argument('-c', '--confdir', help='the config directory', type=str, required=confdir_required)
    parser_download.add_argument('-L', '--libraryname', help='library name', type=str)
    parser_download.add_argument('-s', '--server', help='URL for seafile server', type=str)
    parser_download.add_argument('-d', '--dir', help='the directory to put the library', type=str)
    parser_download.add_argument('-u', '--username', help='username', type=str)
    parser_download.add_argument('-p', '--password', help='password', type=str)
    parser_download.add_argument('-e', '--libpasswd', help='library password', type=str)


    # sync
    parser_sync = subparsers.add_parser('sync',
                                        help='Sync a library with an existing foler')
    parser_sync.set_defaults(func=seaf_sync)
    parser_sync.add_argument('-c', '--confdir', help='the config directory', type=str, required=confdir_required)
    parser_sync.add_argument('-l', '--library', help='library id', type=str)
    parser_sync.add_argument('-s', '--server', help='URL for seafile server', type=str)
    parser_sync.add_argument('-u', '--username', help='username', type=str)
    parser_sync.add_argument('-p', '--password', help='password', type=str)
    parser_sync.add_argument('-d', '--folder', help='the existing local folder', type=str)
    parser_sync.add_argument('-e', '--libpasswd', help='library password', type=str)

    # desync
    parser_desync = subparsers.add_parser('desync',
                                          help='Desync a library with seafile server')
    parser_desync.set_defaults(func=seaf_desync)
    parser_desync.add_argument('-c', '--confdir', help='the config directory', type=str, required=confdir_required)
    parser_desync.add_argument('-d', '--folder', help='the local folder', type=str)

    # create
    parser_create = subparsers.add_parser('create',
                                          help='Create a library')
    parser_create.set_defaults(func=seaf_create)
    parser_create.add_argument('-n', '--name', help='library name', type=str)
    parser_create.add_argument('-t', '--desc', help='library description', type=str)
    parser_create.add_argument('-e', '--libpasswd', help='library password', type=str)
    parser_create.add_argument('-s', '--server', help='URL for seafile server', type=str)
    parser_create.add_argument('-u', '--username', help='username', type=str)
    parser_create.add_argument('-p', '--password', help='password', type=str)
    parser_create.add_argument('-c', '--confdir', help='the config directory', type=str, required=confdir_required)

    # config 
    parser_config = subparsers.add_parser('config',
                                          help='Configure seafile client')
    parser_config.set_defaults(func=seaf_config)
    parser_config.add_argument('-c', '--confdir', help='the config directory', type=str, required=confdir_required)
    parser_config.add_argument('-k', '--key', help='configuration key', type=str)
    parser_config.add_argument('-v', '--value', help='configuration value (if provided, key is set to this value)', type=str, required=False)

    if len(sys.argv) == 1:
        print parser.format_help()
        return

    args = parser.parse_args()
    args.func(args)


if __name__ == '__main__':
    main()