#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2011 Pavol Rusnak <stick@gk2.sk>
# Copyright (c) 2011 Ionuț Arțăriși <iartarisi@suse.cz>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

import httplib
import os
import platform
import re
import rpm
import smtplib
import time

version             = '0.1'
popcorn_post_server = 'popcorn.opensuse.org'
popcorn_post_uri    = '/popcorn'
popcorn_email       = 'popcorn@popcorn.opensuse.org'
HWUUID_FILE         = '/etc/smolt/hw-uuid'

days_recent = 30
days_voted  = 30

pathre = '^/(bin|boot|lib|lib64|sbin|usr/bin|usr/games|usr/include|usr/lib|usr/lib64|usr/libexec|usr/sbin)/'

system_mounts = ['binfmt_misc', 'debugfs', 'devpts', 'fuse.gvfs-fuse-daemon', 'fusectl', 'nfs', 'nfs4', 'proc', 'rootfs', 'rpc_pipefs', 'securityfs', 'sysfs']

class Statistics:
    arch = platform.machine()
    packages = []

    def fill_packages(self):
        pathreprg = re.compile(pathre)
        now = int(time.time())

        # detect mountpoints that are atime and noatime
        atime_mounts = []
        noatime_mounts = []
        try:
            f = open('/proc/mounts', 'r')
            for line in f:
                mount = line.split(' ', 4)
                if not mount[2] in system_mounts:
                    if mount[3].find('noatime') < 0:
                       atime_mounts.append(mount[1])
                    else:
                       noatime_mounts.append(mount[1])
            f.close()
        except:
            pass

        ts = rpm.TransactionSet()
        mi = ts.dbMatch()
        for h in mi:
            name = h[rpm.RPMTAG_NAME]
            if name == 'gpg-pubkey': continue
            installed = h[rpm.RPMTAG_INSTALLTIME]
            (accessed, atime) = (0, 0)
            if len(atime_mounts) > 0:
                for file in h[rpm.RPMTAG_FILENAMES]:
                    # skip non-watched files
                    if not pathreprg.match(file): continue
                    # if the file is mounted from noatime mountpoint, skip it
                    if len( [i for i in noatime_mounts if file.startswith(i)] ) >  0 and \
                       len( [i for i in   atime_mounts if file.startswith(i)] ) <= 0: continue
                    try:
                        (atime, ) = os.stat(file)[7:8]
                        if atime > accessed:
                            accessed = atime
                    except:
                        pass
            if accessed == 0:
                cat = 'n' # no-files
            else:
                if now - installed < days_recent * 86400:
                    cat = 'r' # recent
                else:
                    if now - accessed < days_voted * 86400:
                        cat = 'v' # voted
                    else:
                        cat ='o' # old
            version = h[rpm.RPMTAG_VERSION] or 'None'
            release = h[rpm.RPMTAG_RELEASE] or 'None'
            arch = h[rpm.RPMTAG_ARCH]
            vendor = h[rpm.RPMTAG_VENDOR] or 'None'
            self.packages.append((cat, name, version, release, arch, vendor))

    def serialize(self):
        ret = [ 'POPCORN %s %s %s' % (version, self.arch, get_system_id()) ]
        for pkg in self.packages:
            ret.append( ' '.join(pkg) )
        ret.append('')
        return '\n'.join(ret)

def get_system_id():
    with open(HWUUID_FILE) as f:
        return f.read().strip()

class Client:
    def __init__(self):
        stats = Statistics()
        stats.fill_packages()
        self.data = stats.serialize()

    def post(self, compress=False):
        """Send a POST request to the default server

        """
        (content_type, body) = multipart(self.data)
        headers = {"Content-Type": content_type,}
        conn = httplib.HTTPConnection(popcorn_post_server)
        conn.request("POST", popcorn_post_uri, body, headers)
        response = conn.getresponse()
        print response.read()

    def write(self):
        print self.data,

def multipart(data):
    """Return multipart content (rfc1341) as one file from data"""
    # we will hopefully not need this anymore in the future:
    # http://bugs.python.org/issue3244
    BOUNDARY = 'gc0p4Jq0M2Yt08jU534c0p'
    CRLF = '\r\n'
    L = []

    L.append('--' + BOUNDARY)
    L.append('Content-Disposition: form-data; '
             'name="popcorn"; filename="popcorn"')
    L.append('Content-Type: text/plain')
    L.append('')
    L.append(data)
    L.append('--'+BOUNDARY+'--')
    L.append('')

    body = CRLF.join(L)
    content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
    return (content_type, body)

enabled = os.environ['POPCORN_ENABLED'] if os.environ.has_key('POPCORN_ENABLED') else None
if enabled and enabled != '0' and enabled != 'false':
    method = os.environ['POPCORN_METHOD'] if os.environ.has_key('POPCORN_METHOD') else None
    client = Client()
    if method == 'email':
        client.email()
    elif method == 'post':
        client.post()
    else:
        client.write()
