#!/usr/bin/python
#
# Copyright (C) 2013 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# usage:
# list-active-service [[service-type [[service-prop1] ... [service-propN]]]]
#     service-type: shill service type: wifi, ethernet, etc
#     service-propX: shill service property: Connectable, Name, etc
#
# Queries the currently active services from shill, optionally filtering
# for specific service types and properties

import dbus, flimflam, sys

def main():
    if len(sys.argv) > 1 and str(sys.argv[1]) in ['-h','-?','--help','-help']:
        print('usage: %s [[service-type [[service-prop1] ... [service-propN]]]]'
            % str(sys.argv[0]))
        return

    flim = flimflam.FlimFlam(dbus.SystemBus())

    for service in flim.GetObjectList('Service'):
        properties = service.GetProperties(utf8_strings = True)
        if not bool(properties['IsActive']):
            continue

        if len(sys.argv) > 1 and str(properties['Type']) != sys.argv[1]:
            continue

        if len(sys.argv) > 2:
            requested_keys = sys.argv[2:]
        else:
            print('[ %s ]' % service.object_path)
            requested_keys = properties.keys()

        for key in requested_keys:
            print('    %s = %s' % (
                    key, flimflam.convert_dbus_value(properties[key], 4)))

if __name__ == '__main__':
    main()