#!/usr/bin/python
from __future__ import print_function 

ANSIBLE_METADATA = {
    'metadata_version': '1.0',
    'status': ['preview'],
    'supported_by': 'ISTI-CNR'
}

import glob
import json

import tempfile
import filecmp
import os
import re
from ansible.module_utils.basic import AnsibleModule

def run_configfile_module():
    module = AnsibleModule(
        argument_spec = dict(
            path=dict(required=True),
            key=dict(required=True),
            value=dict(required=True),
            syntax=dict(required=False, choices=['standard', 'shell'], default='standard'),
            )
        )

    path = module.params['path']
    syntax = module.params['syntax']
    key = module.params['key']
    value = module.params['value']

    found = [False]

    def expand(line):
        if syntax == 'standard':
            if re.match("[ #]*%s *=.*" % (key), line):
                found[0] = True
            return re.sub("[ #]*%s *=.*" % (key), "%s = %s" % (key, value), line)
        elif syntax == 'shell':
            if re.match("[ #]*%s *=.*" % (key), line):
                found[0] = True
            return re.sub("[ #]*%s *=.*" % (key), "%s=%s" % (key, value), line)
        else:
            raise Exception("unsupported syntax %s" % syntax)

    changed = False

    with open(path) as input:
        with tempfile.NamedTemporaryFile(dir=os.path.dirname(path)) as temp:
            for line in input:
                print(expand(line), end=' ', file=temp)

            if not found[0]:
                if not line.endswith('\n'):
                    print('', file=temp)
                if syntax == 'standard':
                    print("%s = %s" % (key, value), file=temp)
                elif syntax == 'shell':
                    print("%s=%s" % (key, value), file=temp)
                else:
                    raise Exception("unsupported syntax %s" % syntax)

            temp.delete = False
            temp.close()

            changed = not filecmp.cmp(path, temp.name)
            if changed:
                os.rename(temp.name, path)
            else:
                os.remove(temp.name)

    module.exit_json(changed=changed)

# include magic from lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
def main():
    run_configfile_module()

if __name__ == '__main__':
    main()