# -*- coding: ascii -*-

###########################################################################
# clive, video extraction utility
# Copyright (C) 2007-2008 Toni Gundogdu
#
# clive 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 0.1.2-1307 USA
###########################################################################

## The classes used for checking for clive updates

import sys
import re

import clive as _clive
try:
    from clive.urlgrabber.grabber import URLGrabber, URLGrabError
except ImportError, err:
    raise SystemExit('error: %s' % err)

__all__ = ['Update']


## The class that wraps checking and downloading program updates
class Update:
    _check_url = 'http://dl.gna.org/clive/CURRENT-RELEASE'

    ## Constructor
    # \param self The object pointer
    # \param say The callback method for printing to stdout
    # \param opts The program options
    # \param proxy The program proxy settings
    def __init__(self, say, opts, proxy):
        self._say = say
        self._opts = opts
        self._proxy = proxy

    ## Checks for updates
    #
    # If an update is available, offers to download the source
    # tarball.
    def check(self):
        try:
            g = URLGrabber(
                user_agent = self._opts.http_agent,
                proxies = self._proxy,
                #progress_obj = Progress(self._opts)
            )

            lines = []
            for ln in g.urlopen(self._check_url).readlines():
                ln = ln.strip('\n')
                if len(ln) > 0:
                    lines.append(ln)

            this_release = int(re.sub('[^0-9]', '', _clive.__version_str__))
            curr_release = int(re.sub('[^0-9]', '', lines[0]))

            if this_release < curr_release:
                self._say('new update is available.')
                a = raw_input('download source code tarball? (y/N): ')
                if len(a) > 0 and a.lower()[0] == 'y':
                    filename = lines[1].rsplit('/',1)[1]
                    self._say('write: %s' % filename)
                    file = g.urlgrab(lines[1], filename=filename)
            else:
                self._say('no new updates available.')
        except URLGrabError, err:
            self._say('%s [%s]' % (err.strerror,self._check_url), is_error=1)

	
