#!/usr/bin/env python
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
# 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.

import subprocess


def main():

    existing_services = set()
    for init_filename in os.listdir('/etc/init.d'):
        if init_filename[0] == '.':
            continue
        existing_services.add(init_filename)
    try:
        initctl_list = subprocess.Popen(['initctl', 'list'],
                                        stdout=subprocess.PIPE)
        for upstart_job in initctl_list.stdout:
            existing_services.add(upstart_job.split(' ', 1)[0])
    except subprocess.CalledProcessError as e:
        if e.errno != 2:
            raise e

    module = AnsibleModule(argument_spec={})
    module.exit_json(ansible_facts={'existing_services':
                                    list(existing_services)})


from ansible.module_utils.basic import *
main()
