#!/usr/bin/python
# arch-tag: program to initialize a Debian package repository
# Copyright (C) 2003 John Goerzen
#               2008 Hubert Chathi
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
#

import os, sys
sys.path.append('/usr/share/tla-buildpackage')
from tbppy import tla, extcmd
from tbppy.versions import print_tbp_version
from vcs_support.commandver import cmd
from vcs_support import commandver
import getopt

def printhelp():
    progname = os.path.basename(sys.argv[0])
    print """Usage: %s [options] archive-name archive-location working-location
Initialize an archive and tree for tla-buildpackage

Where:
  archive-name      is the tla archive name to create
  archive-location  is where the tla data gets stored
  working-location  is where you will check out sources and work with the
                    system

Options:
  --make-archive-args=ARGUMENTS
                 pass ARGUMENTS to tla make-archive
                 e.g.: --signed, to GPG sign the archive contents
  --init-tree-args=ARGUMENTS
                 pass ARGUMENTS to tla init-tree
                 e.g.: --nested, if the working directory is in a directory that
                 is already controlled by tla
  -h, --help     display this help message and exit
  -v, --version  display version information and exit

Example:
  Create an archive named "foo@example.com--debian", stored at ~/arch/debian.
  You will be working on the packages at ~/deve/debian.
  # %s foo@example.com--debian ~/arch/debian ~/devel/debian""" % (progname, progname)

def syntax(code = 0):
    printhelp()
    sys.exit(code)

try:
    options, args = getopt.getopt(sys.argv[1:], 'hv', ['help', 'version',
                                                       'make-archive-args=',
                                                       'init-tree-args='])
except getopt.GetoptError, err:
    print str(err)
    syntax(1)

MAKE_ARCHIVE_ARGS = ''
INIT_TREE_ARGS = ''

for o, a in options:
    if o in ("-h", "--help"):
        syntax()
    elif o in ("-v", "--version"):
        print_tbp_version('tbp-initarchive')
        sys.exit(0)
    elif o in ("--make-archive-args"):
        MAKE_ARCHVE_ARGS = a
    elif o in ("--init-tree-args"):
        INIT_TREE_ARGS = a
    else:
        assert False, "unhandled option: %s" % o

if len(args) != 3:
    syntax(1)

commandver.setscm("tla")

ARCHIVENAME, ARCHIVELOC, WCLOC = args
if WCLOC[0] != '/':
    WCLOC = os.path.join(os.getcwd(),WCLOC)
CONFIGVER = "%s/configs--head--1.0" % ARCHIVENAME
if os.path.exists(ARCHIVELOC):
    print "Archive location %s already exists" % ARCHIVELOC
    sys.exit(2)
if os.path.exists(WCLOC):
    print "Working copy directory %s already exists" % WCLOC
    sys.exit(3)

print "Making working copy location..."
os.mkdir(WCLOC)
os.chdir(WCLOC)

print "Creating archive..."
extcmd.qrun('tla make-archive -l %s "%s" "%s"' % (MAKE_ARCHIVE_ARGS, ARCHIVENAME, ARCHIVELOC))

print "Initializing archive..."
extcmd.qrun('tla archive-setup "%s"' % CONFIGVER)

print "Initializing config tree..."
extcmd.qrun('tla init-tree %s "%s"' % (INIT_TREE_ARGS, CONFIGVER))
extcmd.qrun('tla %s tagline' % cmd().tagging_method)

print "Populating config tree..."
for newdir in ['configs', 'configs/upstream', 'configs/debian']:
    os.mkdir(newdir)
    extcmd.qrun('tla %s %s' % (' '.join(cmd().add), newdir))

print "Importing config tree..."
extcmd.qrun('tla import')

configfilename = os.path.expanduser('~/.tla-buildpackage')
if os.path.exists(configfilename):
    print "%s already exists; not modifying" % configfilename
else:
    print "Generating %s" % configfilename
    fd = open(configfilename, "w")
    fd.write("%s\n" % WCLOC)
    fd.close()

print "Operation successful."
