# -*- coding: ascii -*-

###########################################################################
# clive, video extraction utility
# Copyright (C) 2007-2008 Toni Gundogdu
#
# This file is part of clive.
#
# 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 3 of the License, or
# (at your option) any later version.
#
# clive 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 clive.  If not, see <http://www.gnu.org/licenses/>.
###########################################################################

## The classes used for checking for clive updates

__all__ = ['Update']

import clive as _clive
from clive.modules import Modules
from clive.opts import Options

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

    ## Constructor
    def __init__(self, say, proxy):
        self._say = say
        self._opts = Options()._opts
        self._proxy = proxy
        (self._URLGrabber, self._URLGrabError) = \
            Modules().getinst('urlgrabber')

    ## Check for updates
    def check(self):
        try:
            g = self._URLGrabber(user_agent = self._opts.http_agent,
                proxies = self._proxy)
            lines = []
            for ln in g.urlopen(self._check_url).readlines():
                ln = ln.strip('\n')
                if len(ln) > 0: lines.append(ln)
            this = _clive.__version__
            this_release = int(''.join([e.zfill(2) for e in this.split('.')]))
            curr = lines[0]
            curr_release = int(''.join([e.zfill(2) for e in curr.split('.')]))
            if this_release < curr_release:
                self._say('new update is available.')
                a = 'y'
                if self._opts.enable_confirm:
                    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 self._URLGrabError, err:
            self._say('%s [%s]' % (err.strerror,self._check_url), is_error=1)

	
