<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import stat
import platform
import re

DOCUMENTATION = """
---
module: sysrc
author: <NAME>
short_description: Manage FreeBSD's rc.conf files through sysrc. Create file if
  not present.
requirements: [ FreeBSD, sysrc ]
version_added: '0.1'
options:
  key:
    required: true
    aliases: [ option, name ]
    description:
    - the key part of a key-value pair to go in a conf file
  value:
    required: false
    aliases: setting
    description:
    - the value to the preceding key-value. Required for C(state=present)
  state:
    required: false
    choices: [ present, absent ]
    default: "present"
    aliases: []
    description:
    - Whether the line should be there or not
  path:
    required: false
    default: "/etc/rc.conf.local"
    aliases: [ dest ]
    description:
    - Specify the file that sysrc should operate on. Created if not present.
"""

EXAMPLES = r"""
- sysrc: key=sshd_enable
    value=YES
    state=present

- sysrc: key=sendmail_enable
    state=absent
"""

class SysrcDummy(object):
  """Dead simple Sysrc hack for when the real one isn't working."""
  def __init__(self, module):
    self.module = module
    self.result = {}
    self.state  = module.params['state']
    self.key    = module.params['key']
    self.value  = module.params['value']
    if module.params['path']:
      self.path = module.params['path']
    else:
      self.path = '/etc/rc.conf.local'
    cmd = [
        '/usr/sbin/sysrc',
        '-f',
        self.path
        ]
    if self.state == 'absent':
      cmd.insert(1, '-x')
      cmd.append(self.key)
    else:
      cmd.insert(1, '-n')
      cmd.append(self.key + '=' + self.value)
    (rc, out, err) = self.module.run_command(cmd)
    if rc is not None and rc != 0 and self.state != 'absent':
      self.module.fail_json(msg="Return code not 0!", err=err, cmd=cmd, rc=rc)

    if self.state == 'present':
      nochange = re.match('{} -> {}'.format(self.value, self.value), out)
      if nochange:
        self.result['changed'] = False
      else:
        self.result['changed'] = True
      if err:
        self.result['stderr'] = err
        self.result['failed'] = True
        self.module.fail_json(msg=err, cmd=cmd, rc=rc)
    else:
      if rc is not None and rc == 0:
        self.result['changed'] = True
      elif rc == 1:
        self.result['changed'] = False
      else:
        self.module.fail_json(msg=err, cmd=cmd, rc=rc)

    module.exit_json(**self.result)
    
class Sysrc(object):

  def check_file(self, path): # See if file is writeable or needs to be created
    try:
      path = os.path.abspath(path)
      if not os.path.isfile(path):
        with open(path, 'w') as f:
          f.writelines('# {}: Created by the sysrc Ansible module\r\r'.format(path))
        if path == '/etc/rc.conf.local':
          st = os.stat('/etc/rc.conf')
          os.chown(path, st.st_uid, st.st_gid)
          os.chmod(path, stat.S_IMODE(st.st_mode))
    except:
      self.module.fail_json(msg="Something failed while making the file!\r",
          errortype      = '{}'.format(sys.exc_info()[0]),
          errorvalue     = '{}'.format(sys.exc_info()[1]),
          errortraceback = '{}'.format(sys.exc_info()[2]),
          )
    return path

  def __init__(self, module):
    self.module = module
    try: # Find sysrc
      self.sysrc_path = self.module.get_bin_path('sysrc', True)
    except:
      self.module.fail_json(msg="Could not find the path for sysrc!")
    self.state  = module.params['state']
    self.key    = module.params['key']
    self.value  = module.params['value']
    print self.module.jsonify(module.params['path'])
    try:
      self.path = self.check_file(module.params['path'])
      if not os.path.isfile(self.path):
        self.module.fail_json(msg='Path returned doesn\'t real', path=self.path)
    except:
      self.module.fail_json(msg='Could not find or create {}'.format(module.params['path']),<commit_msg>sysrc.py: fix new conf file creation, remove Sysrc-dummy<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import stat
import platform
import re

DOCUMENTATION = """
---
module: sysrc
author: <NAME>
short_description: Manage FreeBSD's rc.conf files through sysrc. Create file if
  not present.
requirements: [ FreeBSD, sysrc ]
version_added: '0.1'
options:
  key:
    required: true
    aliases: [ option, name ]
    description:
    - the key part of a key-value pair to go in a conf file
  value:
    required: false
    aliases: setting
    description:
    - the value to the preceding key-value. Required for C(state=present)
  state:
    required: false
    choices: [ present, absent ]
    default: "present"
    aliases: []
    description:
    - Whether the line should be there or not
  path:
    required: false
    default: "/etc/rc.conf.local"
    aliases: [ dest ]
    description:
    - Specify the file that sysrc should operate on. Created if not present.
"""

EXAMPLES = r"""
- sysrc: key=sshd_enable
    value=YES
    state=present

- sysrc: key=sendmail_enable
    state=absent
"""

class Sysrc(object):

  def check_file(self, path): # See if file is writeable or needs to be created
    try:
      path = os.path.abspath(path)
      if not os.path.isfile(path):
        with open(path, 'w') as f:
          f.writelines('# {}: Created by the sysrc Ansible module\n\n'.format(path))
        if path == '/etc/rc.conf.local':
          st = os.stat('/etc/rc.conf')
          os.chown(path, st.st_uid, st.st_gid)
          os.chmod(path, stat.S_IMODE(st.st_mode))
    except:
      self.module.fail_json(msg="Something failed while making the file!\r",
          errortype      = '{}'.format(sys.exc_info()[0]),
          errorvalue     = '{}'.format(sys.exc_info()[1]),
          errortraceback = '{}'.format(sys.exc_info()[2]),
          )
    return path

  def __init__(self, module):
    self.module = module
    try: # Find sysrc
      self.sysrc_path = self.module.get_bin_path('sysrc', True)
    except:
      self.module.fail_json(msg="Could not find the path for sysrc!")
    self.state  = module.params['state']
    self.key    = module.params['key']
    self.value  = module.params['value']
    print self.module.jsonify(module.params['path'])
    try:
      self.path = self.check_file(module.params['path'])
      if not os.path.isfile(self.path):
        self.module.fail_json(msg='Path returned doesn\'t real', path=self.path)
    except:
      self.module.fail_json(msg='Could not find or create {}'.format(module.params['path']),
{'fraction_non_alphanumeric': 0.13971146545178437, 'fraction_numerical': 0.002733485193621868, 'mean_word_length': 2.642699115044248, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2921824', 'n_tokens_mistral': 2195, 'n_tokens_neox': 2157, 'n_words': 560}