#!/usr/bin/python
# ==============================================================================
#
# pkgupdate_conky.py - Conky client for pkgupdate server.
# Copyright (c) 2010-2012 Spyros Stathopoulos <foucault.online@gmail.com>
#
# pkgupdate 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.
#
# pkgupdate 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, see <http://www.gnu.org/licenses/>.
#
# ==============================================================================

from socket import *
from string import Formatter
from datetime import datetime, date
from optparse import OptionParser
import sys
import json

def get_options_parser():
    parser = OptionParser(add_help_option=False)
    parser.add_option('-?',"--help",action="help",\
        help="Show this message and exit.")
    parser.add_option('-h',"--hot-color",dest="hot_color",\
        action="store",default="EE5500",\
        help="Set the hot color (when updates are available).")
    parser.add_option('-n',"--numerical-only",dest="num_only",\
        action="store_true",default=False,\
        help="Do not use literal expressions (eg. OK).")
    parser.add_option('-w',"--warm-color",dest="warm_color",\
        action="store",default="DDDD00",\
        help="Set the warm color (for warnings etc.).")
    parser.add_option('-c',"--cool-color",dest="cool_color",\
        action="store",default="88CC00",\
        help="Set the cool color (no updates available).")
    parser.add_option('-s',"--socket",dest="socket_name",\
        action="store",default="PkgUpdateSocket",\
        help="The server's socket name.")
    parser.add_option('-p', "--pacman-template",\
        dest="pman_templ", action="store",\
        default="${{color {col}}}{upd:>3}${{color}}",\
        help="Python format string used for pacman updates. "+\
             "Use \"col\" to include color and \"upd\" for the "+\
             "actual number of updates.")
    parser.add_option('-a', "--aur-template",\
        dest="aur_templ", action="store",\
        default="+${{color {col}}}{upd:>2}${{color}}",\
        help="Python format string used for aur updates. "+\
             "Will be dropped if no AUR updates are available. "+\
             "Use \"col\" to include color and \"upd\" for the "+\
             "actual number of updates. Use an empty string "+\
             "to disable the display of AUR updates.")
    return parser

if __name__ == "__main__":
    parser = get_options_parser()
    (options,args) = parser.parse_args(sys.argv)
    colors = {'cool':options.cool_color,'warm':options.warm_color,\
        'hot':options.hot_color}

    sock = socket(AF_UNIX, SOCK_STREAM)
    res = -1
    aur = -1
    try:
        sock.connect("\0%s"%options.socket_name)
        sock.send(b"normal\r\n")
        response = b''
        while True:
            read = sock.recv(128)
            if not read:
                break
            else:
                response += read
        sock.close()
        print(response.decode(), file=sys.stderr)
        response = response.decode()
        data = json.loads(response)
        res = len(data['repos'])
        try:
            aur = len(data['aur'])
        except KeyError:
            pass
    except Exception as exc:
        print("${{color {0}}}ERR${{color}}".format(colors['warm']))
        sys.exit(1)

    res = int(res)
    if res == 0:
        color = colors['cool']
        if options.num_only:
            pman_code = "0"
        else:
            pman_code = "OK"
    elif res == -1:
        color = colors['warm']
        pman_code = "N/A"
    else:
        color = colors['hot']
        pman_code = str(res)
    if (aur != '') and (int(aur) > 0 or options.num_only):
        aur_templ = options.aur_templ
        aur_line = aur_templ.format(col=colors['hot'],upd=aur)
    else:
        aur_line = ""

    pman_templ = options.pman_templ
    pacman_line = pman_templ.format(col=color,upd=pman_code)
    print(pacman_line+aur_line)

# vim: set ts=4:sw=4:et
