#!/usr/bin/python2
# -*- coding: utf-8 -*-

'''Helper script for the Update Notifier Applet.

The script accepts one optional command line argument:
If -v or --verbose is given as argument, some diagnostic information is
printed to stdout, else the script runs quietly.

The script uses "wget --spider" to test if all of the servers in the
sources.list file(s) can be accessed. To pass the test, at least one of the
files Release or InRelease in the server's dists/dist-name directory
must exist.
If all servers are tested ok, returns 0, else returns 1.'''

from commands import getstatusoutput
import os
import sys
import fileinput
import gettext

INSTALLDIR = os.path.abspath(sys.path[0])

if INSTALLDIR.startswith('/usr/local'):
    localepath = '/usr/local/share/locale'
elif INSTALLDIR.startswith('/usr'):
    localepath = '/usr/share/locale'
else:
    localepath = os.path.join(INSTALLDIR, 'locale')
gettext.install('un-applet', localepath, unicode=1)

if sys.argv[2:]:
    print('Too many arguments, aborting.')
    sys.exit(1)

MODE = 'quiet'
if sys.argv[1:]:
    if sys.argv[1] in ('-v', '--verbose'):
        MODE = 'verbose'
    elif sys.argv[1] in ('-q', '--quiet'):
        MODE = 'quiet'
    else:
        print('Unknown argument: "%s", aborting.' % sys.argv[1])
        sys.exit(1)

def which(progname):
    paths = os.getenv('PATH').split(os.pathsep)
    for p in paths:
        full = os.path.join(p, progname)
        if os.path.isfile(full) and os.access(full, os.X_OK):
            return full
    return None

WGET = which('wget')
if not WGET:
    print('No "wget" in "%s", aborting.' % os.getenv('PATH'))
    sys.exit(1)

# a line in sources.list looks like:
# deb http://ftp.de.debian.org/debian/ jessie main contrib non-free
# Use wget to check if we can access at least one of the files:
# http://ftp.de.debian.org/debian/dists/jessie/Release or .../InRelease

# after parsing the sources.list file(s) the all_mirrors list will look like:
# [["<mirror1>/Release", "<mirror1>/InRelease"],...]
all_mirrors = []

def get_mirrors_from_file(filename):
    for line in fileinput.input(filename):
        line = line.strip()
        if not line or line.startswith('#'):
            continue
        l = [x.strip() for x in line.split()]
        if not l[2:]:
            continue# broken line, maybe we should sys.exit(1) here instead?
        if (l[0] == 'deb') and (l[1].split(':')[0] in ('http', 'ftp', 'https')):
            m = os.path.join(l[1], 'dists', l[2])# handles trailing "/" intelligently!
            mirrors = [os.path.join(m, 'Release'), os.path.join(m, 'InRelease')]
            if not mirrors in all_mirrors:
                all_mirrors.append(mirrors)

filenames = ['/etc/apt/sources.list']
if os.path.isdir('/etc/apt/sources.list.d'):
    for f in os.listdir('/etc/apt/sources.list.d'):
        if os.path.splitext(f)[1] == '.list':
            filenames.append(os.path.join('/etc/apt/sources.list.d', f))

for fname in filenames:
    get_mirrors_from_file(fname)

sts = 0
errors = 0
for mirrors in all_mirrors:
    if MODE == 'verbose':
        sys.stdout.write('    %s... ' % os.path.dirname(mirrors[0]))
        sys.stdout.flush()
    sts, out = getstatusoutput('%s --spider "%s"' % (WGET, mirrors[0]))
    if sts:
        sts, out = getstatusoutput('%s --spider "%s"' % (WGET, mirrors[1]))
    if sts:
        if MODE == 'quiet':
            sys.exit(1)
        else:
            errors += 1
            print(_('error'))
    else:
        if MODE == 'verbose':
            print(_('ok'))

if errors == 0:
    sys.exit(0)
else:
    print(u'\n' + _('Error') + u': %d ' % errors + _('mirror server(s) could not be reached.'))
    sys.exit(1)
