#!/usr/bin/python3
#
# Copyright (c) 2017 Red Hat, Inc.
#
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

from __future__ import print_function
from datetime import datetime, timedelta
from optparse import Option, OptionParser
import re
import sys

try:
    import xmlrpclib
except ImportError:
    import xmlrpc.client as xmlrpclib  # pylint: disable=F0401

def processCommandline(argv):
    optionsTable = [
        Option('--idle', action='store', dest='idle',
            help=''),
        Option('--host', action='store', dest='host', default='localhost',
            help=''),
        Option('--username', action='store', dest='username', default='admin',
            help=''),
        Option('--password', action='store', dest='passwd',
            help=''),
        Option('--force', action='store_true', dest='force', default=False,
            help=''),
    ]
    optionParser = OptionParser(
        usage="Usage: %s --idle=<idletime[w|d|h|m]> [--host=<host>] [--username=<username>] [--password=<password>] [--force]" % sys.argv[0],
        option_list=optionsTable)

    options = optionParser.parse_args(argv)[0]

    if not options.idle:
        sys.stderr.write('Need --idle parameter\n')
        sys.exit(1)

    if not options.passwd:
        passwdfile = '/etc/rhn/%s-password' % options.username
        try:
            with open(passwdfile, 'r') as f:
                options.passwd = f.read().splitlines()[0]
        except IOError:
            sys.stderr.write('Error reading password file [%s]: %s\n' % (passwdfile, sys.exc_info()[1]))

    try:
        t, w = re.compile('^(\d+)(\D)$').search(options.idle).groups()
    except AttributeError:
        t = options.idle
        w = 'd'

    try:
        t = int(t)
    except ValueError:
        sys.stderr.write('Unknown idle parameter [%s]\n' % options.idle)
        sys.exit(1)

    if w == 'm':
        options.idle = t * 60
    elif w == 'h':
        options.idle = t * 60 * 60
    elif w == 'd':
        options.idle = t * 60 * 60 * 24
    elif w == 'w':
        options.idle = t * 60 * 60 * 24 * 7
    else:
      sys.stderr.write('Unknown idle parameter [%s]\n' % options.idle)
      sys.exit(1)

    return options

if __name__ == '__main__':
    options = processCommandline(sys.argv)

    not_before = datetime.now() - timedelta(seconds=options.idle)

    print('Lookup on [%s] systems with last checkin before [%s]' % (options.host, not_before))

    client = xmlrpclib.Server('http://%s/rpc/api' % options.host, verbose=0)
    key = client.auth.login(options.username, options.passwd)

    systems = client.system.list_user_systems(key)
    to_delete = []
    for system in systems:
        print('System [%s] id [%s] last checking [%s]' % (system['name'], system['id'], system['last_checkin']), end='')
        if system['last_checkin'] < not_before:
            to_delete.append(system['id'])
            print(' -> delete', end='')
        print()

    if len(to_delete) == 0:
        print('Total systems [%s], none idle' % len(systems))
        sys.exit(0)

    if not options.force:
        print('Total systems [%s], would delete [%s]' % (len(systems), len(to_delete)))
    else:
        client.system.delete_systems(key, to_delete)
        print('All systems deleted')

    client.auth.logout(key)
