#!/usr/bin/env python
# setup.py - Build system for Ubuntu One Storage Protocol package
#
# Copyright 2009 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License version 3,
# as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""setup.py"""

import glob
import os
import sys
import subprocess

sys.path.insert(0, os.path.abspath("."))

from distutils.core import setup
from distutils.spawn import find_executable
from distutils.command import clean, build
from ubuntuone.storageprotocol.context import get_cert_location


class StorageProtocolBuild(build.build):
    """Class to build the protobuf files."""

    description = "build the protocol buffers with protobuf-compiler"

    def run(self):
        """Do the build"""
        protoc = find_executable("protoc")
        if protoc is None:
            sys.stderr.write("*** Cannot find protoc; is the protobuf-compiler"
                             " package installed?\n")
            sys.exit(-1)

        for source in glob.glob('ubuntuone/storageprotocol/*.proto'):
            # glob works with unix and does not like \ in the search path,
            # we use / and correct the issue on windows when appropiate
            if sys.platform == "win32":
                source = source.replace('/', '\\')
            args = (protoc, '--python_out=.', source)
            if subprocess.call(args) != 0:
                sys.exit(-1)

        build.build.run(self)


class StorageProtocolClean(clean.clean):
    """Class to clean up the built protobuf files."""

    description = "clean up files generated by protobuf-compiler"

    def run(self):
        """Do the clean up"""
        for source in \
                glob.glob("ubuntuone/storageprotocol/*_pb2.py"):
            os.unlink(source)

        # Call the parent class clean command
        clean.clean.run(self)


setup(name='ubuntuone-storage-protocol',
      version='4.1.91',
      packages=['ubuntuone',
                'ubuntuone.storageprotocol'],
      extra_path='ubuntuone-storage-protocol',
      data_files=[(get_cert_location(),
                   ['data/UbuntuOne-Go_Daddy_CA.pem',
                    'data/UbuntuOne-ValiCert_Class_2_VA.pem',
                    'data/UbuntuOne-Go_Daddy_Class_2_CA.pem'])],

      cmdclass={'build': StorageProtocolBuild,
                'clean': StorageProtocolClean},
      )
