#!/usr/bin/env python
import optparse
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from anygit import clisetup, models
from anygit.client import fetch

def main():
    parser = optparse.OptionParser('%prog [options] target')
    parser.add_option('-p', '--packfile', dest='packfile',
                      default=None, help='Use a packfile on the local system')
    parser.add_option('-f', '--force', dest='force', default=False,
                      action='store_true', help='Force indexing to proceed, even if repo is marked as indexing')
    parser.add_option('-b', '--batch', dest='batch', default=None,
                      type='int', help='How many branches to fetch at once (by default, all)')
    parser.add_option('-u', '--unpack', dest='unpack', action='store_true', default=False,
                      help='Unpack first, ask questions later.')
    opts, args = parser.parse_args()
    if len(args) != 1:
        parser.print_help()
        return 1
    target  = args[0]
    r = models.Repository.get_or_create(url=target)
    if r.indexing and opts.force:
        r.indexing = False
        r.save()
    models.flush()
    fetch.fetch_and_index(r, recover_mode=True, packfile=opts.packfile,
                          batch=opts.batch, unpack=opts.unpack)

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