# -*- coding: utf-8 -*-
# This file is generated, don't edit it. Edit the files in the scripts/ folder.

script_data = [('change_permissions',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import sys\n'
  'import os\n'
  '\n'
  'if len(sys.argv) < 3:\n'
  "    sys.stderr.write(u'Missing parameters'.encode('utf-8'))\n"
  '    exit(2)\n'
  '\n'
  'try:\n'
  '    os.chmod(sys.argv[1], int(sys.argv[2]))\n'
  'except Exception as e:\n'
  "    sys.stderr.write(unicode(e).encode('utf-8'))\n"
  '    exit(3)\n'
  '\n'
  'exit(0)\n'),
 ('delete',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import json\n'
  'import shutil\n'
  'import sys\n'
  '\n'
  'if len(sys.argv) < 3:\n'
  "    sys.stderr.write(u'Missing parameters'.encode('utf-8'))\n"
  '    exit(2)\n'
  '\n'
  'try:\n'
  '    file_list = json.loads(sys.argv[1])\n'
  '    directory_list = json.loads(sys.argv[2])\n'
  'except Exception as e:\n'
  "    sys.stderr.write(unicode(e).encode('utf-8'))\n"
  '    exit(3)\n'
  '\n'
  'if not isinstance(file_list, list) or not isinstance(directory_list, '
  'list):\n'
  "    sys.stderr.write(u'Invalid parameters'.encode('utf-8'))\n"
  '    exit(4)\n'
  '\n'
  'for file_path in file_list:\n'
  '    if os.path.exists(file_path):\n'
  '        try:\n'
  '            os.remove(file_path)\n'
  '        except Exception as e:\n'
  "            sys.stderr.write(unicode(e).encode('utf-8'))\n"
  '            exit(5)\n'
  '\n'
  'for directory_path in directory_list:\n'
  '    if os.path.isdir(directory_path):\n'
  '        try:\n'
  '            shutil.rmtree(directory_path)\n'
  '        except Exception as e:\n'
  "            sys.stderr.write(unicode(e).encode('utf-8'))\n"
  '            exit(6)\n'
  '\n'
  'exit(0)\n'),
 ('export',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import sys\n'
  'import tarfile\n'
  'import tempfile\n'
  '\n'
  'programs = sys.argv[1:]\n'
  '\n'
  'if len(programs) == 0:\n'
  "    sys.stderr.write(u'Missing parameters'.encode('utf-8'))\n"
  '    exit(1)\n'
  '\n'
  'try:\n'
  "    directory = tempfile.mkdtemp(prefix='tfrba-export-')\n"
  "    archive = os.path.join(directory, 'archive.tfrba')\n"
  "    version = os.path.join(directory, 'tfrba-version')\n"
  '\n'
  '    os.chmod(directory, 0o755)\n'
  '\n'
  "    with open(version, 'wb') as f:\n"
  "        f.write('1')\n"
  '\n'
  "    with tarfile.open(archive, 'w:gz') as a:\n"
  "        a.add(version, 'tfrba-version')\n"
  '\n'
  '        for program in programs:\n'
  "            a.add(os.path.join('/', 'home', 'tf', 'programs', program),\n"
  "                  os.path.join('programs', program))\n"
  'except Exception as e:\n'
  "    sys.stderr.write(unicode(e).encode('utf-8'))\n"
  '    exit(2)\n'
  '\n'
  "sys.stdout.write(unicode(directory).encode('utf-8'))\n"
  'exit(0)\n'),
 ('import_directory',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import sys\n'
  'import tempfile\n'
  '\n'
  'try:\n'
  "    directory = tempfile.mkdtemp(prefix='tfrba-import-')\n"
  '    os.chmod(directory, 0o755)\n'
  'except Exception as e:\n'
  "    sys.stderr.write(unicode(e).encode('utf-8'))\n"
  '    exit(2)\n'
  '\n'
  "sys.stdout.write(unicode(directory).encode('utf-8'))\n"
  'exit(0)\n'),
 ('import_extract',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import sys\n'
  'import os\n'
  'import tarfile\n'
  'import tempfile\n'
  '\n'
  'init_script = """#!/bin/sh\n'
  '### BEGIN INIT INFO\n'
  '# Provides:          redapid-program-import\n'
  '# Required-Start:    $remote_fs $syslog\n'
  '# Required-Stop:     $remote_fs $syslog\n'
  '# Default-Start:     2 3 4 5\n'
  '# Default-Stop:      0 1 6\n'
  '# X-Start-Before:    redapid\n'
  '# Short-Description: redapid-program-import\n'
  '# Description:       Finishes RED Brick program import before RED Brick API '
  'Daemon starts\n'
  '### END INIT INFO\n'
  '\n'
  '. /lib/lsb/init-functions\n'
  '\n'
  'case "$1" in\n'
  '  start)\n'
  '\tlog_daemon_msg "Finishing RED Brick program import" '
  '"redapid-program-import"\n'
  '\n'
  '\t{0}\n'
  '\n'
  '\tif [ -x /bin/systemctl ]; then\n'
  '\t\tsystemctl disable redapid-program-import\n'
  '\telse\n'
  '\t\tupdate-rc.d -f redapid-program-import remove\n'
  '\tfi\n'
  '\n'
  '\trm -f /etc/init.d/redapid-program-import\n'
  '\n'
  '\tif [ -x /bin/systemctl ]; then\n'
  '\t\tsystemctl daemon-reload\n'
  '\tfi\n'
  '\n'
  '\tlog_end_msg 0\n'
  '\t;;\n'
  '  stop)\n'
  '\t;;\n'
  '  restart|force-reload)\n'
  '\t;;\n'
  '  status)\n'
  '\t;;\n'
  '  *)\n'
  '\techo "Usage: /etc/init.d/redapid-program-import '
  '{{start|stop|restart|force-reload|status}}" >&2\n'
  '\texit 1\n'
  '\t;;\n'
  'esac\n'
  '\n'
  'exit 0\n'
  '"""\n'
  '\n'
  'if len(sys.argv) < 3:\n'
  "    sys.stderr.write(u'Missing parameters'.encode('utf-8'))\n"
  '    exit(2)\n'
  '\n'
  "archive = os.path.join(sys.argv[1], 'archive.tfrba')\n"
  'programs = sys.argv[2:]\n'
  '\n'
  'try:\n'
  "    with tarfile.open(archive, 'r:gz') as a:\n"
  '        try:\n'
  "            v = a.extractfile('tfrba-version')\n"
  '        except Exception as e:\n'
  "            raise Exception(u'Could not extract tfrba-version: "
  "{0}'.format(e))\n"
  '\n'
  '        version = v.read()\n'
  '        v.close()\n'
  '\n'
  "        if version != '1':\n"
  "            raise Exception(u'Unknown tfrba-version {0}'.format(version))\n"
  '\n'
  '        prefixes = []\n'
  '\n'
  '        for program in programs:\n'
  '            if len(program) > 0:\n'
  "                prefixes.append('programs/' + program + '/')\n"
  '\n'
  '        members = []\n'
  '\n'
  '        for member in a.getmembers():\n'
  '            for prefix in prefixes:\n'
  '                if member.name.startswith(prefix):\n'
  '                    members.append(member)\n'
  '                    break\n'
  '\n'
  "        directory = tempfile.mkdtemp(prefix='extracted-tfrba-import-', "
  "dir='/home/tf')\n"
  '\n'
  '        def is_within_directory(directory, target):\n'
  '            abs_directory = os.path.abspath(directory)\n'
  '            abs_target = os.path.abspath(target)\n'
  '\n'
  '            prefix = os.path.commonprefix([abs_directory, abs_target])\n'
  '\n'
  '            return prefix == abs_directory\n'
  '\n'
  '        def safe_extract(tar, path=".", members=None):\n'
  '            for member in tar.getmembers():\n'
  '                member_path = os.path.join(path, member.name)\n'
  '                if not is_within_directory(path, member_path):\n'
  '                    raise Exception("Attempted Path Traversal in Tar '
  'File")\n'
  '\n'
  '            tar.extractall(path, members)\n'
  '\n'
  '        safe_extract(a, path=directory, members=members)\n'
  '\n'
  '    def fixup(path):\n'
  '        os.chown(path, 1000, 1000)\n'
  '        os.chmod(path, 0o755)\n'
  '\n'
  "    if not os.path.exists('/home/tf/programs'):\n"
  "        os.mkdir('/home/tf/programs')\n"
  "        fixup('/home/tf/programs')\n"
  '\n'
  '    fixup(directory)\n'
  "    fixup(os.path.join(directory, 'programs'))\n"
  '\n'
  '    for program in programs:\n'
  '        if len(program) > 0:\n'
  "            fixup(os.path.join(directory, 'programs', program))\n"
  '\n'
  '    commands = []\n'
  '\n'
  '    for program in programs:\n'
  '        if len(program) > 0:\n'
  "            commands.append('rm -rf "
  "/home/tf/programs/{0}'.format(program))\n"
  "            commands.append('mv {0} "
  "/home/tf/programs/{1}'.format(os.path.join(directory, 'programs', program), "
  'program))\n'
  '\n'
  "    commands.append('rm -rf {0}'.format(directory))\n"
  '\n'
  "    with open('/etc/init.d/redapid-program-import', 'wb') as f:\n"
  "        f.write(init_script.format('\\n\\t'.join(commands)))\n"
  '\n'
  "    os.chmod('/etc/init.d/redapid-program-import', 0o755)\n"
  '\n'
  "    if os.path.isfile('/bin/systemctl'):\n"
  "        if os.system('/bin/systemctl daemon-reload') != 0:\n"
  '            exit(3)\n'
  '\n'
  "        if os.system('/bin/systemctl enable redapid-program-import') != 0:\n"
  '            exit(4)\n'
  '    else:\n'
  "        if os.system('/usr/sbin/update-rc.d redapid-program-import "
  "defaults') != 0:\n"
  '            exit(5)\n'
  'except Exception as e:\n'
  "    sys.stderr.write(unicode(e).encode('utf-8'))\n"
  '    exit(6)\n'
  '\n'
  'exit(0)\n'),
 ('java_main_classes',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import json\n'
  'import os\n'
  'import sys\n'
  'import zlib\n'
  '\n'
  '\n'
  '# -*- coding: utf-8 -*-\n'
  '"""\n'
  'RED Plugin\n'
  'Copyright (C) 2014 Matthias Bolte <matthias@tinkerforge.com>\n'
  '\n'
  'java_utils.py: Java Utils\n'
  '\n'
  'This program is free software; you can redistribute it and/or\n'
  'modify it under the terms of the GNU General Public License\n'
  'as published by the Free Software Foundation; either version 2\n'
  'of the License, or (at your option) any later version.\n'
  '\n'
  'This program is distributed in the hope that it will be useful,\n'
  'but WITHOUT ANY WARRANTY; without even the implied warranty of\n'
  'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n'
  'General Public License for more details.\n'
  '\n'
  'You should have received a copy of the GNU General Public\n'
  'License along with this program; if not, write to the\n'
  'Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n'
  'Boston, MA 02111-1307, USA.\n'
  '"""\n'
  '\n'
  '# totally stripped down version of the python-javatools (LGPL) package\n'
  "# by Christopher O'Brien <obriencj@gmail.com>\n"
  '#\n'
  '# https://github.com/obriencj/python-javatools\n'
  '\n'
  'import zipfile\n'
  'import struct\n'
  '\n'
  'def decode_utf8(value):\n'
  '    try:\n'
  '        return value.decode("utf8")\n'
  '    except UnicodeDecodeError:\n'
  '        return value.replace("\\xC0\\x80", "\\x00").decode("utf8")\n'
  '\n'
  "unpack_B_ = struct.Struct('>B').unpack\n"
  "unpack_H_ = struct.Struct('>H').unpack\n"
  "unpack_i_ = struct.Struct('>i').unpack\n"
  "unpack_q_ = struct.Struct('>q').unpack\n"
  "unpack_f_ = struct.Struct('>f').unpack\n"
  "unpack_d_ = struct.Struct('>d').unpack\n"
  "unpack_BH_ = struct.Struct('>BH').unpack\n"
  "unpack_HI_ = struct.Struct('>HI').unpack\n"
  "unpack_HH_ = struct.Struct('>HH').unpack\n"
  "unpack_HHH_ = struct.Struct('>HHH').unpack\n"
  '\n'
  'unpack_B = lambda f: unpack_B_(f.read(1))[0]\n'
  'unpack_H = lambda f: unpack_H_(f.read(2))[0]\n'
  'unpack_i = lambda f: unpack_i_(f.read(4))[0]\n'
  'unpack_q = lambda f: unpack_q_(f.read(8))[0]\n'
  'unpack_f = lambda f: unpack_f_(f.read(4))[0]\n'
  'unpack_d = lambda f: unpack_d_(f.read(8))[0]\n'
  'unpack_BH = lambda f: unpack_BH_(f.read(3))\n'
  'unpack_HI = lambda f: unpack_HI_(f.read(6))\n'
  'unpack_HH = lambda f: unpack_HH_(f.read(4))\n'
  'unpack_HHH = lambda f: unpack_HHH_(f.read(6))\n'
  '#unpack_utf8 = lambda f: decode_utf8(f.read(unpack_H(f)))\n'
  'unpack_utf8 = lambda f: f.read(unpack_H(f))\n'
  '\n'
  'CONST_UTF8 = 1\n'
  'CONST_INTEGER = 3\n'
  'CONST_FLOAT = 4\n'
  'CONST_LONG = 5\n'
  'CONST_DOUBLE = 6\n'
  'CONST_CLASS = 7\n'
  'CONST_STRING = 8\n'
  'CONST_FIELDREF = 9\n'
  'CONST_METHODREF = 10\n'
  'CONST_INTERFACEMETHODREF = 11\n'
  'CONST_NAMEANDTYPE = 12\n'
  'CONST_MODULEID = 13\n'
  'CONST_METHODHANDLE = 15\n'
  'CONST_METHODTYPE = 16\n'
  'CONST_INVOKEDYNAMIC = 18\n'
  '\n'
  'ACCESS_PUBLIC = 0x0001\n'
  'ACCESS_STATIC = 0x0008\n'
  'ACCESS_PUBLIC_STATIC = ACCESS_PUBLIC | ACCESS_STATIC\n'
  '\n'
  'unpack_cpool_value_by_type = [\n'
  '    None,\n'
  '    unpack_utf8,\n'
  '    None,\n'
  '    unpack_i,\n'
  '    unpack_f,\n'
  '    unpack_q,\n'
  '    unpack_d,\n'
  '    unpack_H,\n'
  '    unpack_H,\n'
  '    unpack_HH,\n'
  '    unpack_HH,\n'
  '    unpack_HH,\n'
  '    unpack_HH,\n'
  '    unpack_BH,\n'
  '    unpack_HH,\n'
  '    unpack_HH,\n'
  '    unpack_H,\n'
  '    None,\n'
  '    unpack_HH\n'
  ']\n'
  '\n'
  'def unpack_cpool(class_file):\n'
  '    count = unpack_H(class_file) - 1\n'
  '    items = [(None, None)]\n'
  '    skip_types = (CONST_LONG, CONST_DOUBLE)\n'
  '    skip = False\n'
  '    main_ref = None\n'
  '\n'
  '    for i in range(count):\n'
  '        if skip:\n'
  '            skip = False\n'
  '            items.append((None, None))\n'
  '        else:\n'
  '            type_ = unpack_B(class_file)\n'
  '            value = unpack_cpool_value_by_type[type_](class_file)\n'
  '\n'
  '            items.append((type_, value))\n'
  '\n'
  '            if main_ref == None and type_ == CONST_UTF8 and value == '
  "'main':\n"
  '                main_ref = i + 1\n'
  '\n'
  '            skip = type_ in skip_types\n'
  '\n'
  '    return items, main_ref\n'
  '\n'
  'def has_main_method(class_file):\n'
  '    # check magic\n'
  "    if class_file.read(4) != '\\xCA\\xFE\\xBA\\xBE':\n"
  '        return None\n'
  '\n'
  '    # skip version\n'
  '    if len(class_file.read(4)) != 4:\n'
  '        return None\n'
  '\n'
  '    # unpack constant pool\n'
  '    cpool, main_ref = unpack_cpool(class_file)\n'
  '\n'
  '    if main_ref == None:\n'
  '        return None\n'
  '\n'
  '    # unpack meta info\n'
  '    access_flags, this_ref, super_ref = unpack_HHH(class_file)\n'
  '\n'
  '    if (access_flags & ACCESS_PUBLIC) != ACCESS_PUBLIC:\n'
  '        return None\n'
  '\n'
  "    class_name = decode_utf8(cpool[cpool[this_ref][1]][1]).replace('/', "
  "'.')\n"
  '\n'
  '    # skip interfaces\n'
  '    interface_count = unpack_H(class_file)\n'
  '\n'
  '    if len(class_file.read(interface_count * 2)) != interface_count * 2:\n'
  '        return None\n'
  '\n'
  '    # skip fields\n'
  '    field_count = unpack_H(class_file)\n'
  '\n'
  '    for i in range(field_count):\n'
  '        access_flags, name_ref, descriptor_ref = unpack_HHH(class_file)\n'
  '\n'
  '        # skip attributes\n'
  '        attribute_count = unpack_H(class_file)\n'
  '\n'
  '        for i in range(attribute_count):\n'
  '            attribute_name, attribute_size = unpack_HI(class_file)\n'
  '\n'
  '            if len(class_file.read(attribute_size)) != attribute_size:\n'
  '                return None\n'
  '\n'
  '    # unpack methods\n'
  '    methods_count = unpack_H(class_file)\n'
  '\n'
  '    for i in range(methods_count):\n'
  '        access_flags, name_ref, descriptor_ref = unpack_HHH(class_file)\n'
  '\n'
  '        if main_ref == name_ref and \\\n'
  '           (access_flags & ACCESS_PUBLIC_STATIC) == ACCESS_PUBLIC_STATIC '
  'and \\\n'
  "           cpool[descriptor_ref][1] == '([Ljava/lang/String;)V':\n"
  '            return class_name\n'
  '\n'
  '        # skip attributes\n'
  '        attribute_count = unpack_H(class_file)\n'
  '\n'
  '        for i in range(attribute_count):\n'
  '            attribute_name, attribute_size = unpack_HI(class_file)\n'
  '\n'
  '            if len(class_file.read(attribute_size)) != attribute_size:\n'
  '                return None\n'
  '\n'
  '    return None\n'
  '\n'
  'def get_jar_file_main_classes(filename, abort_ref=None):\n'
  '    if abort_ref == None:\n'
  '        abort_ref = [False]\n'
  '\n'
  "    with zipfile.ZipFile(filename, 'r') as jar_file:\n"
  '        main_classes = []\n'
  '\n'
  '        for entry in jar_file.namelist():\n'
  '            if abort_ref[0]:\n'
  '                break\n'
  '\n'
  "            if not entry.endswith('.class'):\n"
  '                continue\n'
  '\n'
  "            class_file = jar_file.open(entry, 'r')\n"
  '            class_name = has_main_method(class_file)\n'
  '\n'
  '            if class_name != None:\n'
  '                main_classes.append(class_name)\n'
  '\n'
  '            class_file.close()\n'
  '\n'
  '        return main_classes\n'
  '\n'
  'def get_class_file_main_classes(filename):\n'
  "    with open(filename, 'r') as class_file:\n"
  '        class_name = has_main_method(class_file)\n'
  '\n'
  '        if class_name != None:\n'
  '            return [class_name]\n'
  '        else:\n'
  '            return []\n'
  '\n'
  '\n'
  'result = {}\n'
  '\n'
  'if len(sys.argv) < 2 or not os.path.isdir(sys.argv[1]):\n'
  "    sys.stderr.write(u'Missing or invalid parameters'.encode('utf-8'))\n"
  '    exit(2)\n'
  '\n'
  'base = sys.argv[1]\n'
  '\n'
  'try:\n'
  '    for root, directories, files in os.walk(base):\n'
  '        relative_root = os.path.relpath(root, base)\n'
  '\n'
  '        for filename in files:\n'
  "            if filename.endswith('.jar'):\n"
  '                absolute = os.path.join(root, filename)\n'
  '\n'
  '                try:\n'
  '                    classes = get_jar_file_main_classes(absolute)\n'
  '                except:\n'
  '                    continue\n'
  '\n'
  '                relative = os.path.join(relative_root, filename)\n'
  '\n'
  '                for cls in classes:\n'
  '                    result.setdefault(cls, []).append(relative)\n'
  "            elif filename.endswith('.class'):\n"
  '                try:\n'
  '                    classes = '
  'get_class_file_main_classes(os.path.join(root, filename))\n'
  '                except:\n'
  '                    continue\n'
  '\n'
  '                for cls in classes:\n'
  '                    result.setdefault(cls, []).append(relative_root)\n'
  'except Exception as e:\n'
  "    sys.stderr.write(unicode(e).encode('utf-8'))\n"
  '    exit(3)\n'
  '\n'
  "sys.stdout.write(zlib.compress(json.dumps(result, separators=(',', ':'))))\n"
  'exit(0)\n'),
 ('openhab_configs_list',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import sys\n'
  'import json\n'
  'from distutils.version import StrictVersion\n'
  '\n'
  'IMAGE_VERSION = None\n'
  "MIN_VERSION_WITH_OPENHAB2 = StrictVersion('1.10')\n"
  '\n'
  "with open('/etc/tf_image_version', 'r') as f:\n"
  "    IMAGE_VERSION = StrictVersion(f.read().split(' ')[0].strip())\n"
  '\n'
  "result = {'items': [], 'sitemaps': [], 'rules': [], 'persistence': [], "
  "'scripts': [], 'transform': []}\n"
  '\n'
  'try:\n'
  '    if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_OPENHAB2:\n'
  "        for name in os.listdir('/etc/openhab2/items/'):\n"
  "            if name.endswith('.items'):\n"
  "                result['items'].append(name)\n"
  '    else:\n'
  "        for name in os.listdir('/etc/openhab/configurations/items/'):\n"
  "            if name.endswith('.items'):\n"
  "                result['items'].append(name)\n"
  '\n'
  '    if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_OPENHAB2:\n'
  "        for name in os.listdir('/etc/openhab2/sitemaps/'):\n"
  "            if name.endswith('.sitemap'):\n"
  "                result['sitemaps'].append(name)\n"
  '    else:\n'
  "        for name in os.listdir('/etc/openhab/configurations/sitemaps/'):\n"
  "            if name.endswith('.sitemap'):\n"
  "                result['sitemaps'].append(name)\n"
  '\n'
  '    if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_OPENHAB2:\n'
  "        for name in os.listdir('/etc/openhab2/rules/'):\n"
  "            if name.endswith('.rules'):\n"
  "                result['rules'].append(name)\n"
  '    else:\n'
  "        for name in os.listdir('/etc/openhab/configurations/rules/'):\n"
  "            if name.endswith('.rules'):\n"
  "                result['rules'].append(name)\n"
  '\n'
  '    if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_OPENHAB2:\n'
  "        for name in os.listdir('/etc/openhab2/persistence/'):\n"
  "            if name.endswith('.persist'):\n"
  "                result['persistence'].append(name)\n"
  '    else:\n'
  '        for name in '
  "os.listdir('/etc/openhab/configurations/persistence/'):\n"
  "            if name.endswith('.persist'):\n"
  "                result['persistence'].append(name)\n"
  '\n'
  '    if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_OPENHAB2:\n'
  "        for name in os.listdir('/etc/openhab2/scripts/'):\n"
  "            if name.endswith('.script'):\n"
  "                result['scripts'].append(name)\n"
  '    else:\n'
  "        for name in os.listdir('/etc/openhab/configurations/scripts/'):\n"
  "            if name.endswith('.script'):\n"
  "                result['scripts'].append(name)\n"
  '\n'
  '    if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_OPENHAB2:\n'
  "        for name in os.listdir('/etc/openhab2/transform/'):\n"
  "            if name.endswith('.transform'):\n"
  "                result['transform'].append(name)\n"
  '    else:\n'
  "        for name in os.listdir('/etc/openhab/configurations/transform/'):\n"
  "            if name.endswith('.transform'):\n"
  "                result['transform'].append(name)\n"
  '\n'
  'except Exception as e:\n'
  "    sys.stderr.write(unicode(e).encode('utf-8'))\n"
  '    exit(2)\n'
  '\n'
  "sys.stdout.write(json.dumps(result, separators=(',', ':')))\n"
  'exit(0)\n'),
 ('openhab_set_configs_ownership',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import sys\n'
  'import pwd\n'
  'import grp\n'
  'from distutils.version import StrictVersion\n'
  '\n'
  'IMAGE_VERSION = None\n'
  "MIN_VERSION_WITH_OPENHAB2 = StrictVersion('1.10')\n"
  '\n'
  "with open('/etc/tf_image_version', 'r') as f:\n"
  "    IMAGE_VERSION = StrictVersion(f.read().split(' ')[0].strip())\n"
  '\n'
  'try:\n'
  '    if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_OPENHAB2:\n'
  "        for name in os.listdir('/etc/openhab2/services/'):\n"
  "            if name.endswith('.cfg'):\n"
  "                os.chown(os.path.join('/etc/openhab2/services/', name),\n"
  "                         pwd.getpwnam('openhab').pw_uid,\n"
  "                         grp.getgrnam('openhab').gr_gid)\n"
  '\n'
  "        for name in os.listdir('/var/lib/openhab2/etc/'):\n"
  "            if name.endswith('.cfg'):\n"
  "                os.chown(os.path.join('/var/lib/openhab2/etc/', name),\n"
  "                         pwd.getpwnam('openhab').pw_uid,\n"
  "                         grp.getgrnam('openhab').gr_gid)\n"
  '    else:\n'
  "        for name in os.listdir('/etc/openhab/configurations/'):\n"
  "            if name.endswith('.cfg'):\n"
  "                os.chown(os.path.join('/etc/openhab/configurations/', "
  'name),\n'
  "                         pwd.getpwnam('openhab').pw_uid,\n"
  "                         grp.getgrnam('openhab').gr_gid)\n"
  '\n'
  "        for name in os.listdir('/etc/openhab/'):\n"
  "            if name.endswith('.xml'):\n"
  "                os.chown(os.path.join('/etc/openhab/', name),\n"
  "                         pwd.getpwnam('openhab').pw_uid,\n"
  "                         grp.getgrnam('openhab').gr_gid)\n"
  '\n'
  '    if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_OPENHAB2:\n'
  "        for name in os.listdir('/etc/openhab2/items/'):\n"
  "            if name.endswith('.items'):\n"
  "                os.chown(os.path.join('/etc/openhab2/items/', name),\n"
  "                         pwd.getpwnam('openhab').pw_uid,\n"
  "                         grp.getgrnam('openhab').gr_gid)\n"
  '    else:\n'
  "        for name in os.listdir('/etc/openhab/configurations/items/'):\n"
  "            if name.endswith('.items'):\n"
  "                os.chown(os.path.join('/etc/openhab/configurations/items/', "
  'name),\n'
  "                         pwd.getpwnam('openhab').pw_uid,\n"
  "                         grp.getgrnam('openhab').gr_gid)\n"
  '\n'
  '    if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_OPENHAB2:\n'
  "        for name in os.listdir('/etc/openhab2/sitemaps/'):\n"
  "            if name.endswith('.sitemap'):\n"
  "                os.chown(os.path.join('/etc/openhab2/sitemaps/', name),\n"
  "                         pwd.getpwnam('openhab').pw_uid,\n"
  "                         grp.getgrnam('openhab').gr_gid)\n"
  '    else:\n'
  "        for name in os.listdir('/etc/openhab/configurations/sitemaps/'):\n"
  "            if name.endswith('.sitemap'):\n"
  '                '
  "os.chown(os.path.join('/etc/openhab/configurations/sitemaps/', name),\n"
  "                         pwd.getpwnam('openhab').pw_uid,\n"
  "                         grp.getgrnam('openhab').gr_gid)\n"
  '\n'
  '    if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_OPENHAB2:\n'
  "        for name in os.listdir('/etc/openhab2/rules/'):\n"
  "            if name.endswith('.rules'):\n"
  "                os.chown(os.path.join('/etc/openhab2/rules/', name),\n"
  "                         pwd.getpwnam('openhab').pw_uid,\n"
  "                         grp.getgrnam('openhab').gr_gid)\n"
  '    else:\n'
  "        for name in os.listdir('/etc/openhab/configurations/rules/'):\n"
  "            if name.endswith('.rules'):\n"
  "                os.chown(os.path.join('/etc/openhab/configurations/rules/', "
  'name),\n'
  "                         pwd.getpwnam('openhab').pw_uid,\n"
  "                         grp.getgrnam('openhab').gr_gid)\n"
  '\n'
  '    if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_OPENHAB2:\n'
  "        for name in os.listdir('/etc/openhab2/persistence/'):\n"
  "            if name.endswith('.persist'):\n"
  "                os.chown(os.path.join('/etc/openhab2/persistence/', name),\n"
  "                         pwd.getpwnam('openhab').pw_uid,\n"
  "                         grp.getgrnam('openhab').gr_gid)\n"
  '    else:\n'
  '        for name in '
  "os.listdir('/etc/openhab/configurations/persistence/'):\n"
  "            if name.endswith('.persist'):\n"
  '                '
  "os.chown(os.path.join('/etc/openhab/configurations/persistence/', name),\n"
  "                         pwd.getpwnam('openhab').pw_uid,\n"
  "                         grp.getgrnam('openhab').gr_gid)\n"
  '\n'
  '    if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_OPENHAB2:\n'
  "        for name in os.listdir('/etc/openhab2/scripts/'):\n"
  "            if name.endswith('.script'):\n"
  "                os.chown(os.path.join('/etc/openhab2/scripts/', name),\n"
  "                         pwd.getpwnam('openhab').pw_uid,\n"
  "                         grp.getgrnam('openhab').gr_gid)\n"
  '    else:\n'
  "        for name in os.listdir('/etc/openhab/configurations/scripts/'):\n"
  "            if name.endswith('.script'):\n"
  '                '
  "os.chown(os.path.join('/etc/openhab/configurations/scripts/', name),\n"
  "                         pwd.getpwnam('openhab').pw_uid,\n"
  "                         grp.getgrnam('openhab').gr_gid)\n"
  '\n'
  '    if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_OPENHAB2:\n'
  "        for name in os.listdir('/etc/openhab2/transform/'):\n"
  "            if name.endswith('.transform'):\n"
  "                os.chown(os.path.join('/etc/openhab2/transform/', name),\n"
  "                         pwd.getpwnam('openhab').pw_uid,\n"
  "                         grp.getgrnam('openhab').gr_gid)\n"
  '    else:\n'
  "        for name in os.listdir('/etc/openhab/configurations/transform/'):\n"
  "            if name.endswith('.transform'):\n"
  '                '
  "os.chown(os.path.join('/etc/openhab/configurations/transform/', name),\n"
  "                         pwd.getpwnam('openhab').pw_uid,\n"
  "                         grp.getgrnam('openhab').gr_gid)\n"
  '\n'
  'except Exception as e:\n'
  "    sys.stderr.write(unicode(e).encode('utf-8'))\n"
  '    exit(2)\n'
  '\n'
  'exit(0)\n'),
 ('overview',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import psutil\n'
  'import sys\n'
  'import json\n'
  'import zlib\n'
  'import os\n'
  '\n'
  'if psutil.version_info >= (2, 1, 0): # image version >= 1.4 (jessie)\n'
  '    def get_cmdline(p):\n'
  '        return p.cmdline()\n'
  '    def get_name(p):\n'
  '        return p.name()\n'
  '    def get_username(p):\n'
  '        return p.username()\n'
  'else: # image version < 1.4 (wheezy)\n'
  '    def get_cmdline(p):\n'
  '        return p.cmdline\n'
  '    def get_name(p):\n'
  '        return p.name\n'
  '    def get_username(p):\n'
  '        return p.username\n'
  '\n'
  'result = {}\n'
  '\n'
  'with open("/proc/uptime", "r") as utf:\n'
  '    result[\'uptime\'] = utf.readline().split(".")[0]\n'
  '\n'
  'du = psutil.disk_usage("/")\n'
  '\n'
  'all_process_info = []\n'
  '\n'
  'for p in psutil.process_iter(): # update CPU usage info\n'
  '    try:\n'
  '        if psutil.version_info >= (5, 0, 1):\n'
  '            p.cpu_percent(interval=0)\n'
  '        else:\n'
  '            p.get_cpu_percent(interval=0)\n'
  '    except:\n'
  '        pass\n'
  '\n'
  'if len(sys.argv) < 2:\n'
  "    result['cpu_used'] = psutil.cpu_percent(1)\n"
  'else:\n'
  "    result['cpu_used'] = psutil.cpu_percent(float(sys.argv[1]))\n"
  '\n'
  'all_process_info = []\n'
  'own_pid = os.getpid()\n'
  'for p in psutil.process_iter():\n'
  '    try:\n'
  '        if p.pid == own_pid:\n'
  '            continue\n'
  '\n'
  '        if psutil.version_info >= (5, 0, 1):\n'
  "            process_dict = {'cmd': ' '.join(get_cmdline(p)),\n"
  "                            'name': get_name(p),\n"
  "                            'pid': p.pid,\n"
  "                            'user': get_username(p),\n"
  "                            'cpu': int(p.cpu_percent(interval=0) * 10),\n"
  "                            'mem': int(p.memory_percent() * 10)}\n"
  '        else:\n'
  "            process_dict = {'cmd': ' '.join(get_cmdline(p)),\n"
  "                            'name': get_name(p),\n"
  "                            'pid': p.pid,\n"
  "                            'user': get_username(p),\n"
  "                            'cpu': int(p.get_cpu_percent(interval=0) * "
  '10),\n'
  "                            'mem': int(p.get_memory_percent() * 10)}\n"
  '    except:\n'
  '        continue\n'
  '\n'
  '    all_process_info.append(process_dict)\n'
  '\n'
  "result['processes'] = all_process_info\n"
  '\n'
  'if psutil.version_info >= (5, 0, 1):\n'
  '    mem_info = psutil.virtual_memory()\n'
  "    result['mem_used'] = mem_info.used\n"
  "    result['mem_total'] = mem_info.total\n"
  'else:\n'
  "    result['mem_used'] = psutil.used_phymem() - psutil.phymem_buffers() - "
  'psutil.cached_phymem()\n'
  "    result['mem_total'] = psutil.TOTAL_PHYMEM\n"
  '\n'
  "result['disk_used'] = du.used\n"
  "result['disk_total'] = du.total\n"
  '\n'
  'if psutil.version_info >= (5, 0, 1):\n'
  '    interfaces = psutil.net_io_counters(pernic=True)\n'
  'else:\n'
  '    interfaces = psutil.network_io_counters(pernic=True)\n'
  '\n'
  "if 'tunl0' in interfaces: # ignore tunl0 interface\n"
  "    del interfaces['tunl0']\n"
  '\n'
  "result['ifaces'] = interfaces\n"
  '\n'
  "sys.stdout.write(zlib.compress(json.dumps(result, separators=(',', "
  "':'))))\n"),
 ('program_logs_list',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import json\n'
  'import os\n'
  'import stat\n'
  'import sys\n'
  'import zlib\n'
  '\n'
  'result = {}\n'
  '\n'
  'if len(sys.argv) < 2 or not os.path.isdir(sys.argv[1]):\n'
  "    sys.stderr.write(u'Missing or invalid parameters'.encode('utf-8'))\n"
  '    exit(2)\n'
  '\n'
  'base = sys.argv[1]\n'
  '\n'
  'try:\n'
  '    for name in os.listdir(base):\n'
  "        if not name.endswith('_stdout.log') and not "
  "name.endswith('_stderr.log'):\n"
  '            continue\n'
  '\n'
  '        st = os.lstat(os.path.join(base, name))\n'
  '\n'
  '        if stat.S_ISREG(st.st_mode):\n'
  '            result[name] = st.st_size\n'
  'except Exception as e:\n'
  "    sys.stderr.write(unicode(e).encode('utf-8'))\n"
  '    exit(3)\n'
  '\n'
  "sys.stdout.write(zlib.compress(json.dumps(result, separators=(',', ':'))))\n"
  'exit(0)\n'),
 ('rename',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import sys\n'
  'import os\n'
  '\n'
  'if len(sys.argv) < 3:\n'
  "    sys.stderr.write(u'Missing parameters'.encode('utf-8'))\n"
  '    exit(2)\n'
  '\n'
  'try:\n'
  '    os.rename(sys.argv[1], sys.argv[2])\n'
  'except Exception as e:\n'
  "    sys.stderr.write(unicode(e).encode('utf-8'))\n"
  '    exit(3)\n'
  '\n'
  'exit(0)\n'),
 ('restart_reboot_shutdown_systemd',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import sys\n'
  'import traceback\n'
  'from sys import argv\n'
  'from distutils.version import StrictVersion\n'
  '\n'
  'CMD_REBOOT = "1"\n'
  'CMD_SHUTDOWN = "2"\n'
  'IMAGE_VERSION = None\n'
  'MIN_VERSION_WITH_SYSTEMD = StrictVersion("1.4")\n'
  '\n'
  'with open("/etc/tf_image_version", "r") as f:\n'
  "    IMAGE_VERSION = StrictVersion(f.read().split(' ')[0].strip())\n"
  '\n'
  'if len(argv) != 2:\n'
  "    sys.stderr.write(u'Invalid number of arguments "
  "provided'.encode('utf-8'))\n"
  '    exit(1)\n'
  '\n'
  'try:\n'
  '    if argv[1] == CMD_REBOOT:\n'
  '        if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_SYSTEMD:\n'
  '            os.system("/bin/systemctl reboot &> /dev/null")\n'
  '        else:\n'
  '            os.system("/sbin/init 6 &> /dev/null")\n'
  '    elif argv[1] == CMD_SHUTDOWN:\n'
  '        if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_SYSTEMD:\n'
  '            os.system("/bin/systemctl poweroff &> /dev/null")\n'
  '        else:\n'
  '            os.system("/sbin/halt &> /dev/null")\n'
  '    else:\n'
  "        sys.stderr.write(u'Unknown command'.encode('utf-8'))\n"
  '        exit(1)\n'
  'except :\n'
  '    traceback.print_exc()\n'
  '    exit(1)\n'),
 ('settings_ap_apply',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import json\n'
  'import StringIO\n'
  'import traceback\n'
  'import netifaces\n'
  'import subprocess\n'
  'import ConfigParser\n'
  'from sys import argv\n'
  'from distutils.version import StrictVersion\n'
  '\n'
  'IMAGE_VERSION = None\n'
  "MIN_VERSION_FOR_NAT = StrictVersion('1.7')\n"
  "MIN_VERSION_WITH_NM = StrictVersion('1.10')\n"
  "MIN_VERSION_FOR_HOSTAPD_UPDATE_1 = StrictVersion('1.10')\n"
  '\n'
  "with open('/etc/tf_image_version', 'r') as f:\n"
  "    IMAGE_VERSION = StrictVersion(f.read().split(' ')[0].strip())\n"
  '\n'
  "PY_SETUP_AP_NAT = '''\n"
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*\n'
  '\n'
  'import os\n'
  'import dbus\n'
  'import ConfigParser\n'
  'from xml.dom import minidom\n'
  '\n'
  "DBUS_MM_BUS_NAME = 'org.freedesktop.ModemManager1'\n"
  "DBUS_MM_OBJECT_PATH = '/org/freedesktop/ModemManager1'\n"
  "DBUS_MM_SIM_INTERFACE = 'org.freedesktop.ModemManager1.Sim'\n"
  "DBUS_PROPERTIES_INTERFACE = 'org.freedesktop.DBus.Properties'\n"
  "DBUS_MM_MODEM_INTERFACE = 'org.freedesktop.ModemManager1.Modem'\n"
  "DBUS_MM_BEARER_INTERFACE = 'org.freedesktop.ModemManager1.Bearer'\n"
  "DBUS_MM_MODEM_OBJECT_PATH = '/org/freedesktop/ModemManager1/Modem'\n"
  "DBUS_INTROSPECTABLE_INTERFACE = 'org.freedesktop.DBus.Introspectable'\n"
  'DBUS_MM_MODEM_SIMPLE_INTERFACE = '
  "'org.freedesktop.ModemManager1.Modem.Simple'\n"
  '\n'
  "DBUS_NM_BUS_NAME = 'org.freedesktop.NetworkManager'\n"
  "DBUS_NM_INTERFACE = 'org.freedesktop.NetworkManager'\n"
  "DBUS_NM_OBJECT_PATH = '/org/freedesktop/NetworkManager'\n"
  "DBUS_PROPERTIES_INTERFACE = 'org.freedesktop.DBus.Properties'\n"
  "DBUS_NM_DEVICE_INTERFACE = 'org.freedesktop.NetworkManager.Device'\n"
  "DBUS_NM_AP_INTERFACE = 'org.freedesktop.NetworkManager.AccessPoint'\n"
  "DBUS_NM_SETTINGS_INTERFACE = 'org.freedesktop.NetworkManager.Settings'\n"
  "DBUS_NM_SETTINGS_OBJECT_PATH = '/org/freedesktop/NetworkManager/Settings'\n"
  'DBUS_NM_DEVICE_WIRELESS_INTERFACE = '
  "'org.freedesktop.NetworkManager.Device.Wireless'\n"
  'DBUS_NM_SETTINGS_CONNECTION_INTERFACE = '
  "'org.freedesktop.NetworkManager.Settings.Connection'\n"
  'DBUS_NM_SETTINGS_CONNECTION_ACTIVE_INTERFACE = '
  "'org.freedesktop.NetworkManager.Connection.Active'\n"
  '\n'
  'NM_DEVICE_TYPE_MODEM = 8\n'
  'NM_DEVICE_STATE_ACTIVATED = 100\n'
  '\n'
  'def deactivate_ethernet_connections():\n'
  '    active_connection_object_paths = \\\n'
  '        dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                       dbus_interface = '
  "DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_INTERFACE, 'ActiveConnections')\n"
  '\n'
  '    for active_connection_object_path in active_connection_object_paths:\n'
  '        connection_object_path = \\\n'
  '            dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'active_connection_object_path),\n'
  '                           dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_SETTINGS_CONNECTION_ACTIVE_INTERFACE, '
  "'Connection')\n"
  '        connection_settings = \\\n'
  '            dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'connection_object_path),\n'
  '                           dbus_interface = '
  'DBUS_NM_SETTINGS_CONNECTION_INTERFACE).GetSettings()\n'
  '\n'
  "        if connection_settings['connection']['type'] != 'ethernet' \\\n"
  "           and connection_settings['connection']['type'] != "
  "'802-3-ethernet':\n"
  '                continue\n'
  '\n'
  '        dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                       dbus_interface = '
  'DBUS_NM_INTERFACE).DeactivateConnection(active_connection_object_path)\n'
  '\n'
  'def get_mm_modem_object_paths():\n'
  '    modem_object_path_list = []\n'
  '\n'
  '    xml = dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME,\n'
  '                                                     '
  'DBUS_MM_MODEM_OBJECT_PATH),\n'
  '                         dbus_interface = '
  'DBUS_INTROSPECTABLE_INTERFACE).Introspect()\n'
  '    xml_parsed = minidom.parseString(xml)\n'
  "    items = xml_parsed.getElementsByTagName('node')\n"
  '\n'
  '    items.pop(0)\n'
  '\n'
  '    for i in items:\n'
  '        try:\n'
  "            v = int(i.attributes['name'].value)\n"
  '        except:\n'
  '            continue\n'
  '\n'
  '        '
  "modem_object_path_list.append('/org/freedesktop/ModemManager1/Modem/' + "
  'str(v))\n'
  '\n'
  '    return modem_object_path_list\n'
  '\n'
  "modem_imei = ''\n"
  "modem_primary_port = ''\n"
  'c_parser_config = ConfigParser.ConfigParser()\n'
  '\n'
  'deactivate_ethernet_connections()\n'
  '\n'
  "if not os.path.isfile('/etc/tf_mobile_internet_enabled'):\n"
  '    exit(0)\n'
  '\n'
  "c_parser_config.read('/etc/tf_mobile_internet_enabled')\n"
  "modem_imei = c_parser_config.get('configuration', 'modem-imei', '')\n"
  '\n'
  'if not modem_imei:\n'
  '    exit(0)\n'
  '\n'
  'modem_object_path_list = get_mm_modem_object_paths()\n'
  '\n'
  'for o in modem_object_path_list:\n'
  '    ip_interface_found = False\n'
  '\n'
  '    imei = \\\n'
  '        dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME, o),\n'
  '                       dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_MM_MODEM_INTERFACE, '
  "'EquipmentIdentifier')\n"
  '\n'
  '    if imei != modem_imei:\n'
  '        continue\n'
  '\n'
  '    modem_primary_port = \\\n'
  '        dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME, o),\n'
  '                       dbus_interface = '
  "DBUS_PROPERTIES_INTERFACE).Get(DBUS_MM_MODEM_INTERFACE, 'PrimaryPort')\n"
  '\n'
  '    nm_devices = \\\n'
  '        dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                       dbus_interface = DBUS_NM_INTERFACE).GetDevices()\n'
  '\n'
  '    for device_object_path in nm_devices:\n'
  '        device_properties = \\\n'
  '            dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'device_object_path),\n'
  '                           dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).GetAll(DBUS_NM_DEVICE_INTERFACE)\n'
  '\n'
  "        if device_properties['DeviceType'] != NM_DEVICE_TYPE_MODEM:\n"
  '            continue\n'
  '\n'
  "        if device_properties['State'] != NM_DEVICE_STATE_ACTIVATED:\n"
  '            continue\n'
  '\n'
  "        if device_properties['Interface'] != modem_primary_port:\n"
  '            continue\n'
  '\n'
  "        os.system('/sbin/iptables -t nat -D POSTROUTING -o ' + "
  "device_properties['IpInterface'] + ' -j MASQUERADE &> /dev/null')\n"
  "        os.system('/sbin/iptables -D FORWARD -i {0} -j ACCEPT &> "
  "/dev/null')\n"
  "        os.system('/sbin/iptables -t nat -A POSTROUTING -o ' + "
  "device_properties['IpInterface'] + ' -j MASQUERADE &> /dev/null')\n"
  "        os.system('/sbin/iptables -A FORWARD -i {0} -j ACCEPT &> "
  "/dev/null')\n"
  '\n'
  '        ip_interface_found = True\n'
  '\n'
  '        break\n'
  '\n'
  '    if ip_interface_found:\n'
  '        break\n'
  "'''\n"
  '\n'
  "SH_SETUP_AP_NAT = '''\n"
  '#! /bin/bash\n'
  '\n'
  'gw=$(/sbin/route | /usr/bin/awk \'{{if($1=="default") print $8}}\')\n'
  '\n'
  'if [ ! -z "$gw" ] && [ $gw != \'{0}\' ]; then\n'
  '    /sbin/iptables -t nat -D POSTROUTING -o $gw -j MASQUERADE &> /dev/null\n'
  '    /sbin/iptables -D FORWARD -i {0} -j ACCEPT &> /dev/null\n'
  '    /sbin/iptables -t nat -A POSTROUTING -o $gw -j MASQUERADE &> /dev/null\n'
  '    /sbin/iptables -A FORWARD -i {0} -j ACCEPT &> /dev/null\n'
  'fi\n'
  "'''\n"
  '\n'
  "UNIT_SETUP_AP_NAT = '''[Unit]\n"
  'Description=Service to setup/update NAT configuration\n'
  'Wants=network.target network-online.target\n'
  'After=network.target network-online.target\n'
  '\n'
  '[Service]\n'
  'Type=oneshot\n'
  'ExecStart={0}\n'
  '\n'
  '[Install]\n'
  'WantedBy=default.target\n'
  "'''\n"
  '\n'
  "TIMER_SETUP_AP_NAT = '''[Unit]\n"
  'Description=Execute tf_setup_ap_nat.service every 5 seconds\n'
  '\n'
  '[Timer]\n'
  'OnUnitActiveSec=5s\n'
  'Unit=tf_setup_ap_nat.service\n'
  '\n'
  '[Install]\n'
  'WantedBy=timers.target\n'
  "'''\n"
  '\n'
  "HOSTAPD_CONF = '''# Checkout "
  'https://w1.fi/cgit/hostap/plain/hostapd/hostapd.conf\n'
  '# for the details of the configuration parameters in this file.\n'
  'interface={0}\n'
  '{1}\n'
  'ssid={2}\n'
  'channel={3}\n'
  'macaddr_acl=0\n'
  'auth_algs=1\n'
  'ignore_broadcast_ssid={4}\n'
  'wpa=2\n'
  'wpa_passphrase={5}\n'
  'wpa_key_mgmt=WPA-PSK\n'
  'wpa_pairwise=TKIP\n'
  'rsn_pairwise=CCMP\n'
  'ieee80211n=1\n'
  'hw_mode=g\n'
  "'''\n"
  '\n'
  "DNSMASQ_CONF = '''{0}\n"
  'no-poll\n'
  'no-hosts\n'
  'no-resolv\n'
  'bogus-priv\n'
  'expand-hosts\n'
  'domain-needed\n'
  'dhcp-authoritative\n'
  'listen-address=127.0.0.1\n'
  'listen-address={1}\n'
  'server=8.8.8.8\n'
  'local=/{2}/127.0.0.1\n'
  'domain={2}\n'
  'host-record={2},{1}\n'
  'ptr-record={3}.in-addr.arpa,"{2}"\n'
  'dhcp-range={4},{5},72h\n'
  'dhcp-option=option:netmask,{6}\n'
  'dhcp-option=option:router,{1}\n'
  'dhcp-option=option:dns-server,{1}\n'
  'dhcp-option=option:ip-forward-enable,0\n'
  'dhcp-option=option:netbios-nodetype,8\n'
  "'''\n"
  '\n'
  "INTERFACES_CONF = '''# interfaces(5) file used by ifup(8) and ifdown(8)\n"
  'auto lo\n'
  'iface lo inet loopback\n'
  '\n'
  'auto {0}\n'
  'allow-hotplug {0}\n'
  'iface {0} inet static\n'
  '    address {1}\n'
  '    netmask {2}\n'
  "'''\n"
  '\n'
  "DEFAULT_DNSMASQ = '''# This file has five functions:\n"
  '# 1) to completely disable starting dnsmasq,\n'
  '# 2) to set DOMAIN_SUFFIX by running `dnsdomainname`\n'
  '# 3) to select an alternative config file\n'
  '#    by setting DNSMASQ_OPTS to --conf-file=<file>\n'
  '# 4) to tell dnsmasq to read the files in /etc/dnsmasq.d for\n'
  '#    more configuration variables.\n'
  "# 5) to stop the resolvconf package from controlling dnsmasq's\n"
  '#    idea of which upstream nameservers to use.\n'
  '# For upgraders from very old versions, all the shell variables set\n'
  '# here in previous versions are still honored by the init script\n'
  '# so if you just keep your old version of this file nothing will break.\n'
  '\n'
  '#DOMAIN_SUFFIX=`dnsdomainname`\n'
  '#DNSMASQ_OPTS="--conf-file=/etc/dnsmasq.alt"\n'
  '\n'
  '# Whether or not to run the dnsmasq daemon; set to 0 to disable.\n'
  'ENABLED=1\n'
  '\n'
  '# By default search this drop directory for configuration options.\n'
  '# Libvirt leaves a file here to make the system dnsmasq play nice.\n'
  "# Comment out this line if you don't want this. The dpkg-* are file\n"
  '# endings which cause dnsmasq to skip that file. This avoids pulling\n'
  '# in backups made by dpkg.\n'
  'CONFIG_DIR=/etc/dnsmasq.d,.dpkg-dist,.dpkg-old,.dpkg-new\n'
  '\n'
  '# If the resolvconf package is installed, dnsmasq will use its output\n'
  '# rather than the contents of /etc/resolv.conf to find upstream\n'
  '# nameservers. Uncommenting this line inhibits this behaviour.\n'
  '# Not that including a "resolv-file=<filename>" line in\n'
  '# /etc/dnsmasq.conf is not enough to override resolvconf if it is\n'
  '# installed: the line below must be uncommented.\n'
  '#IGNORE_RESOLVCONF=yes\n'
  "'''\n"
  '\n'
  'def setup_nat():\n'
  '    if IMAGE_VERSION and IMAGE_VERSION < MIN_VERSION_FOR_NAT:\n'
  '        return\n'
  '\n'
  '    if not IMAGE_VERSION:\n'
  '        return\n'
  '\n'
  "    file_path_sysctl_conf = '/etc/sysctl.d/enable_ipv4_forward.conf'\n"
  "    file_path_systemd_sh = '/usr/local/scripts/_tf_setup_ap_nat.sh'\n"
  "    file_path_systemd_py = '/usr/local/scripts/_tf_setup_ap_nat.py'\n"
  "    file_path_systemd_unit = '/etc/systemd/system/tf_setup_ap_nat.service'\n"
  "    file_path_systemd_timer = '/etc/systemd/system/tf_setup_ap_nat.timer'\n"
  '\n'
  "    with open(file_path_sysctl_conf, 'w') as fh_sysctl:\n"
  "        fh_sysctl.write('net.ipv4.ip_forward = 1\\n')\n"
  '\n'
  '    os.chmod(file_path_sysctl_conf, 0644)\n'
  '\n'
  "    if os.system('/sbin/sysctl -p ' + file_path_sysctl_conf + ' &> "
  "/dev/null') == 0:\n"
  '        if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_NM:\n'
  "            with open(file_path_systemd_py, 'w') as fh_py:\n"
  '                fh_py.write(PY_SETUP_AP_NAT.format(interface))\n'
  '\n'
  '            os.chmod(file_path_systemd_py, 0755)\n'
  '        else:\n'
  "            with open(file_path_systemd_sh, 'w') as fh_sh:\n"
  '                fh_sh.write(SH_SETUP_AP_NAT.format(interface))\n'
  '\n'
  '            os.chmod(file_path_systemd_sh, 0755)\n'
  '\n'
  '        if os.path.exists(file_path_systemd_unit):\n'
  "            os.system('/bin/systemctl stop ' + file_path_systemd_unit + ' "
  "&> /dev/null')\n"
  "            os.system('/bin/systemctl disable ' + file_path_systemd_unit + "
  "' &> /dev/null')\n"
  '\n'
  '        if os.path.exists(file_path_systemd_timer):\n'
  "            os.system('/bin/systemctl stop ' + file_path_systemd_timer +' "
  "&> /dev/null')\n"
  "            os.system('/bin/systemctl disable ' + file_path_systemd_timer + "
  "' &> /dev/null')\n"
  '\n'
  "        with open(file_path_systemd_unit, 'w') as fh_unit:\n"
  '            if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_NM:\n'
  "                fh_unit.write(UNIT_SETUP_AP_NAT.format('/usr/bin/python ' + "
  'file_path_systemd_py))\n'
  '            else:\n'
  "                fh_unit.write(UNIT_SETUP_AP_NAT.format('/bin/bash ' + "
  'file_path_systemd_sh))\n'
  '\n'
  "        with open(file_path_systemd_timer, 'w') as fh_timer:\n"
  '            fh_timer.write(TIMER_SETUP_AP_NAT)\n'
  '\n'
  '        os.chmod(file_path_systemd_unit, 0644)\n'
  '        os.chmod(file_path_systemd_timer, 0644)\n'
  '\n'
  '        if os.path.exists(file_path_systemd_unit):\n'
  "            os.system('/bin/systemctl enable ' + file_path_systemd_unit + ' "
  "&> /dev/null')\n"
  "            os.system('/bin/systemctl start tf_setup_ap_nat.service &> "
  "/dev/null')\n"
  '\n'
  '        if os.path.exists(file_path_systemd_timer):\n'
  "            os.system('/bin/systemctl enable ' + file_path_systemd_timer + "
  "' &> /dev/null')\n"
  "            os.system('/bin/systemctl start tf_setup_ap_nat.timer &> "
  "/dev/null')\n"
  '\n'
  "        os.system('/bin/systemctl daemon-reload &> /dev/null')\n"
  '\n'
  'if len(argv) < 2:\n'
  '    exit (1)\n'
  '\n'
  'try:\n'
  '    apply_dict = json.loads(argv[1])\n'
  '\n'
  '    if IMAGE_VERSION and  IMAGE_VERSION >= '
  'MIN_VERSION_FOR_HOSTAPD_UPDATE_1:\n'
  '        if len(apply_dict) != 13:\n'
  '            exit(1)\n'
  '    else:\n'
  '        if len(apply_dict) != 12:\n'
  '            exit(1)\n'
  '\n'
  "    interface        = unicode(apply_dict['interface'])\n"
  "    interface_ip     = unicode(apply_dict['interface_ip'])\n"
  "    interface_mask   = unicode(apply_dict['interface_mask'])\n"
  "    ssid             = unicode(apply_dict['ssid'])\n"
  "    ssid_hidden      = apply_dict['ssid_hidden']\n"
  "    wpa_key          = unicode(apply_dict['wpa_key'])\n"
  "    channel          = unicode(apply_dict['channel'])\n"
  "    enabled_dns_dhcp = apply_dict['enabled_dns_dhcp']\n"
  "    domain           = unicode(apply_dict['domain'])\n"
  "    dhcp_start       = unicode(apply_dict['dhcp_start'])\n"
  "    dhcp_end         = unicode(apply_dict['dhcp_end'])\n"
  "    dhcp_mask        = unicode(apply_dict['dhcp_mask'])\n"
  '\n'
  '    # If there is an existing hostapd configuration with an interface '
  'defined\n'
  '    # then try to disable the interface.\n'
  '    if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_NM:\n'
  "        if os.path.exists('/etc/hostapd/hostapd.conf'):\n"
  '            is_hostapd_interface = False\n'
  '\n'
  "            with open('/etc/hostapd/hostapd.conf', 'r') as fh:\n"
  "                hostapd_config_buf = '[root]\\n' + fh.read()\n"
  '                hostapd_parser = ConfigParser.ConfigParser()\n'
  '                '
  'hostapd_parser.readfp(StringIO.StringIO(hostapd_config_buf))\n'
  "                hostapd_interface = hostapd_parser.get('root', 'interface', "
  'None)\n'
  '\n'
  '                if hostapd_interface:\n'
  '                    is_hostapd_interface = True\n'
  '\n'
  '            if is_hostapd_interface:\n'
  '                try:\n'
  "                    os.system('/sbin/ifdown ' + hostapd_interface + ' &> "
  "/dev/null')\n"
  '                except:\n'
  '                    pass\n'
  '\n'
  '    if IMAGE_VERSION and IMAGE_VERSION >= '
  'MIN_VERSION_FOR_HOSTAPD_UPDATE_1:\n'
  "        hostapd_driver = unicode(apply_dict['hostapd_driver'])\n"
  '    else:\n'
  "        hostapd_driver = ''\n"
  '\n'
  "    with open('/etc/default/dnsmasq', 'w') as fd_default_dnsmasq:\n"
  '        fd_default_dnsmasq.write(DEFAULT_DNSMASQ)\n'
  '\n'
  "    with open('/etc/default/hostapd', 'w') as fd_default_hostapd_conf:\n"
  '        '
  'fd_default_hostapd_conf.write(\'DAEMON_CONF="/etc/hostapd/hostapd.conf"\')\n'
  '\n'
  "    with open('/etc/hostapd/hostapd.conf', 'w') as fd_hostapd_conf:\n"
  '        if ssid_hidden:\n'
  '            fd_hostapd_conf.write(HOSTAPD_CONF.format(interface,\n'
  '                                                      hostapd_driver,\n'
  '                                                      ssid,\n'
  '                                                      channel,\n'
  "                                                      '2',\n"
  '                                                      wpa_key))\n'
  '        else:\n'
  '            fd_hostapd_conf.write(HOSTAPD_CONF.format(interface,\n'
  '                                                      hostapd_driver,\n'
  '                                                      ssid,\n'
  '                                                      channel,\n'
  "                                                      '0',\n"
  '                                                      wpa_key))\n'
  '\n'
  "    with open('/etc/dnsmasq.conf', 'w') as fd_dnsmasq_conf:\n"
  '        if enabled_dns_dhcp:\n'
  "            fd_dnsmasq_conf.write(DNSMASQ_CONF.format('#Enabled',\n"
  '                                                      interface_ip,\n'
  '                                                      domain,\n'
  '                                                      '
  "'.'.join(interface_ip.split('.')[::-1]),\n"
  '                                                      dhcp_start,\n'
  '                                                      dhcp_end,\n'
  '                                                      dhcp_mask))\n'
  '        else:\n'
  "            fd_dnsmasq_conf.write(DNSMASQ_CONF.format('#Disabled',\n"
  '                                                      interface_ip,\n'
  '                                                      domain,\n'
  '                                                      '
  "'.'.join(interface_ip.split('.')[::-1]),\n"
  '                                                      dhcp_start,\n'
  '                                                      dhcp_end,\n'
  '                                                      dhcp_mask))\n'
  '\n'
  "    with open('/etc/network/interfaces', 'w') as fd_interfaces_conf:\n"
  '        fd_interfaces_conf.write(INTERFACES_CONF.format(interface, '
  'interface_ip, interface_mask))\n'
  '\n'
  "    with open('/etc/network/interfaces.ap', 'w') as fd_interfaces_ap_conf:\n"
  '        fd_interfaces_ap_conf.write(INTERFACES_CONF.format(interface, '
  'interface_ip, interface_mask))\n'
  '\n'
  '    for intf in netifaces.interfaces():\n'
  '        if intf != interface:\n'
  '            continue\n'
  '\n'
  "        if os.system('/sbin/ifconfig '+intf+' up &> /dev/null') != 0:\n"
  '            exit(1)\n'
  '\n'
  '    if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_NM:\n'
  "        if os.system('/usr/bin/nmcli radio wifi off &> /dev/null') != 0:\n"
  '            exit(1)\n'
  '    else:\n'
  "        if os.system('/bin/systemctl stop wicd &> /dev/null') != 0:\n"
  '            exit(1)\n'
  '\n'
  "        if os.system('/bin/systemctl disable wicd &> /dev/null') != 0:\n"
  '            exit(1)\n'
  '\n'
  '    if enabled_dns_dhcp:\n'
  "        if os.system('/bin/systemctl enable dnsmasq &> /dev/null') != 0:\n"
  '            exit(1)\n'
  '\n'
  "        if os.system('/bin/systemctl restart dnsmasq &> /dev/null') != 0:\n"
  '            exit(1)\n'
  '    else:\n'
  "        if os.system('/bin/systemctl disable dnsmasq &> /dev/null') != 0:\n"
  '            exit(1)\n'
  '\n'
  "        if os.system('/bin/systemctl stop dnsmasq &> /dev/null') != 0:\n"
  '            exit(1)\n'
  '\n'
  "    if os.system('/bin/systemctl enable hostapd &> /dev/null') != 0:\n"
  '        exit(1)\n'
  '\n'
  '    setup_nat()\n'
  '\n'
  "    if os.system('/bin/systemctl restart networking &> /dev/null; "
  "/bin/systemctl restart hostapd &> /dev/null') != 0:\n"
  '        exit(1)\n'
  '\n'
  'except:\n'
  '    traceback.print_exc()\n'
  '    exit(1)\n'),
 ('settings_ap_get_interfaces',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import json\n'
  'import netifaces\n'
  '\n'
  'return_dict = {}\n'
  '\n'
  'try:\n'
  '    for intf in netifaces.interfaces():\n'
  "        if not os.path.isdir('/sys/class/net/'+intf+'/wireless'):\n"
  '            continue\n'
  '\n'
  "        intf_dict = {'ip'  : None,\n"
  "                     'mask': None}\n"
  '\n'
  '        return_dict[intf] = intf_dict\n'
  '\n'
  '        intf_addrs = netifaces.ifaddresses(intf)\n'
  '\n'
  '        if netifaces.AF_INET in intf_addrs and\\\n'
  "           'addr' in intf_addrs[netifaces.AF_INET][0] and\\\n"
  "           'netmask' in intf_addrs[netifaces.AF_INET][0]:\n"
  "                return_dict[intf]['ip'] = "
  "intf_addrs[netifaces.AF_INET][0]['addr']\n"
  "                return_dict[intf]['mask'] = "
  "intf_addrs[netifaces.AF_INET][0]['netmask']\n"
  '                \n'
  'except:\n'
  '    exit(1)\n'
  '\n'
  'print json.dumps(return_dict)\n'),
 ('settings_ap_status',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import json\n'
  'import netifaces\n'
  'import psutil\n'
  '\n'
  'if psutil.version_info >= (2, 1, 0): # image version >= 1.4 (jessie)\n'
  '    def get_name(p):\n'
  '        return p.name()\n'
  'else: # image version < 1.4 (wheezy)\n'
  '    def get_name(p):\n'
  '        return p.name\n'
  '\n'
  "return_dict = {'ap_first_time'                 : None,\n"
  "               'ap_incomplete_config'          : None,\n"
  "               'ap_hardware_or_config_problem' : None}\n"
  '\n'
  'try:\n'
  "    return_dict['ap_first_time']  = False\n"
  "    return_dict['ap_incomplete_config'] = True\n"
  "    if os.path.isfile('/etc/hostapd/hostapd.conf') and \\\n"
  "       os.path.isfile('/etc/dnsmasq.conf'):\n"
  "            with open('/etc/hostapd/hostapd.conf', 'r') as "
  'fd_hostapd_conf:\n'
  '                lines = fd_hostapd_conf.readlines()\n'
  '\n'
  '                for l in lines:\n'
  "                    l_split = l.strip().split('=')\n"
  "                    if len(l_split) == 2 and l_split[0].strip(' ') == "
  "'interface':\n"
  '                        if l_split[1]:\n'
  "                            return_dict['ap_incomplete_config'] = False\n"
  '                        else:\n'
  '                            hostapd_running = False\n'
  '                            for p in psutil.process_iter():\n'
  "                                if p.name == 'hostapd':\n"
  '                                    hostapd_running = True\n'
  '                            if not hostapd_running:\n'
  "                                return_dict['ap_first_time'] = True\n"
  '\n'
  "    return_dict['ap_hardware_or_config_problem'] = True\n"
  "    if not return_dict['ap_incomplete_config']:\n"
  '        hostapd_running = False\n'
  '        dnsmasq_running = False\n'
  '        for p in psutil.process_iter():\n'
  "            if get_name(p) == 'hostapd':\n"
  '                hostapd_running = True\n'
  "            elif get_name(p) == 'dnsmasq':\n"
  '                dnsmasq_running = True\n'
  '\n'
  '        if hostapd_running and dnsmasq_running:\n'
  "            return_dict['ap_hardware_or_config_problem'] = False\n"
  '\n'
  'except:\n'
  '    exit(1)\n'
  '\n'
  'print json.dumps(return_dict)\n'),
 ('settings_fs_expand_check',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import json\n'
  'import subprocess\n'
  'import sys\n'
  'import os\n'
  '\n'
  'if len(sys.argv) < 2:\n'
  "    sys.stderr.write(u'Missing parameters'.encode('utf-8'))\n"
  '    exit(2)\n'
  '\n'
  'block_device = sys.argv[1]\n'
  'result = {}\n'
  "cmd_get_part = '/bin/lsblk -o name -ln ' + block_device\n"
  'ps_get_part = subprocess.Popen(cmd_get_part, shell=True, '
  'stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n'
  'cmd_output, cmd_error = ps_get_part.communicate()\n'
  '\n'
  'if ps_get_part.returncode != 0:\n'
  '    cmd_error = cmd_error.strip()\n'
  '\n'
  '    if len(cmd_error) > 0:\n'
  "        sys.stderr.write(u'Could not get block devices "
  "list:\\n\\n{0}'.format(cmd_error).encode('utf-8'))\n"
  '    else:\n'
  "        sys.stderr.write(u'Could not get block devices "
  "list'.encode('utf-8'))\n"
  '\n'
  '    exit(ps_get_part.returncode)\n'
  'elif len(cmd_output.splitlines()) != 2:\n'
  "    sys.stderr.write(u'Found more than one partition, cannot resize this')\n"
  '    exit(3)\n'
  '\n'
  'try:\n'
  "    with open('/sys/block/mmcblk0/size') as f_card_size:\n"
  '        card_size = f_card_size.readline()\n'
  "        result['card_size'] = int(card_size.strip())\n"
  '\n'
  "    s = os.statvfs('/')\n"
  '\n'
  '    # divide by 512 to get the size in the same base as the /sys/block '
  'values\n'
  "    result['ext3_size'] = s.f_blocks * s.f_bsize / 512\n"
  '\n'
  "    with open('/sys/block/mmcblk0/mmcblk0p1/start') as f_p1_start:\n"
  '        p1_start = f_p1_start.readline()\n'
  "        result['p1_start'] = int(p1_start.strip())\n"
  '\n'
  "    with open('/sys/block/mmcblk0/mmcblk0p1/size') as f_p1_size:\n"
  '        p1_size = f_p1_size.readline()\n'
  "        result['p1_size'] = int(p1_size.strip())\n"
  'except Exception as e:\n'
  "    sys.stderr.write(unicode(e).encode('utf-8'))\n"
  '    exit(4)\n'
  '\n'
  "sys.stdout.write(json.dumps(result, separators=(',', ':')))\n"
  'exit(0)\n'),
 ('settings_mobile_internet',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import re\n'
  'import os\n'
  'import sys\n'
  'import json\n'
  'import time\n'
  'import dbus\n'
  'import shlex\n'
  'import signal\n'
  'import serial\n'
  'import socket\n'
  'import struct\n'
  'import netifaces\n'
  'import traceback\n'
  'import netifaces\n'
  'import subprocess\n'
  'import ConfigParser\n'
  'from xml.dom import minidom\n'
  'from distutils.version import StrictVersion\n'
  '\n'
  'if len(sys.argv) < 2:\n'
  '    exit (1)\n'
  '\n'
  'IMAGE_VERSION = None\n'
  '\n'
  'try:\n'
  "    with open('/etc/tf_image_version', 'r') as f:\n"
  "        IMAGE_VERSION = StrictVersion(f.read().split(' ')[0].strip())\n"
  'except:\n'
  '    exit(1)\n'
  '\n'
  'ACTION = sys.argv[1]\n'
  '\n'
  "MIN_VERSION_WITH_MM = StrictVersion('1.10')\n"
  "CMD_MM_SEARCH_MODEMS = '/usr/bin/mmcli -S &> /dev/null'\n"
  '\n'
  'MM_MODEM_STATE_FAILED = 0\n'
  'MM_MODEM_STATE_UNKNOWN = 1\n'
  'MM_MODEM_STATE_INITIALIZING = 2\n'
  'MM_MODEM_STATE_LOCKED = 3\n'
  'MM_MODEM_STATE_DISABLED = 4\n'
  'MM_MODEM_STATE_DISABLING = 5\n'
  'MM_MODEM_STATE_ENABLING = 6\n'
  'MM_MODEM_STATE_ENABLED = 7\n'
  'MM_MODEM_STATE_SEARCHING = 8\n'
  'MM_MODEM_STATE_REGISTERED = 9\n'
  'MM_MODEM_STATE_DISCONNECTING = 10\n'
  'MM_MODEM_STATE_CONNECTING = 11\n'
  'MM_MODEM_STATE_CONNECTED = 12\n'
  '\n'
  'MM_MODEM_STATE_FAILED_REASON_NONE = 0\n'
  'MM_MODEM_STATE_FAILED_REASON_UNKNOWN = 1\n'
  'MM_MODEM_STATE_FAILED_REASON_SIM_MISSING = 2\n'
  'MM_MODEM_STATE_FAILED_REASON_SIM_ERROR = 3\n'
  '\n'
  'MM_MODEM_POWER_STATE_UNKNOWN = 0\n'
  'MM_MODEM_POWER_STATE_OFF = 1\n'
  'MM_MODEM_POWER_STATE_LOW = 2\n'
  'MM_MODEM_POWER_STATE_ON = 3\n'
  '\n'
  'NM_DEVICE_TYPE_MODEM = 8\n'
  'NM_DEVICE_STATE_ACTIVATED = 100\n'
  '\n'
  "DBUS_MM_BUS_NAME = 'org.freedesktop.ModemManager1'\n"
  "DBUS_MM_OBJECT_PATH = '/org/freedesktop/ModemManager1'\n"
  "DBUS_MM_SIM_INTERFACE = 'org.freedesktop.ModemManager1.Sim'\n"
  "DBUS_PROPERTIES_INTERFACE = 'org.freedesktop.DBus.Properties'\n"
  "DBUS_MM_MODEM_INTERFACE = 'org.freedesktop.ModemManager1.Modem'\n"
  "DBUS_MM_BEARER_INTERFACE = 'org.freedesktop.ModemManager1.Bearer'\n"
  "DBUS_MM_MODEM_OBJECT_PATH = '/org/freedesktop/ModemManager1/Modem'\n"
  "DBUS_INTROSPECTABLE_INTERFACE = 'org.freedesktop.DBus.Introspectable'\n"
  'DBUS_MM_MODEM_SIMPLE_INTERFACE = '
  "'org.freedesktop.ModemManager1.Modem.Simple'\n"
  '\n'
  "DBUS_NM_BUS_NAME = 'org.freedesktop.NetworkManager'\n"
  "DBUS_NM_INTERFACE = 'org.freedesktop.NetworkManager'\n"
  "DBUS_NM_OBJECT_PATH = '/org/freedesktop/NetworkManager'\n"
  "DBUS_PROPERTIES_INTERFACE = 'org.freedesktop.DBus.Properties'\n"
  "DBUS_NM_DEVICE_INTERFACE = 'org.freedesktop.NetworkManager.Device'\n"
  "DBUS_NM_AP_INTERFACE = 'org.freedesktop.NetworkManager.AccessPoint'\n"
  "DBUS_NM_SETTINGS_INTERFACE = 'org.freedesktop.NetworkManager.Settings'\n"
  "DBUS_NM_SETTINGS_OBJECT_PATH = '/org/freedesktop/NetworkManager/Settings'\n"
  "DBUS_NM_IPV4_CONFIG_INTERFACE = 'org.freedesktop.NetworkManager.IP4Config'\n"
  'DBUS_NM_DEVICE_WIRELESS_INTERFACE = '
  "'org.freedesktop.NetworkManager.Device.Wireless'\n"
  'DBUS_NM_SETTINGS_CONNECTION_INTERFACE = '
  "'org.freedesktop.NetworkManager.Settings.Connection'\n"
  'DBUS_NM_SETTINGS_CONNECTION_ACTIVE_INTERFACE = '
  "'org.freedesktop.NetworkManager.Connection.Active'\n"
  '\n'
  'TAG_CONFIG_SAKIS_OPERATORS = "conf[\'sakisOperators\']"\n'
  "TAG_PARAM_SIM_PIN = 'SIM_PIN'\n"
  "TAG_PARAM_DIAL = 'DIAL'\n"
  "TAG_PARAM_APN = 'FORCE_APN'\n"
  "TAG_PARAM_APN_USER = 'APN_USER'\n"
  "TAG_PARAM_APN_PASS = 'APN_PASS'\n"
  "TAG_PARAM_USBMODEM = 'USBMODEM'\n"
  '\n'
  "SERVICE_SYSTEMD_TF_MOBILE_INTERNET = 'tf_mobile_internet.service'\n"
  "FILE_UNIT_TF_MOBILE_INTERNET = '/etc/systemd/system/' + "
  'SERVICE_SYSTEMD_TF_MOBILE_INTERNET\n'
  'FILE_UNIT_TF_MOBILE_INTERNET_NM = '
  "'/etc/systemd/system/tf_mobile_internet_nm.service'\n"
  "FILE_CONFIG_UMTSKEEPER = '/usr/umtskeeper/umtskeeper.conf'\n"
  "FILE_TMP_SAKIS3GNET = '/tmp/sakis3g.3gnet'\n"
  "FILE_UNIT_TIMER = '/etc/systemd/system/tf_mobile_internet_nm.timer'\n"
  "FILE_UNIT_TARGET_SCRIPT = '/usr/local/scripts/_tf_mobile_internet_nm.py'\n"
  "FILE_MOBILE_INTERNET_CONFIG = '/etc/tf_mobile_internet_enabled'\n"
  '\n'
  "BINARY_SAKIS3G = '/usr/umtskeeper/sakis3g'\n"
  "BINARY_LSUSB = '/usr/bin/lsusb'\n"
  "BINARY_UMTSKEEPER = '/usr/umtskeeper/umtskeeper'\n"
  "BINARY_KILLALL = '/usr/bin/killall'\n"
  "BINARY_SYSTEMCTL = '/bin/systemctl'\n"
  "BINARY_UDEVADM = '/sbin/udevadm'\n"
  '\n'
  "SPLIT_SEARCH_INTERFACE = 'Interface: '\n"
  "SPLIT_SEARCH_OPERATOR = 'Operator name: '\n"
  "SPLIT_SEARCH_IP = 'IP Address: '\n"
  "SPLIT_SEARCH_SUBNET_MASK = 'Subnet Mask: '\n"
  "SPLIT_SEARCH_GATEWAY = 'Default route(s): '\n"
  '\n'
  "DIR_SYS_CLASS_TTY = '/sys/class/tty'\n"
  '\n'
  "UNIT_SYSTEMD = '''[Unit]\n"
  'Description=systemd service for Tinkerforge mobile internet\n'
  '\n'
  '[Service]\n'
  'Type=simple\n'
  'TimeoutStartSec=5\n'
  'ExecStart=/usr/umtskeeper/umtskeeper --conf '
  '/usr/umtskeeper/umtskeeper.conf\n'
  'TimeoutStopSec=5\n'
  'ExecStop=/usr/bin/killall -9 umtskeeper sakis3g pppd\n'
  '\n'
  '[Install]\n'
  'WantedBy=multi-user.target\n'
  "'''\n"
  '\n'
  "CONFIG_UMTSKEEPER = '''\n"
  "conf['deviceName'] = 'modem_mobile_internet'\n"
  'conf[\'sakisSwitches\'] = "--nostorage --pppd --console"\n'
  'conf[\'sakisOperators\'] = "{0}"\n'
  "conf['sakisMaxFails'] = 8\n"
  "conf['sakisFailLockDuration'] = 120\n"
  "conf['wrongPinDelay'] = 60\n"
  "conf['DNSprobeDomain'] = 'google.com'\n"
  "conf['DNSprobeCycle'] = 600\n"
  "conf['writeStats'] = False\n"
  "conf['printMsg'] = False\n"
  "conf['logMsg'] = False\n"
  "conf['logFile'] = '/var/log/umtskeeper.log'\n"
  "conf['statCycle'] = 20 # slow down all checking by 5x\n"
  "'''\n"
  '\n'
  "PY_TF_MOBILE_INTERNET = '''\n"
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import dbus\n'
  'import ConfigParser\n'
  'from xml.dom import minidom\n'
  '\n'
  "DBUS_MM_BUS_NAME = 'org.freedesktop.ModemManager1'\n"
  "DBUS_MM_OBJECT_PATH = '/org/freedesktop/ModemManager1'\n"
  "DBUS_MM_SIM_INTERFACE = 'org.freedesktop.ModemManager1.Sim'\n"
  "DBUS_PROPERTIES_INTERFACE = 'org.freedesktop.DBus.Properties'\n"
  "DBUS_MM_MODEM_INTERFACE = 'org.freedesktop.ModemManager1.Modem'\n"
  "DBUS_MM_BEARER_INTERFACE = 'org.freedesktop.ModemManager1.Bearer'\n"
  "DBUS_MM_MODEM_OBJECT_PATH = '/org/freedesktop/ModemManager1/Modem'\n"
  "DBUS_INTROSPECTABLE_INTERFACE = 'org.freedesktop.DBus.Introspectable'\n"
  'DBUS_MM_MODEM_SIMPLE_INTERFACE = '
  "'org.freedesktop.ModemManager1.Modem.Simple'\n"
  '\n'
  "DBUS_NM_BUS_NAME = 'org.freedesktop.NetworkManager'\n"
  "DBUS_NM_INTERFACE = 'org.freedesktop.NetworkManager'\n"
  "DBUS_NM_OBJECT_PATH = '/org/freedesktop/NetworkManager'\n"
  "DBUS_PROPERTIES_INTERFACE = 'org.freedesktop.DBus.Properties'\n"
  "DBUS_NM_DEVICE_INTERFACE = 'org.freedesktop.NetworkManager.Device'\n"
  "DBUS_NM_AP_INTERFACE = 'org.freedesktop.NetworkManager.AccessPoint'\n"
  "DBUS_NM_SETTINGS_INTERFACE = 'org.freedesktop.NetworkManager.Settings'\n"
  "DBUS_NM_SETTINGS_OBJECT_PATH = '/org/freedesktop/NetworkManager/Settings'\n"
  'DBUS_NM_DEVICE_WIRELESS_INTERFACE = '
  "'org.freedesktop.NetworkManager.Device.Wireless'\n"
  'DBUS_NM_SETTINGS_CONNECTION_INTERFACE = '
  "'org.freedesktop.NetworkManager.Settings.Connection'\n"
  'DBUS_NM_SETTINGS_CONNECTION_ACTIVE_INTERFACE = '
  "'org.freedesktop.NetworkManager.Connection.Active'\n"
  '\n'
  'def get_mm_modem_object_paths():\n'
  '    modem_object_path_list = []\n'
  '\n'
  '    xml = dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME,\n'
  '                                                     '
  'DBUS_MM_MODEM_OBJECT_PATH),\n'
  '                         dbus_interface = '
  'DBUS_INTROSPECTABLE_INTERFACE).Introspect()\n'
  '    xml_parsed = minidom.parseString(xml)\n'
  "    items = xml_parsed.getElementsByTagName('node')\n"
  '\n'
  '    items.pop(0)\n'
  '\n'
  '    for i in items:\n'
  '        try:\n'
  "            v = int(i.attributes['name'].value)\n"
  '        except:\n'
  '            continue\n'
  '\n'
  '        '
  "modem_object_path_list.append('/org/freedesktop/ModemManager1/Modem/' + "
  'str(v))\n'
  '\n'
  '    return modem_object_path_list\n'
  '\n'
  "modem_imei = ''\n"
  "interface_name = ''\n"
  'gsm_connection_active = False\n'
  'c_parser_config = ConfigParser.ConfigParser()\n'
  'c_parser_brickv_gsm = ConfigParser.ConfigParser()\n'
  '\n'
  "if not os.path.isfile('/etc/tf_mobile_internet_enabled'):\n"
  '    exit(0)\n'
  '\n'
  'if not '
  "os.path.isfile('/etc/NetworkManager/system-connections/_tf_brickv_gsm'):\n"
  '    exit(0)\n'
  '\n'
  "c_parser_config.read('/etc/tf_mobile_internet_enabled')\n"
  "modem_imei = c_parser_config.get('configuration', 'modem-imei', '')\n"
  '\n'
  'if not modem_imei:\n'
  '    exit(0)\n'
  '\n'
  "c_parser_brickv_gsm.read('/etc/NetworkManager/system-connections/_tf_brickv_gsm')\n"
  "interface_name = c_parser_brickv_gsm.get('connection', 'interface-name', "
  "'')\n"
  '\n'
  'if not interface_name:\n'
  '    exit(0)\n'
  '\n'
  'active_connection_object_paths = \\\n'
  '    dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                   dbus_interface = '
  "DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_INTERFACE, 'ActiveConnections')\n"
  '\n'
  'for active_connection_object_path in active_connection_object_paths:\n'
  '    connection_object_path = \\\n'
  '        dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'active_connection_object_path),\n'
  '                       dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_SETTINGS_CONNECTION_ACTIVE_INTERFACE, '
  "'Connection')\n"
  '    connection_settings = \\\n'
  '        dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'connection_object_path),\n'
  '                       dbus_interface = '
  'DBUS_NM_SETTINGS_CONNECTION_INTERFACE).GetSettings()\n'
  '\n'
  "    if not connection_settings['connection']['type'] \\\n"
  "       or connection_settings['connection']['type'] != 'gsm':\n"
  '            continue\n'
  '\n'
  "    if not connection_settings['connection']['interface-name'] \\\n"
  "       or connection_settings['connection']['interface-name'] != "
  'interface_name:\n'
  '            dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                           dbus_interface = '
  'DBUS_NM_INTERFACE).DeactivateConnection(active_connection_object_path)\n'
  '\n'
  'modem_object_path_list = get_mm_modem_object_paths()\n'
  '\n'
  'for o in modem_object_path_list:\n'
  '    imei = \\\n'
  '        dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME, o),\n'
  '                       dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_MM_MODEM_INTERFACE, '
  "'EquipmentIdentifier')\n"
  '\n'
  '    if imei != modem_imei:\n'
  '        continue\n'
  '\n'
  '    active_connection_object_paths = \\\n'
  '        dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                       dbus_interface = '
  "DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_INTERFACE, 'ActiveConnections')\n"
  '\n'
  '    for active_connection_object_path in active_connection_object_paths:\n'
  '        connection_object_path = \\\n'
  '            dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'active_connection_object_path),\n'
  '                           dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_SETTINGS_CONNECTION_ACTIVE_INTERFACE, '
  "'Connection')\n"
  '        connection_settings = \\\n'
  '            dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'connection_object_path),\n'
  '                           dbus_interface = '
  'DBUS_NM_SETTINGS_CONNECTION_INTERFACE).GetSettings()\n'
  '\n'
  "        if connection_settings['connection']['id'] == '_tf_brickv_gsm':\n"
  '            gsm_connection_active = True\n'
  '\n'
  '            break\n'
  '\n'
  '    if gsm_connection_active:\n'
  '        break\n'
  '\n'
  '    primary_port = \\\n'
  '        dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME, o),\n'
  '                       dbus_interface = '
  "DBUS_PROPERTIES_INTERFACE).Get(DBUS_MM_MODEM_INTERFACE, 'PrimaryPort')\n"
  '\n'
  "    c_parser_brickv_gsm.set('connection', 'interface-name', primary_port)\n"
  '\n'
  "    with open('/etc/NetworkManager/system-connections/_tf_brickv_gsm', 'w') "
  'as fh:\n'
  '        c_parser_brickv_gsm.write(fh)\n'
  '\n'
  "    os.system('/usr/bin/nmcli connection reload')\n"
  "    os.system('/usr/bin/nmcli connection up _tf_brickv_gsm')\n"
  "'''\n"
  '\n'
  "UNIT_TF_MOBILE_INTERNET = '''[Unit]\n"
  'Description=Check state of configured mobile internet modem and try to keep '
  'it connected\n'
  'Wants=network.target network-online.target\n'
  'After=network.target network-online.target\n'
  '\n'
  '[Service]\n'
  'Type=oneshot\n'
  'ExecStart=/usr/bin/python /usr/local/scripts/_tf_mobile_internet_nm.py\n'
  '\n'
  '[Install]\n'
  'WantedBy=multi-user.target\n'
  "'''\n"
  '\n'
  "TIMER_TF_MOBILE_INTERNET = '''[Unit]\n"
  'Description=Execute tf_mobile_internet_nm.service every 5 seconds\n'
  '\n'
  '[Timer]\n'
  'OnUnitActiveSec=5s\n'
  'Unit=tf_mobile_internet_nm.service\n'
  '\n'
  '[Install]\n'
  'WantedBy=timers.target\n'
  "'''\n"
  '\n'
  "dict_status = {'status'     : None,\n"
  "               'interface'  : None,\n"
  "               'ip'         : None,\n"
  "               'subnet_mask': None,\n"
  "               'gateway'    : None,\n"
  "               'dns'        : None}\n"
  '\n'
  "dict_configuration = {'modem_list'      : None,\n"
  "                      'modem_configured': None,\n"
  "                      'dial'            : None,\n"
  "                      'apn'             : None,\n"
  "                      'username'        : None,\n"
  "                      'password'        : None,\n"
  "                      'sim_card_pin'    : None}\n"
  '\n'
  'c_parser_config = ConfigParser.ConfigParser()\n'
  '\n'
  'if os.path.isfile(FILE_MOBILE_INTERNET_CONFIG):\n'
  '    c_parser_config.read(FILE_MOBILE_INTERNET_CONFIG)\n'
  '\n'
  'def get_value_from_line(line):\n'
  "    split_line = line.split('=', 1)\n"
  '\n'
  '    if len(split_line) == 2:\n'
  '        return split_line[1]\n'
  '    else:\n'
  '        return False\n'
  '\n'
  'def get_vid_pid(pstdout):\n'
  "    vid = ''\n"
  "    pid = ''\n"
  '\n'
  '    for line in pstdout.splitlines():\n'
  "        if 'ID_VENDOR_ID=' in line:\n"
  '            value = get_value_from_line(line)\n'
  '\n'
  '            if value:\n'
  '                vid = value\n'
  '\n'
  "        if 'ID_MODEL_ID=' in line:\n"
  '            value = get_value_from_line(line)\n'
  '\n'
  '            if value:\n'
  '                pid = value\n'
  '\n'
  '    if not vid or not pid:\n'
  '        return False\n'
  '\n'
  "    return ':'.join([vid, pid])\n"
  '\n'
  'def get_device_name(pstdout):\n'
  '    vendor = None\n'
  '    model = None\n'
  '\n'
  '    for line in pstdout.splitlines():\n'
  "        if 'ID_VENDOR_FROM_DATABASE=' in line:\n"
  '            value = get_value_from_line(line)\n'
  '\n'
  '            if value:\n'
  '                vendor = value\n'
  '\n'
  "        if 'ID_MODEL_FROM_DATABASE=' in line:\n"
  '            value = get_value_from_line(line)\n'
  '\n'
  '            if value:\n'
  '                model = value\n'
  '\n'
  '    if not vendor and not model:\n'
  '        return False\n'
  '\n'
  '    if vendor and not model:\n'
  '        return vendor\n'
  '\n'
  '    if not vendor and model:\n'
  '        return model\n'
  '\n'
  "    return ' '.join([vendor, model])\n"
  '\n'
  'def get_usb_tty_devices():\n'
  '\n'
  '    usb_tty_devices = []\n'
  '\n'
  '    for device_node in os.listdir(DIR_SYS_CLASS_TTY):\n'
  '\n'
  "        device_node_path = '/dev/' + device_node\n"
  '\n'
  "        p = subprocess.Popen([BINARY_UDEVADM, 'info', device_node_path],\n"
  '                             stdout = subprocess.PIPE,\n'
  '                             stderr = subprocess.PIPE)\n'
  '        pstdout = p.communicate()[0]\n'
  '\n'
  '        if not pstdout:\n'
  '            continue\n'
  '\n'
  '        if p.returncode != 0:\n'
  '            continue\n'
  '\n'
  "        if not 'ID_' in pstdout:\n"
  '            continue\n'
  '\n'
  "        if not 'N: ' in pstdout:\n"
  '            continue\n'
  '\n'
  "        if not 'ID_VENDOR_ID=' in pstdout:\n"
  '            continue\n'
  '\n'
  "        if not 'ID_MODEL_ID=' in pstdout:\n"
  '            continue\n'
  '\n'
  '        vid_pid = get_vid_pid(pstdout)\n'
  '        device_name = get_device_name(pstdout)\n'
  '\n'
  '        if not vid_pid:\n'
  '            conitnue\n'
  '\n'
  '        if not device_name:\n'
  "            device_name = ''\n"
  '\n'
  "        usb_tty_devices.append({'device_node_path': device_node_path,\n"
  "                                'vid_pid': vid_pid,\n"
  "                                'device_name': device_name})\n"
  '\n'
  '    if len(usb_tty_devices) <= 0:\n'
  '        return False\n'
  '\n'
  '    return usb_tty_devices\n'
  '\n'
  'def killall_processes():\n'
  "    os.system(' -9 '.join([BINARY_KILLALL, 'umtskeeper sakis3g pppd']) + ' "
  "&> /dev/null')\n"
  '\n'
  'def test_connection(command_test_connection):\n'
  '    def remove_tmp_sakis3gnet():\n'
  '        if os.path.exists(FILE_TMP_SAKIS3GNET):\n'
  '            try:\n'
  '                os.remove(FILE_TMP_SAKIS3GNET)\n'
  '            except:\n'
  '                pass\n'
  '\n'
  '    killall_processes()\n'
  '    remove_tmp_sakis3gnet()\n'
  '\n'
  '    ret_command_test_connection = '
  'execute_command(shlex.split(command_test_connection))\n'
  '\n'
  '    if ret_command_test_connection != 0:\n'
  '        killall_processes()\n'
  '        remove_tmp_sakis3gnet()\n'
  "        sys.stdout.write('ERRORCODE = ' + "
  'str(ret_command_test_connection))\n'
  '        if ret_command_test_connection == 7 or \\\n'
  '           ret_command_test_connection == 8 or \\\n'
  '           ret_command_test_connection == 12 or \\\n'
  '           ret_command_test_connection == 13 or \\\n'
  '           ret_command_test_connection == 98:\n'
  '                return ret_command_test_connection\n'
  '        return 2\n'
  '\n'
  '    killall_processes()\n'
  '    remove_tmp_sakis3gnet()\n'
  '\n'
  '    return 0\n'
  '\n'
  'def enable_start_systemd_service():\n'
  "    if execute_command([BINARY_SYSTEMCTL, 'enable', "
  'FILE_UNIT_TF_MOBILE_INTERNET]) != 0:\n'
  '        stop_disable_remove_systemd_service()\n'
  '        return 3\n'
  '\n'
  "    if execute_command([BINARY_SYSTEMCTL, 'start', "
  'SERVICE_SYSTEMD_TF_MOBILE_INTERNET]) != 0:\n'
  '        stop_disable_remove_systemd_service()\n'
  '        return 4\n'
  '\n'
  '    return 0\n'
  '\n'
  'def stop_disable_remove_systemd_service():\n'
  "    os.system(' stop '.join([BINARY_SYSTEMCTL, "
  "SERVICE_SYSTEMD_TF_MOBILE_INTERNET]) + ' &> /dev/null')\n"
  "    os.system(' disable '.join([BINARY_SYSTEMCTL, "
  "SERVICE_SYSTEMD_TF_MOBILE_INTERNET]) + ' &> /dev/null')\n"
  '\n'
  '    if os.path.exists(FILE_UNIT_TF_MOBILE_INTERNET):\n'
  '        os.remove(FILE_UNIT_TF_MOBILE_INTERNET)\n'
  '\n'
  '    killall_processes()\n'
  '\n'
  '# This function is used when a command must be executed with '
  'subprocess.Popen and\n'
  '# only returncode is needed\n'
  'def execute_command(command):\n'
  '    p = subprocess.Popen(command, stdout = subprocess.PIPE, stderr = '
  'subprocess.PIPE)\n'
  '    p.communicate()\n'
  '    return p.returncode\n'
  '\n'
  'def prepare_test_command_and_umtskeeper_configuration(usb_modem,\n'
  '                                                      dial,\n'
  '                                                      apn,\n'
  '                                                      apn_user,\n'
  '                                                      apn_pass,\n'
  '                                                      sim_pin):\n'
  "    command_test_connection = ''\n"
  "    configuration_umtskeeper = ''\n"
  '    sakis_operators = \'\'\'DIAL="{0}" FORCE_APN="{1}" APN_USER="{2}" '
  'APN_PASS="{3}" OTHER="USBMODEM" USBMODEM="{4}" MODEM="{4}"\'\'\'\n'
  '    sakis_operators_sim_pin = \'\'\'SIM_PIN="{0}" DIAL="{1}" '
  'FORCE_APN="{2}" APN_USER="{3}" APN_PASS="{4}" OTHER="USBMODEM" '
  'USBMODEM="{5}" MODEM="{5}"\'\'\'\n'
  '\n'
  "    if sim_pin != '':\n"
  "        command_test_connection_args = ' connect --nostorage --pppd --nofix "
  "--console ' +\\\n"
  '            sakis_operators_sim_pin.format(sim_pin,\n'
  '                                           dial,\n'
  '                                           apn,\n'
  '                                           apn_user,\n'
  '                                           apn_pass,\n'
  '                                           usb_modem)\n'
  '        command_test_connection = BINARY_SAKIS3G + '
  'command_test_connection_args\n'
  '        configuration_umtskeeper = '
  'CONFIG_UMTSKEEPER.format(sakis_operators_sim_pin.replace(\'"\', '
  '"\'").format(sim_pin,\n'
  '                                                                                                             '
  'dial,\n'
  '                                                                                                             '
  'apn,\n'
  '                                                                                                             '
  'apn_user,\n'
  '                                                                                                             '
  'apn_pass,\n'
  '                                                                                                             '
  'usb_modem))\n'
  '        return command_test_connection, configuration_umtskeeper\n'
  '\n'
  '    else:\n'
  "        command_test_connection_args = ' connect --nostorage --pppd --nofix "
  "--console ' +\\\n"
  '            sakis_operators.format(dial,\n'
  '                                   apn,\n'
  '                                   apn_user,\n'
  '                                   apn_pass,\n'
  '                                   usb_modem)\n'
  '        command_test_connection = BINARY_SAKIS3G + '
  'command_test_connection_args\n'
  '        configuration_umtskeeper = '
  'CONFIG_UMTSKEEPER.format(sakis_operators.replace(\'"\', "\'").format(dial,\n'
  '                                                                                                     '
  'apn,\n'
  '                                                                                                     '
  'apn_user,\n'
  '                                                                                                     '
  'apn_pass,\n'
  '                                                                                                     '
  'usb_modem))\n'
  '        return command_test_connection, configuration_umtskeeper\n'
  '\n'
  'def find_whole_word(word):\n'
  "    return re.compile(r'\\b({0})\\b'.format(word), "
  'flags=re.IGNORECASE).search\n'
  '\n'
  'def get_DNS():\n'
  "    if not os.path.exists('/etc/resolv.conf'):\n"
  '        return None\n'
  '\n'
  "    with open('/etc/resolv.conf', 'r') as rcfh:\n"
  '        dns_servers = []\n'
  '\n'
  '        for line in rcfh.readlines():\n'
  "            line_split = line.split(' ')\n"
  '\n'
  '            if len(line_split) == 2 and \\\n'
  "               'nameserver' in line_split[0] and line_split[1] != '':\n"
  '                    dns_servers.append(line_split[1].strip())\n'
  '\n'
  '        if len(dns_servers) <= 0:\n'
  "            return '-'\n"
  '\n'
  "        return ', '.join(dns_servers)\n"
  '\n'
  'def find_modem_ports(vid, pid):\n'
  '    ports_modem = []\n'
  "    id_v = ''\n"
  "    id_p = ''\n"
  '\n'
  '    try:\n'
  "        for device_number in os.listdir('/sys/bus/usb/devices'):\n"
  "            device_dir = os.path.join('/sys/bus/usb/devices', "
  'device_number)\n'
  '\n'
  "            if not os.path.exists(os.path.join(device_dir, 'idVendor')):\n"
  '                continue\n'
  '\n'
  "            with open(os.path.join(device_dir, 'idVendor')) as idvfh:\n"
  '                id_v = idvfh.read().strip()\n'
  '\n'
  '            if id_v != vid:\n'
  '                continue\n'
  '\n'
  "            with open(os.path.join(device_dir, 'idProduct')) as idpfh:\n"
  '                id_p = idpfh.read().strip()\n'
  '\n'
  '            if id_p != pid:\n'
  '                continue\n'
  '\n'
  '            for subdir in os.listdir(device_dir):\n'
  "                if not subdir.startswith(device_number + ':'):\n"
  '                    continue\n'
  '\n'
  '                for subsubdir in os.listdir(os.path.join(device_dir, '
  'subdir)):\n'
  "                    if not subsubdir.startswith('ttyUSB'):\n"
  '                        continue\n'
  '\n'
  "                    ports_modem.append(os.path.join('/dev', subsubdir))\n"
  '    except:\n'
  '        pass\n'
  '\n'
  '    return ports_modem\n'
  '\n'
  'def get_signal_quality():\n'
  '    def close_modem(modem):\n'
  '        if modem:\n'
  '            modem.close()\n'
  '            modem = None\n'
  '\n'
  '    def handler_timeout_signal(self, signal_number, frame):\n'
  '        raise Exception\n'
  '\n'
  '    lines = []\n'
  '    ports_modem = []\n'
  '    modem = None\n'
  '    signal_quality = None\n'
  '\n'
  '    if not os.path.exists(FILE_CONFIG_UMTSKEEPER):\n'
  '        return signal_quality\n'
  '\n'
  '    try:\n'
  "        with open(FILE_CONFIG_UMTSKEEPER, 'r') as ucfh:\n"
  '            lines = ucfh.readlines()\n'
  '    except:\n'
  '        return signal_quality\n'
  '\n'
  '    if len(lines) == 0:\n'
  '        return signal_quality\n'
  '\n'
  '    try:\n'
  '        for line in lines:\n'
  "            if ' MODEM=' not in line:\n"
  '                continue\n'
  '\n'
  "            split_sakisops = line.split(' MODEM=')\n"
  '\n'
  '            if len(split_sakisops) != 2:\n'
  '                continue\n'
  '\n'
  '            vid_pid = split_sakisops[1].replace(\'"\', \'\').replace("\'", '
  "'').strip()\n"
  '\n'
  "            split_vid_pid = vid_pid.split(':')\n"
  '\n'
  '            if len(split_vid_pid) != 2:\n'
  '                continue\n'
  '\n'
  '            vid = split_vid_pid[0].strip()\n'
  '            pid = split_vid_pid[1].strip()\n'
  '\n'
  '            if len(vid) != 4 or len(pid) != 4:\n'
  '                continue\n'
  '\n'
  '            ports_modem = find_modem_ports(vid, pid)\n'
  '\n'
  '            if len(ports_modem) > 0:\n'
  '                break\n'
  '    except:\n'
  '        pass\n'
  '\n'
  '    if len(ports_modem) == 0:\n'
  '        return signal_quality\n'
  '\n'
  '    signal.signal(signal.SIGALRM, handler_timeout_signal)\n'
  '\n'
  '    for port in ports_modem:\n'
  '        try:\n'
  '            close_modem(modem)\n'
  '            modem = serial.Serial(port, 9600, timeout = 2, writeTimeout = '
  '2)\n'
  '            # Even though pySerial provides read and write timeouts the '
  'write timeout\n'
  "            # doesn't work if the port is currently being used by some "
  'other process.\n'
  '            # This is why the timeout signal exception mechanism is used '
  'with 4 seconds\n'
  '            # timeout.\n'
  '            signal.alarm(4)\n'
  "            modem.write(b'AT+CSQ\\r')\n"
  '            signal.alarm(0) # Reset timeout signal if write call returned\n'
  '            time.sleep(0.2)\n'
  '            at_response = modem.read(32)\n'
  '\n'
  '            if not at_response:\n'
  '                continue\n'
  '\n'
  "            signal_quality_stripped = at_response.replace('\\r', '')\\\n"
  "                                                 .replace('\\n', '')\\\n"
  "                                                 .replace('OK', '')\\\n"
  "                                                 .replace(' ', '')\\\n"
  '                                                 .strip()\n'
  '            signal_quality_csq_split = '
  "signal_quality_stripped.split('+CSQ:')\n"
  '\n'
  '            if len(signal_quality_csq_split) != 2:\n'
  '                continue\n'
  '\n'
  '            signal_quality_comma_split = '
  "signal_quality_csq_split[1].split(',')\n"
  '\n'
  '            if len(signal_quality_comma_split) != 2:\n'
  '                continue\n'
  '\n'
  '            signal_quality_raw = signal_quality_comma_split[0]\n'
  '\n'
  '            if int(signal_quality_raw) > 1 and int(signal_quality_raw) < '
  '10:\n'
  '                close_modem(modem)\n'
  "                signal_quality = '25%'\n"
  '                break\n'
  '            elif int(signal_quality_raw) > 9 and int(signal_quality_raw) < '
  '15:\n'
  '                close_modem(modem)\n'
  "                signal_quality = '50%'\n"
  '                break\n'
  '            elif int(signal_quality_raw) > 14 and int(signal_quality_raw) < '
  '20:\n'
  '                close_modem(modem)\n'
  "                signal_quality = '75%'\n"
  '                break\n'
  '            elif int(signal_quality_raw) > 19 and int(signal_quality_raw) < '
  '31:\n'
  '                close_modem(modem)\n'
  "                signal_quality = '100%'\n"
  '                break\n'
  '            else:\n'
  '                close_modem(modem)\n'
  '                signal_quality = None\n'
  '                break\n'
  '        except:\n'
  '            signal.alarm(0) # Reset timeout signal\n'
  '\n'
  '    return signal_quality\n'
  '\n'
  'def populate_dict_configuration():\n'
  "    dict_configuration['modem_configured'] = ''\n"
  "    dict_configuration['dial'] = ''\n"
  "    dict_configuration['apn'] = ''\n"
  "    dict_configuration['user'] = ''\n"
  "    dict_configuration['password'] = ''\n"
  "    dict_configuration['sim_card_pin'] = ''\n"
  '\n'
  '    try:\n'
  "        dict_configuration['modem_configured'] = "
  "c_parser_config.get('configuration', 'modem-imei', '')\n"
  '    except:\n'
  '        pass\n'
  '\n'
  '    try:\n'
  "        dict_configuration['dial'] = c_parser_config.get('configuration', "
  "'dial-number', '')\n"
  '    except:\n'
  '        pass\n'
  '\n'
  '    try:\n'
  "        dict_configuration['apn'] = c_parser_config.get('configuration', "
  "'apn', '')\n"
  '    except:\n'
  '        pass\n'
  '\n'
  '    try:\n'
  "        dict_configuration['username'] = "
  "c_parser_config.get('configuration', 'user', '')\n"
  '    except:\n'
  '        pass\n'
  '\n'
  '    try:\n'
  "        dict_configuration['password'] = "
  "c_parser_config.get('configuration', 'password', '')\n"
  '    except:\n'
  '        pass\n'
  '\n'
  '    try:\n'
  "        dict_configuration['sim_card_pin'] = "
  "c_parser_config.get('configuration', 'sim-pin', '')\n"
  '    except:\n'
  '        pass\n'
  '\n'
  'def cidr_to_netmask(cidr):\n'
  '    host_bits = 32 - int(cidr)\n'
  "    return socket.inet_ntoa(struct.pack('!I', (1 << 32) - (1 << "
  'host_bits)))\n'
  '\n'
  'def populate_dict_status():\n'
  "    imei = ''\n"
  "    dict_status['status'] = '-'\n"
  "    dict_status['signal_quality'] = '-'\n"
  "    dict_status['interface'] = '-'\n"
  "    dict_status['ip'] = '-'\n"
  "    dict_status['subnet_mask'] = '-'\n"
  "    dict_status['gateway'] = '-'\n"
  "    dict_status['dns'] = '-'\n"
  '\n'
  '    try:\n'
  "        imei = c_parser_config.get('configuration', 'modem-imei', '')\n"
  '    except:\n'
  '        pass\n'
  '\n'
  "    if imei == '':\n"
  '        return\n'
  '\n'
  '    modem_object_path_list = get_mm_modem_object_paths()\n'
  '\n'
  '    for o in modem_object_path_list:\n'
  '        modem_imei = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME, o),\n'
  '                                    dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_MM_MODEM_INTERFACE, '
  "'EquipmentIdentifier')\n"
  '        if modem_imei != imei:\n'
  '            continue\n'
  '\n'
  '        bearers = []\n'
  '        nm_devices = []\n'
  "        modem_primary_port = ''\n"
  '        modem_state = MM_MODEM_STATE_UNKNOWN\n'
  '\n'
  '        modem_state = \\\n'
  '            dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME, '
  'o),\n'
  '                           dbus_interface = '
  "DBUS_PROPERTIES_INTERFACE).Get(DBUS_MM_MODEM_INTERFACE, 'State')\n"
  '\n'
  '        if modem_state == MM_MODEM_STATE_FAILED or modem_state == -1:\n'
  '            modem_fail_reason = \\\n'
  '                '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME, o),\n'
  '                               dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_MM_MODEM_INTERFACE, '
  "'StateFailedReason')\n"
  '\n'
  '            if modem_fail_reason == '
  'MM_MODEM_STATE_FAILED_REASON_SIM_MISSING:\n'
  "                dict_status['status'] = 'Modem is not usable, SIM missing'\n"
  '            elif modem_fail_reason == '
  'MM_MODEM_STATE_FAILED_REASON_SIM_ERROR:\n'
  "                dict_status['status'] = 'Modem is not usable, SIM error'\n"
  '            else:\n'
  "                dict_status['status'] = 'Modem is not usable, unknown "
  "error'\n"
  '        elif modem_state == MM_MODEM_STATE_UNKNOWN:\n'
  "            dict_status['status'] = 'Modem is in unknown state'\n"
  '        elif modem_state == MM_MODEM_STATE_INITIALIZING:\n'
  "            dict_status['status'] = 'Modem is initializing'\n"
  '        elif modem_state == MM_MODEM_STATE_DISABLED \\\n'
  '             or modem_state == MM_MODEM_STATE_LOCKED:\n'
  "                dict_status['status'] = 'Modem is disabled/locked'\n"
  '\n'
  '                '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME, o),\n'
  '                               dbus_interface = '
  'DBUS_MM_MODEM_INTERFACE).Enable(True)\n'
  '        elif modem_state == MM_MODEM_STATE_DISABLING:\n'
  "            dict_status['status'] = 'Modem is disabling'\n"
  '        elif modem_state == MM_MODEM_STATE_ENABLING:\n'
  "            dict_status['status'] = 'Modem is enabling'\n"
  '        elif modem_state == MM_MODEM_STATE_ENABLED:\n'
  "            dict_status['status'] = 'Modem is enabled'\n"
  '        elif modem_state == MM_MODEM_STATE_REGISTERED \\\n'
  '             or modem_state == MM_MODEM_STATE_SEARCHING:\n'
  "                operator_name = ''\n"
  "                dict_status['status'] = 'Modem is searching for network'\n"
  '                sim_object_path = \\\n'
  '                    '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME, o),\n'
  '                                   dbus_interface = '
  "DBUS_PROPERTIES_INTERFACE).Get(DBUS_MM_MODEM_INTERFACE, 'Sim')\n"
  '                operator_name = \\\n'
  '                    '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME, '
  'sim_object_path),\n'
  '                                   dbus_interface = '
  "DBUS_PROPERTIES_INTERFACE).Get(DBUS_MM_SIM_INTERFACE, 'OperatorName')\n"
  '\n'
  '                if operator_name:\n'
  "                    dict_status['status'] = 'Modem registered to network ' "
  '+ operator_name\n'
  '        elif modem_state == MM_MODEM_STATE_DISCONNECTING:\n'
  "            dict_status['status'] = 'Modem is disconnecting'\n"
  '        elif modem_state == MM_MODEM_STATE_CONNECTING \\\n'
  '             or modem_state == MM_MODEM_STATE_CONNECTED:\n'
  "                operator_name = ''\n"
  "                dict_status['status'] = 'Modem is connecting'\n"
  '\n'
  '                sim_object_path = \\\n'
  '                    '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME, o),\n'
  '                                   dbus_interface = '
  "DBUS_PROPERTIES_INTERFACE).Get(DBUS_MM_MODEM_INTERFACE, 'Sim')\n"
  '                operator_name = \\\n'
  '                    '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME, '
  'sim_object_path),\n'
  '                                   dbus_interface = '
  "DBUS_PROPERTIES_INTERFACE).Get(DBUS_MM_SIM_INTERFACE, 'OperatorName')\n"
  '\n'
  '                if operator_name:\n'
  "                    dict_status['status'] = 'Modem registered and connected "
  "to ' + operator_name\n"
  '        else:\n'
  "            dict_status['status'] = 'Modem is in unknown state'\n"
  '\n'
  "        dict_status['signal_quality'] = \\\n"
  '            '
  'str(dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME, o),\n'
  '                           dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_MM_MODEM_INTERFACE, '
  "'SignalQuality')[0]) + '%'\n"
  '\n'
  '        modem_primary_port = \\\n'
  '            dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME, '
  'o),\n'
  '                           dbus_interface = '
  "DBUS_PROPERTIES_INTERFACE).Get(DBUS_MM_MODEM_INTERFACE, 'PrimaryPort')\n"
  '\n'
  '        nm_devices = \\\n'
  '            dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                           dbus_interface = '
  'DBUS_NM_INTERFACE).GetDevices()\n'
  '\n'
  '        for device_object_path in nm_devices:\n'
  '            device_properties = \\\n'
  '                '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'device_object_path),\n'
  '                               dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).GetAll(DBUS_NM_DEVICE_INTERFACE)\n'
  '\n'
  "            if device_properties['DeviceType'] != NM_DEVICE_TYPE_MODEM:\n"
  '                continue\n'
  '\n'
  "            if device_properties['State'] != NM_DEVICE_STATE_ACTIVATED:\n"
  '                continue\n'
  '\n'
  "            if device_properties['Interface'] != modem_primary_port:\n"
  '                continue\n'
  '\n'
  "            dict_status['interface'] = device_properties['IpInterface'] + ' "
  "(IMEI: ' + modem_imei +')'\n"
  '\n'
  '            ipv4_properties = \\\n'
  '                '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  "device_properties['Ip4Config']),\n"
  '                               dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).GetAll(DBUS_NM_IPV4_CONFIG_INTERFACE)\n'
  '\n'
  "            dict_status['ip'] = "
  "ipv4_properties['AddressData'][0]['address']\n"
  "            dict_status['subnet_mask'] = "
  "cidr_to_netmask(ipv4_properties['AddressData'][0]['prefix'])\n"
  "            dict_status['gateway'] = ipv4_properties['Gateway']\n"
  "            dict_status['dns'] = get_DNS()\n"
  '\n'
  '        break\n'
  '\n'
  'def get_mm_modem_object_paths():\n'
  '    modem_object_path_list = []\n'
  '\n'
  '    xml = dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME,\n'
  '                                                     '
  'DBUS_MM_MODEM_OBJECT_PATH),\n'
  '                         dbus_interface = '
  'DBUS_INTROSPECTABLE_INTERFACE).Introspect()\n'
  '    xml_parsed = minidom.parseString(xml)\n'
  "    items = xml_parsed.getElementsByTagName('node')\n"
  '\n'
  '    items.pop(0)\n'
  '\n'
  '    for i in items:\n'
  '        try:\n'
  "            v = int(i.attributes['name'].value)\n"
  '        except:\n'
  '            continue\n'
  '\n'
  '        '
  "modem_object_path_list.append('/org/freedesktop/ModemManager1/Modem/' + "
  'str(v))\n'
  '\n'
  '    return modem_object_path_list\n'
  '\n'
  'try:\n'
  '    # Handle command GET_STATUS\n'
  "    if ACTION == 'GET_STATUS':\n"
  '        if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_MM:\n'
  '            populate_dict_status()\n'
  '\n'
  '            sys.stdout.write(json.dumps(dict_status))\n'
  '        else:\n'
  '            if not os.path.exists(FILE_TMP_SAKIS3GNET):\n'
  '                p = subprocess.Popen([BINARY_SYSTEMCTL,\n'
  "                                      'status',\n"
  '                                      SERVICE_SYSTEMD_TF_MOBILE_INTERNET],\n'
  '                                      stdout = subprocess.PIPE,\n'
  '                                      stderr = subprocess.PIPE)\n'
  '                p_out_str = p.communicate()[0]\n'
  '\n'
  '                if p_out_str and \\\n'
  "                   'Loaded: loaded' in p_out_str and \\\n"
  "                   'Active: active' in p_out_str:\n"
  "                        dict_status['status'] = 'Connecting...'\n"
  '                else:\n'
  "                    dict_status['status'] = 'Not connected'\n"
  '\n'
  "                dict_status['signal_quality'] = None\n"
  "                dict_status['interface'] = None\n"
  "                dict_status['ip'] = None\n"
  "                dict_status['subnet_mask'] = None\n"
  "                dict_status['gateway'] = None\n"
  "                dict_status['dns'] = get_DNS()\n"
  '                sys.stdout.write(json.dumps(dict_status))\n'
  '                exit(0)\n'
  '\n'
  "            p = subprocess.Popen([BINARY_SAKIS3G, 'info'],\n"
  '                                 stdout = subprocess.PIPE,\n'
  '                                 stderr = subprocess.PIPE)\n'
  '            p_out_str = p.communicate()[0]\n'
  '\n'
  '            if p.returncode != 0:\n'
  '                exit(1)\n'
  '\n'
  '            if not p_out_str:\n'
  '                exit(1)\n'
  '\n'
  '            # The file /tmp/sakis3g.3gnet file might exist when the modem '
  'is not connected.\n'
  '            # For example when a connected modem is disconnected physically '
  'from USB port or got\n'
  '            # disconnected from the network and currently in retry phase.\n'
  "            if 'Not connected' in p_out_str:\n"
  '                _p = subprocess.Popen([BINARY_SYSTEMCTL,\n'
  "                                      'status',\n"
  '                                      SERVICE_SYSTEMD_TF_MOBILE_INTERNET],\n'
  '                                      stdout = subprocess.PIPE,\n'
  '                                      stderr = subprocess.PIPE)\n'
  '                _p_out_str = _p.communicate()[0]\n'
  '\n'
  '                if _p_out_str and \\\n'
  "                   'Loaded: loaded' in _p_out_str and \\\n"
  "                   'Active: active' in _p_out_str:\n"
  "                        dict_status['status'] = 'Connecting...'\n"
  '                else:\n'
  "                    dict_status['status'] = 'Not connected'\n"
  '\n'
  "                dict_status['signal_quality'] = None\n"
  "                dict_status['interface'] = None\n"
  "                dict_status['ip'] = None\n"
  "                dict_status['subnet_mask'] = None\n"
  "                dict_status['gateway'] = None\n"
  "                dict_status['dns'] = get_DNS()\n"
  '                sys.stdout.write(json.dumps(dict_status))\n'
  '                exit(0)\n'
  '\n'
  '            for line in p_out_str.splitlines():\n'
  '                if SPLIT_SEARCH_OPERATOR in line and '
  'len(line.split(SPLIT_SEARCH_OPERATOR)) == 2:\n'
  "                    if line.split(SPLIT_SEARCH_OPERATOR)[0] == '':\n"
  "                        dict_status['status'] = 'Connected to ' + "
  'line.split(SPLIT_SEARCH_OPERATOR)[1]\n'
  '\n'
  '                elif SPLIT_SEARCH_INTERFACE in line and '
  'len(line.split(SPLIT_SEARCH_INTERFACE)) == 2:\n'
  "                    if line.split(SPLIT_SEARCH_INTERFACE)[0] == '':\n"
  "                        dict_status['interface'] = "
  'line.split(SPLIT_SEARCH_INTERFACE)[1]\n'
  '\n'
  '                elif SPLIT_SEARCH_IP in line and '
  'len(line.split(SPLIT_SEARCH_IP)) == 2:\n'
  "                    if line.split(SPLIT_SEARCH_IP)[0] == '':\n"
  "                        dict_status['ip'] = line.split(SPLIT_SEARCH_IP)[1]\n"
  '\n'
  '                elif SPLIT_SEARCH_SUBNET_MASK in line and '
  'len(line.split(SPLIT_SEARCH_SUBNET_MASK)) == 2:\n'
  "                    if line.split(SPLIT_SEARCH_SUBNET_MASK)[0] == '':\n"
  "                        dict_status['subnet_mask'] = "
  'line.split(SPLIT_SEARCH_SUBNET_MASK)[1]\n'
  '\n'
  '                elif SPLIT_SEARCH_GATEWAY in line and '
  'len(line.split(SPLIT_SEARCH_GATEWAY)) == 2:\n'
  "                    if line.split(SPLIT_SEARCH_GATEWAY)[0] == '':\n"
  "                        dict_status['gateway'] = "
  'line.split(SPLIT_SEARCH_GATEWAY)[1]\n'
  '\n'
  "            dict_status['signal_quality'] = get_signal_quality()\n"
  "            dict_status['dns'] = get_DNS()\n"
  '            sys.stdout.write(json.dumps(dict_status))\n'
  '\n'
  '    # Handle command REFRESH\n'
  "    elif ACTION == 'REFRESH':\n"
  '        if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_MM:\n'
  "            imei = ''\n"
  '            list_modem = []\n'
  "            dict_configuration['modem_list'] = None\n"
  '            modem_object_path_list = get_mm_modem_object_paths()\n'
  '\n'
  '            os.system(CMD_MM_SEARCH_MODEMS)\n'
  '\n'
  '            for o in modem_object_path_list:\n'
  '                manufacturer = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME, o),\n'
  '                                              dbus_interface = '
  "DBUS_PROPERTIES_INTERFACE).Get(DBUS_MM_MODEM_INTERFACE, 'Manufacturer')\n"
  '                model = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME, o),\n'
  '                                       dbus_interface = '
  "DBUS_PROPERTIES_INTERFACE).Get(DBUS_MM_MODEM_INTERFACE, 'Model')\n"
  '                imei = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME, o),\n'
  '                                       dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_MM_MODEM_INTERFACE, '
  "'EquipmentIdentifier')\n"
  '\n'
  "                list_modem.append({'name': manufacturer + ' ' + model + ' "
  "(IMEI: ' + imei + ')',\n"
  "                                   'imei': imei})\n"
  '\n'
  "            dict_configuration['modem_list'] = list_modem\n"
  '\n'
  '            populate_dict_configuration()\n'
  '        else:\n'
  '            usb_tty_devices = get_usb_tty_devices()\n'
  '\n'
  '            if usb_tty_devices:\n'
  '                list_modem = []\n'
  '                list_vid_pid = []\n'
  '\n'
  '                for dict_device in usb_tty_devices:\n'
  "                    if dict_device['vid_pid'] in list_vid_pid:\n"
  '                        continue\n'
  '\n'
  "                    list_vid_pid.append(dict_device['vid_pid'])\n"
  "                    list_modem.append({'vid_pid': dict_device['vid_pid'],\n"
  "                                       'name'   : "
  "dict_device['device_name']})\n"
  '\n'
  "                dict_configuration['modem_list'] = list_modem\n"
  '            else:\n'
  "                dict_configuration['modem_list'] = None\n"
  '\n'
  '            # Process configuration file if it exists\n'
  '            if os.path.exists(FILE_CONFIG_UMTSKEEPER):\n'
  "                with open(FILE_CONFIG_UMTSKEEPER, 'r') as ucfh:\n"
  '                    for line in ucfh.readlines():\n'
  '                        if TAG_CONFIG_SAKIS_OPERATORS not in line:\n'
  '                            continue\n'
  '\n'
  "                        splitted_line = line.split('=', 1)\n"
  '\n'
  '                        if len(splitted_line) != 2:\n'
  '                            continue\n'
  '\n'
  "                        splitted_params = splitted_line[1].strip().split(' "
  "')\n"
  '\n'
  '                        if len(splitted_params) < 1:\n'
  '                            continue\n'
  '\n'
  '                        for raw_param in splitted_params:\n'
  "                            splitted_raw_param = raw_param.split('=')\n"
  '\n'
  '                            if len(splitted_raw_param) != 2:\n'
  '                                continue\n'
  '\n'
  '                            if '
  'find_whole_word(TAG_PARAM_USBMODEM)(splitted_raw_param[0]):\n'
  "                                dict_configuration['modem_configured'] =\\\n"
  '                                    '
  'splitted_raw_param[1].strip().replace("\'", \'\').replace(\'"\', \'\')\n'
  '\n'
  '                            elif '
  'find_whole_word(TAG_PARAM_DIAL)(splitted_raw_param[0]):\n'
  "                                dict_configuration['dial'] =\\\n"
  '                                    '
  'splitted_raw_param[1].strip().replace("\'", \'\').replace(\'"\', \'\')\n'
  '\n'
  '                            elif '
  'find_whole_word(TAG_PARAM_APN)(splitted_raw_param[0]):\n'
  "                                dict_configuration['apn'] =\\\n"
  '                                    '
  'splitted_raw_param[1].strip().replace("\'", \'\').replace(\'"\', \'\')\n'
  '\n'
  '                            elif '
  'find_whole_word(TAG_PARAM_APN_USER)(splitted_raw_param[0]):\n'
  "                                dict_configuration['username'] =\\\n"
  '                                    '
  'splitted_raw_param[1].strip().replace("\'", \'\').replace(\'"\', \'\')\n'
  '\n'
  '                            elif '
  'find_whole_word(TAG_PARAM_APN_PASS)(splitted_raw_param[0]):\n'
  "                                dict_configuration['password'] =\\\n"
  '                                    '
  'splitted_raw_param[1].strip().replace("\'", \'\').replace(\'"\', \'\')\n'
  '\n'
  '                            elif '
  'find_whole_word(TAG_PARAM_SIM_PIN)(splitted_raw_param[0]):\n'
  "                                dict_configuration['sim_card_pin'] =\\\n"
  '                                    '
  'splitted_raw_param[1].strip().replace("\'", \'\').replace(\'"\', \'\')\n'
  '\n'
  '        sys.stdout.write(json.dumps(dict_configuration))\n'
  '\n'
  '    # Handle command CONNECT\n'
  "    elif ACTION == 'CONNECT':\n"
  '        if len(sys.argv) < 8:\n'
  '            exit(1)\n'
  '\n'
  '        usb_modem = sys.argv[2]\n'
  '        dial = sys.argv[3]\n'
  '        apn = sys.argv[4]\n'
  '        apn_user = sys.argv[5]\n'
  '        apn_pass = sys.argv[6]\n'
  '        sim_pin = sys.argv[7]\n'
  '\n'
  '        if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_MM:\n'
  "            modem_imei = ''\n"
  "            modem_primary_serial_port = ''\n"
  '            modem_object_path_list = []\n'
  '            c_parser_brickv_gsm = ConfigParser.ConfigParser()\n'
  '            gsm_connection_config_nm = \\\n'
  '                {\n'
  "                    'connection':\n"
  '                    {\n'
  "                        'id': '_tf_brickv_gsm',\n"
  "                        'interface-name': None,\n"
  "                        'type': 'gsm',\n"
  "                        'autoconnect': False\n"
  '                    },\n'
  '\n'
  "                    'gsm':\n"
  '                    {\n'
  "                        'number': None,\n"
  "                        'username': None,\n"
  "                        'password': None,\n"
  "                        'password-flags': dbus.UInt32(0L),\n"
  "                        'apn': None,\n"
  "                        'pin': None,\n"
  "                        'pin-flags': dbus.UInt32(0L)\n"
  '                    }\n'
  '                }\n'
  '\n'
  '            try:\n'
  "                c_parser_config.add_section('configuration')\n"
  '            except:\n'
  '                pass\n'
  '\n'
  "            c_parser_config.set('configuration', 'modem-imei', usb_modem)\n"
  "            c_parser_config.set('configuration', 'dial-number', dial)\n"
  "            c_parser_config.set('configuration', 'apn', apn)\n"
  "            c_parser_config.set('configuration', 'user', apn_user)\n"
  "            c_parser_config.set('configuration', 'password', apn_pass)\n"
  "            c_parser_config.set('configuration', 'sim-pin', sim_pin)\n"
  '\n'
  "            with open(FILE_MOBILE_INTERNET_CONFIG, 'w') as fh:\n"
  '                c_parser_config.write(fh)\n'
  '\n'
  '            os.chmod(FILE_MOBILE_INTERNET_CONFIG, 0600)\n'
  '\n'
  '            modem_object_path_list = get_mm_modem_object_paths()\n'
  '\n'
  '            # Get primary serial port of the target modem\n'
  '            for o in modem_object_path_list:\n'
  '                modem_imei = \\\n'
  '                    '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME, o),\n'
  '                                   dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_MM_MODEM_INTERFACE, '
  "'EquipmentIdentifier')\n"
  '\n'
  '                if modem_imei != usb_modem:\n'
  '                    continue\n'
  '\n'
  '                modem_primary_serial_port = \\\n'
  '                    '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_MM_BUS_NAME, o),\n'
  '                                   dbus_interface = '
  "DBUS_PROPERTIES_INTERFACE).Get(DBUS_MM_MODEM_INTERFACE, 'PrimaryPort')\n"
  '\n'
  '                break\n'
  '\n'
  '            # Deactivate target mobile internet connection\n'
  '            active_connection_object_paths = \\\n'
  '                '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                               dbus_interface = '
  "DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_INTERFACE, 'ActiveConnections')\n"
  '\n'
  '            for active_connection_object_path in '
  'active_connection_object_paths:\n'
  '                connection_object_path = \\\n'
  '                    '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'active_connection_object_path),\n'
  '                                   dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_SETTINGS_CONNECTION_ACTIVE_INTERFACE, '
  "'Connection')\n"
  '                connection_settings = \\\n'
  '                    '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'connection_object_path),\n'
  '                                   dbus_interface = '
  'DBUS_NM_SETTINGS_CONNECTION_INTERFACE).GetSettings()\n'
  '\n'
  "                if connection_settings['connection']['id'] != "
  "'_tf_brickv_gsm':\n"
  '                        continue\n'
  '\n'
  '                '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                               dbus_interface = '
  'DBUS_NM_INTERFACE).DeactivateConnection(active_connection_object_path)\n'
  '\n'
  '            # Delete target mobile internet connection\n'
  '            connection_object_paths = \\\n'
  '                '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_SETTINGS_OBJECT_PATH),\n'
  '                               dbus_interface = '
  "DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_SETTINGS_INTERFACE, 'Connections')\n"
  '\n'
  '            for connection_object_path in connection_object_paths:\n'
  '                connection_settings = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'connection_object_path),\n'
  '                                                     dbus_interface = '
  'DBUS_NM_SETTINGS_CONNECTION_INTERFACE).GetSettings()\n'
  '\n'
  "                if connection_settings['connection']['id'] == "
  "'_tf_brickv_gsm':\n"
  '                    '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'connection_object_path),\n'
  '                                   dbus_interface = '
  'DBUS_NM_SETTINGS_CONNECTION_INTERFACE).Delete()\n'
  '\n'
  '            # Reload connections.\n'
  '            r = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_SETTINGS_OBJECT_PATH),\n'
  '                               dbus_interface = '
  'DBUS_NM_SETTINGS_INTERFACE).ReloadConnections()\n'
  '\n'
  '            if not r:\n'
  '                exit(1)\n'
  '\n'
  '            # Add new mobile internet connection, reload connections and '
  'activate\n'
  "            gsm_connection_config_nm['connection']['interface-name'] = "
  'modem_primary_serial_port\n'
  "            gsm_connection_config_nm['gsm']['number'] = dial\n"
  "            gsm_connection_config_nm['gsm']['username'] = apn_user\n"
  "            gsm_connection_config_nm['gsm']['password'] = apn_pass\n"
  "            gsm_connection_config_nm['gsm']['apn'] = apn\n"
  "            gsm_connection_config_nm['gsm']['pin'] = sim_pin\n"
  '\n'
  '            dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_SETTINGS_OBJECT_PATH),\n'
  '                           dbus_interface = '
  'DBUS_NM_SETTINGS_INTERFACE).AddConnection(gsm_connection_config_nm)\n'
  '\n'
  '            '
  "c_parser_brickv_gsm.read('/etc/NetworkManager/system-connections/_tf_brickv_gsm')\n"
  '\n'
  '            with '
  "open('/etc/NetworkManager/system-connections/_tf_brickv_gsm', 'w') as fh:\n"
  '                c_parser_brickv_gsm.write(fh)\n'
  '\n'
  "            os.system('/usr/bin/nmcli connection reload')\n"
  "            os.system('/usr/bin/nmcli connection up _tf_brickv_gsm')\n"
  '\n'
  '            if os.path.isfile(FILE_UNIT_TIMER):\n'
  '                try:\n'
  "                    os.system('/bin/systemctl stop "
  "tf_mobile_internet_nm.timer &> /dev/null')\n"
  "                    os.system('/bin/systemctl disable "
  "tf_mobile_internet_nm.timer &> /dev/null')\n"
  '                except:\n'
  '                    pass\n'
  '\n'
  '            if os.path.isfile(FILE_UNIT_TF_MOBILE_INTERNET_NM):\n'
  '                try:\n'
  "                    os.system('/bin/systemctl stop "
  "tf_mobile_internet_nm.service &> /dev/null')\n"
  "                    os.system('/bin/systemctl disable "
  "tf_mobile_internet_nm.service &> /dev/null')\n"
  '                except:\n'
  '                    pass\n'
  '\n'
  "            with open(FILE_UNIT_TARGET_SCRIPT, 'w') as fh:\n"
  '                fh.write(PY_TF_MOBILE_INTERNET)\n'
  '\n'
  '            os.chmod(FILE_UNIT_TARGET_SCRIPT, 0755)\n'
  '\n'
  "            with open(FILE_UNIT_TF_MOBILE_INTERNET_NM, 'w') as fh:\n"
  '                fh.write(UNIT_TF_MOBILE_INTERNET)\n'
  '\n'
  '            os.chmod(FILE_UNIT_TF_MOBILE_INTERNET_NM, 0644)\n'
  '\n'
  "            with open(FILE_UNIT_TIMER, 'w') as fh:\n"
  '                fh.write(TIMER_TF_MOBILE_INTERNET)\n'
  '\n'
  '            os.chmod(FILE_UNIT_TIMER, 0644)\n'
  '\n'
  "            os.system('/bin/systemctl enable tf_mobile_internet_nm.service "
  "&> /dev/null')\n"
  "            os.system('/bin/systemctl enable tf_mobile_internet_nm.timer &> "
  "/dev/null')\n"
  "            os.system('/bin/systemctl start tf_mobile_internet_nm.service "
  "&> /dev/null')\n"
  "            os.system('/bin/systemctl start tf_mobile_internet_nm.timer &> "
  "/dev/null')\n"
  '        else:\n'
  '            command_test_connection, configuration_umtskeeper =\\\n'
  '                '
  'prepare_test_command_and_umtskeeper_configuration(usb_modem,\n'
  '                                                                  dial,\n'
  '                                                                  apn,\n'
  '                                                                  '
  'apn_user,\n'
  '                                                                  '
  'apn_pass,\n'
  '                                                                  sim_pin)\n'
  '\n'
  '            # Disable and remove the systemd service if it exists\n'
  '            stop_disable_remove_systemd_service()\n'
  '\n'
  '            # Test connection to verify provided configuration\n'
  '            ret_test_connection = test_connection(command_test_connection)\n'
  '\n'
  '            if ret_test_connection != 0:\n'
  '                exit(ret_test_connection)\n'
  '\n'
  '            # Write umtskeeper configuration file\n'
  "            with open(FILE_CONFIG_UMTSKEEPER, 'w') as ucfh:\n"
  '                ucfh.write(configuration_umtskeeper)\n'
  '\n'
  '            # Write the systemd unit file\n'
  "            with open(FILE_UNIT_TF_MOBILE_INTERNET, 'w') as ufh:\n"
  '                ufh.write(UNIT_SYSTEMD)\n'
  '\n'
  '            os.chmod(FILE_UNIT_TF_MOBILE_INTERNET, 0644)\n'
  '\n'
  '            ret_enable_start_systemd_service = '
  'enable_start_systemd_service()\n'
  '\n'
  '            if ret_enable_start_systemd_service != 0:\n'
  '                exit(ret_enable_start_systemd_service)\n'
  '\n'
  '    else:\n'
  '        exit(1)\n'
  '\n'
  'except SystemExit as e:\n'
  '    # For handling the exit() calls within the try block\n'
  '    exit(e.code)\n'
  '\n'
  'except:\n'
  '    traceback.print_exc()\n'
  '    # For all the other exceptions raised from the try block\n'
  '    exit(1)\n'),
 ('settings_network_apply',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'from sys import argv\n'
  '\n'
  'if len(argv) < 3:\n'
  '    exit (1)\n'
  '\n'
  'iname = unicode(argv[1])\n'
  'iname_previous = unicode(argv[2])\n'
  'itype = unicode(argv[3])\n'
  '\n'
  "if iname_previous and iname_previous != 'None':\n"
  "    cmd_ifdown = '/sbin/ifconfig '+iname_previous+' down 2> /dev/null && "
  "/bin/sleep 1'\n"
  '    os.system(cmd_ifdown)\n'
  '\n'
  "if itype == 'wireless':\n"
  "    cmd_wireless = '/usr/bin/wicd-cli --wireless -x && /bin/sleep 5 &&\\\n"
  "                    /usr/sbin/service wicd restart && /bin/sleep 8 && :'\n"
  '\n'
  '    cmd_wireless_code = os.system(cmd_wireless)\n'
  '\n'
  '    if cmd_wireless_code:\n'
  '        exit (1)\n'
  '\n'
  "elif itype == 'wired':\n"
  "    cmd_wired = '/usr/bin/wicd-cli --wired -x && /bin/sleep 5 &&\\\n"
  '                 /usr/sbin/service wicd restart && /bin/sleep 5 &&\\\n'
  "                 /usr/bin/wicd-cli --wired -c -n0 && :'\n"
  '    cmd_wired_code = os.system(cmd_wired)\n'
  '    if cmd_wired_code:\n'
  '        exit (1)\n'
  'else:\n'
  '    exit (1)\n'),
 ('settings_network_apply_nm',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import dbus\n'
  'import time\n'
  'import json\n'
  'import socket\n'
  'import struct\n'
  'import traceback\n'
  'import ConfigParser\n'
  'from sys import argv\n'
  '\n'
  'NM_DEVICE_TYPE_ETHERNET = 1\n'
  'NM_DEVICE_TYPE_WIFI = 2\n'
  'INTERFACE_TYPE_WIRELESS = 1\n'
  'INTERFACE_TYPE_WIRED = 2\n'
  '\n'
  'DBUS_NM_BUS_NAME = "org.freedesktop.NetworkManager"\n'
  'DBUS_NM_INTERFACE = "org.freedesktop.NetworkManager"\n'
  'DBUS_NM_OBJECT_PATH = "/org/freedesktop/NetworkManager"\n'
  'DBUS_PROPERTIES_INTERFACE = "org.freedesktop.DBus.Properties"\n'
  'DBUS_NM_DEVICE_INTERFACE = "org.freedesktop.NetworkManager.Device"\n'
  'DBUS_NM_AP_INTERFACE = "org.freedesktop.NetworkManager.AccessPoint"\n'
  'DBUS_NM_SETTINGS_INTERFACE = "org.freedesktop.NetworkManager.Settings"\n'
  'DBUS_NM_SETTINGS_OBJECT_PATH = "/org/freedesktop/NetworkManager/Settings"\n'
  'DBUS_NM_DEVICE_WIRELESS_INTERFACE = '
  '"org.freedesktop.NetworkManager.Device.Wireless"\n'
  'DBUS_NM_SETTINGS_CONNECTION_INTERFACE = '
  '"org.freedesktop.NetworkManager.Settings.Connection"\n'
  'DBUS_NM_SETTINGS_CONNECTION_ACTIVE_INTERFACE = '
  "'org.freedesktop.NetworkManager.Connection.Active'\n"
  '\n'
  'HIDDEN_AP_CMD_CON_RELOAD = "/usr/bin/nmcli connection reload"\n'
  'HIDDEN_AP_CMD_UP = "/usr/bin/nmcli connection up _tf_brickv_wifi"\n'
  'HIDDEN_AP_CMD_SET_PSK = "/usr/bin/nmcli connection modify _tf_brickv_wifi '
  'wifi-sec.psk {psk}"\n'
  'HIDDEN_AP_CMD_SET_HIDDEN = "/usr/bin/nmcli connection modify '
  '_tf_brickv_wifi wifi.hidden yes"\n'
  'HIDDEN_AP_CMD_SET_STATIC_DNS = "/usr/bin/nmcli connection modify '
  '_tf_brickv_wifi ipv4.dns \\"{dns}\\""\n'
  'HIDDEN_AP_CMD_SET_WPA_PSK = "/usr/bin/nmcli connection modify '
  '_tf_brickv_wifi wifi-sec.key-mgmt wpa-psk"\n'
  'HIDDEN_AP_CMD_ADD = "/usr/bin/nmcli connection add type wifi con-name '
  '_tf_brickv_wifi ifname {ifname} ssid {ssid}"\n'
  'HIDDEN_AP_CMD_ADD_STATIC_IP = \\\n'
  '    "/usr/bin/nmcli connection add type wifi con-name _tf_brickv_wifi '
  'ifname {ifname} ssid {ssid} ip4 {ip4} gw4 {gw4}"\n'
  '\n'
  'C_PARSER_WIFI = ConfigParser.ConfigParser()\n'
  'C_PARSER_ETHERNET = ConfigParser.ConfigParser()\n'
  'CONNECTED_HIDDEN_WIFI_NETWORKS_FILE_PATH = '
  '"/etc/tf_connected_hidden_wifi_networks"\n'
  'WIFI_CONNECTION_FILE_PATH = '
  '"/etc/NetworkManager/system-connections/_tf_brickv_wifi"\n'
  'ETHERNET_CONNECTION_FILE_PATH = '
  '"/etc/NetworkManager/system-connections/_tf_brickv_ethernet"\n'
  '\n'
  'if len(argv) != 2:\n'
  '    exit (1)\n'
  '\n'
  'def get_ap_object(device_object_paths):\n'
  '    connection_specific_object = None\n'
  '\n'
  '    for device_object_path in device_object_paths:\n'
  '        device_type = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'device_object_path),\n'
  '                                     dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_DEVICE_INTERFACE, "DeviceType")\n'
  '\n'
  '        device_interface = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'device_object_path),\n'
  '                                          dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_DEVICE_INTERFACE, "Interface")\n'
  '\n'
  '        if device_type != NM_DEVICE_TYPE_WIFI:\n'
  '            continue\n'
  '\n'
  '        if device_interface != '
  'connection_config["connection"]["interface-name"]:\n'
  '            continue\n'
  '\n'
  '        ap_object_paths = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'device_object_path),\n'
  '                                         dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_DEVICE_WIRELESS_INTERFACE, '
  '"AccessPoints")\n'
  '\n'
  '        for ap_object_path in ap_object_paths:\n'
  '            ap_ssid = '
  'str(bytearray(dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'ap_object_path),\n'
  '                                    dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_AP_INTERFACE, "Ssid")))\n'
  '\n'
  '            if connection_config["802-11-wireless"]["ssid"] != ap_ssid:\n'
  '                continue\n'
  '\n'
  '            connection_specific_object = ap_object_path\n'
  '\n'
  '            break\n'
  '\n'
  '    if not connection_specific_object:\n'
  '        return None\n'
  '    else:\n'
  '        return connection_specific_object\n'
  '\n'
  'try:\n'
  '    ip_org = None\n'
  '    gw_org = None\n'
  '    psk_org = None\n'
  '    dns_org = None\n'
  '    ssid_org = None\n'
  '    ifname_org = None\n'
  '    prefix_org = None\n'
  '    wifi_address1 = None\n'
  '    hidden_wifi_networks = []\n'
  '    device_object_paths = None\n'
  '    connection_type_to_delete = None\n'
  '    hidden_wifi_network_found = False\n'
  '    connection_specific_object = None\n'
  '    selected_device_object_path = None\n'
  '    added_connection_object_path = None\n'
  '    active_connection_object_path = None\n'
  '    connection_config = json.loads(argv[1])\n'
  '\n'
  '    # Deactivate target WiFi and ethernet connections.\n'
  '    active_connection_object_paths = \\\n'
  '        dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                       dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_INTERFACE, "ActiveConnections")\n'
  '\n'
  '    for active_connection_object_path in active_connection_object_paths:\n'
  '        connection_object_path = \\\n'
  '            dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'active_connection_object_path),\n'
  '                           dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_SETTINGS_CONNECTION_ACTIVE_INTERFACE, '
  '"Connection")\n'
  '        connection_settings = \\\n'
  '            dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'connection_object_path),\n'
  '                           dbus_interface = '
  'DBUS_NM_SETTINGS_CONNECTION_INTERFACE).GetSettings()\n'
  '\n'
  '        if connection_settings["connection"]["id"] != "_tf_brickv_wifi" \\\n'
  '           and connection_settings["connection"]["id"] != '
  '"_tf_brickv_ethernet":\n'
  '                continue\n'
  '\n'
  '        dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                       dbus_interface = '
  'DBUS_NM_INTERFACE).DeactivateConnection(active_connection_object_path)\n'
  '\n'
  '    # Delete target WiFi and ethernet connections.\n'
  '    connection_object_paths = \\\n'
  '        dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_SETTINGS_OBJECT_PATH),\n'
  '                       dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_SETTINGS_INTERFACE, "Connections")\n'
  '\n'
  '    if connection_config["connection"]["type"] == "802-11-wireless":\n'
  '        connection_type_to_delete = "_tf_brickv_wifi"\n'
  '    else:\n'
  '        connection_type_to_delete = "_tf_brickv_ethernet"\n'
  '\n'
  '    for connection_object_path in connection_object_paths:\n'
  '        connection_settings  = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'connection_object_path),\n'
  '                                              dbus_interface = '
  'DBUS_NM_SETTINGS_CONNECTION_INTERFACE).GetSettings()\n'
  '\n'
  '        if connection_settings["connection"]["id"] == '
  'connection_type_to_delete:\n'
  '            dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'connection_object_path),\n'
  '                           dbus_interface = '
  'DBUS_NM_SETTINGS_CONNECTION_INTERFACE).Delete()\n'
  '\n'
  '    # Reload connections.\n'
  '    r = dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_SETTINGS_OBJECT_PATH),\n'
  '                       dbus_interface = '
  'DBUS_NM_SETTINGS_INTERFACE).ReloadConnections()\n'
  '\n'
  '    if not r:\n'
  '        exit(1)\n'
  '\n'
  '    # Get the originals.\n'
  '    dns_org = connection_config["ipv4"]["dns"]\n'
  '    gw_org = connection_config["ipv4"]["gateway"]\n'
  '    ip_org = connection_config["ipv4"]["address-data"]["address"]\n'
  '    ifname_org = connection_config["connection"]["interface-name"]\n'
  '    prefix_org = connection_config["ipv4"]["address-data"]["prefix"]\n'
  '\n'
  '    # Add new connection.\n'
  '\n'
  '    # Prepare DNS entry.\n'
  '    if connection_config["ipv4"]["dns"] != "":\n'
  '        connection_config["ipv4"]["dns"] = \\\n'
  '            [dbus.UInt32(struct.unpack("L", '
  'socket.inet_aton(connection_config["ipv4"]["dns"]))[0])]\n'
  '    else:\n'
  '        connection_config["ipv4"]["dns"] = [dbus.UInt32(0L)]\n'
  '\n'
  '    # Prepare address information entry.\n'
  '    connection_config["ipv4"]["address-data"]["prefix"] = \\\n'
  '        dbus.UInt32(connection_config["ipv4"]["address-data"]["prefix"])\n'
  '    connection_config["ipv4"]["address-data"] = \\\n'
  '        dbus.Array([connection_config["ipv4"]["address-data"]], signature = '
  'dbus.Signature("a{sv}"))\n'
  '\n'
  '    # Get list of all available devices.\n'
  '    device_object_paths = \\\n'
  '        dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                       dbus_interface = DBUS_NM_INTERFACE).GetDevices()\n'
  '\n'
  '    # Do WiFi connection specific preparations.\n'
  '    if connection_config["connection"]["type"] == "802-11-wireless":\n'
  '        # Get the originals.\n'
  '        ssid_org = connection_config["802-11-wireless"]["ssid"]\n'
  '\n'
  '        if "802-11-wireless-security" in connection_config:\n'
  '            psk_org = connection_config["802-11-wireless-security"]["psk"]\n'
  '\n'
  '        # Prepare SSID entry.\n'
  '        connection_config["802-11-wireless"]["ssid"] = \\\n'
  '            dbus.ByteArray(connection_config["802-11-wireless"]["ssid"])\n'
  '\n'
  '        # Prepare PSK flags entry.\n'
  '        if "802-11-wireless-security" in connection_config:\n'
  '            connection_config["802-11-wireless-security"]["psk-flags"] = '
  '\\\n'
  '                '
  'dbus.UInt32(connection_config["802-11-wireless-security"]["psk-flags"])\n'
  '\n'
  "        if not connection_config['802-11-wireless']['hidden']:\n"
  '            connection_specific_object = '
  'get_ap_object(device_object_paths)\n'
  '\n'
  '            if not connection_specific_object:\n'
  '                # Try to request scan with all available WiFi interfaces. '
  'Ignore errors.\n'
  '                for device_object_path in device_object_paths:\n'
  '                    device_type = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'device_object_path),\n'
  '                                                 dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_DEVICE_INTERFACE, "DeviceType")\n'
  '\n'
  '                    if device_type != NM_DEVICE_TYPE_WIFI:\n'
  '                        continue\n'
  '\n'
  '                    try:\n'
  '                        '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'device_object_path),\n'
  '                                       dbus_interface = '
  'DBUS_NM_DEVICE_WIRELESS_INTERFACE).RequestScan(dbus.Array([], signature = '
  'dbus.Signature("a{sv}")))\n'
  '                    except:\n'
  '                        continue\n'
  '\n'
  '                connection_specific_object = '
  'get_ap_object(device_object_paths)\n'
  '\n'
  '                if not connection_specific_object:\n'
  '                    exit(1)\n'
  '\n'
  '    # Do ethernet connection specific preparations.\n'
  '    elif connection_config["connection"]["type"] == "802-3-ethernet":\n'
  '        connection_specific_object = "/"\n'
  '    else:\n'
  '        exit(1)\n'
  '\n'
  '    for device_object_path in device_object_paths:\n'
  '        interface = \\\n'
  '            dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'device_object_path),\n'
  '                           dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_DEVICE_INTERFACE, "Interface")\n'
  '\n'
  '        if interface == connection_config["connection"]["interface-name"]:\n'
  '            selected_device_object_path = device_object_path\n'
  '\n'
  '            break\n'
  '\n'
  '    if not selected_device_object_path:\n'
  '        exit(1)\n'
  '\n'
  '    if connection_config["connection"]["type"] == "802-11-wireless":\n'
  "        if not connection_config['802-11-wireless']['hidden']:\n"
  '            added_connection_object_path, active_connection_object_path = '
  '\\\n'
  '                '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                               dbus_interface = '
  'DBUS_NM_INTERFACE).AddAndActivateConnection(connection_config,\n'
  '                                                                                            '
  'device_object_path,\n'
  '                                                                                            '
  'connection_specific_object)\n'
  '            if not added_connection_object_path or \\\n'
  '               not active_connection_object_path:\n'
  '                    exit(1)\n'
  '        else:\n'
  '            if connection_config["ipv4"]["method"] == "manual":\n'
  '                os.system(HIDDEN_AP_CMD_ADD_STATIC_IP.format(ifname = '
  'ifname_org,\n'
  '                                                             ssid = '
  'ssid_org,\n'
  '                                                             ip4 = ip_org + '
  '"/" + str(prefix_org),\n'
  '                                                             gw4 = '
  'gw_org))\n'
  '\n'
  '                os.system(HIDDEN_AP_CMD_SET_STATIC_DNS.format(dns = '
  'dns_org))\n'
  '            else:\n'
  '                os.system(HIDDEN_AP_CMD_ADD.format(ifname = ifname_org, '
  'ssid = ssid_org))\n'
  '\n'
  '            os.system(HIDDEN_AP_CMD_SET_HIDDEN)\n'
  '\n'
  '            if "802-11-wireless-security" in connection_config:\n'
  '                os.system(HIDDEN_AP_CMD_SET_WPA_PSK)\n'
  '                os.system(HIDDEN_AP_CMD_SET_PSK.format(psk = psk_org))\n'
  '\n'
  '                C_PARSER_WIFI.read(WIFI_CONNECTION_FILE_PATH)\n'
  '\n'
  '                C_PARSER_WIFI.set("wifi-security", "psk-flags", 0)\n'
  '                C_PARSER_WIFI.set("wifi-security", "auth-alg", "open")\n'
  '\n'
  '                with open(WIFI_CONNECTION_FILE_PATH, "w") as fh:\n'
  '                    C_PARSER_WIFI.write(fh)\n'
  '\n'
  '            if os.path.isfile(ETHERNET_CONNECTION_FILE_PATH):\n'
  '                C_PARSER_ETHERNET.read(ETHERNET_CONNECTION_FILE_PATH)\n'
  '                C_PARSER_ETHERNET.set("connection", "autoconnect", '
  '"false")\n'
  '\n'
  '                with open(ETHERNET_CONNECTION_FILE_PATH, "w") as '
  'fh_connection:\n'
  '                    C_PARSER_ETHERNET.write(fh_connection)\n'
  '\n'
  '            os.system(HIDDEN_AP_CMD_CON_RELOAD)\n'
  '\n'
  '            time.sleep(2)\n'
  '\n'
  '            os.system(HIDDEN_AP_CMD_UP)\n'
  '\n'
  '            if not '
  'os.path.isfile(CONNECTED_HIDDEN_WIFI_NETWORKS_FILE_PATH):\n'
  '                with open(CONNECTED_HIDDEN_WIFI_NETWORKS_FILE_PATH, "w") as '
  'fh:\n'
  '                    fh.write(ssid_org + "\\n")\n'
  '            else:\n'
  '                with open(CONNECTED_HIDDEN_WIFI_NETWORKS_FILE_PATH, "r") as '
  'fh:\n'
  '                    hidden_wifi_networks = fh.readlines()\n'
  '\n'
  '                for n in hidden_wifi_networks:\n'
  '                    if ssid_org == n.strip():\n'
  '                        hidden_wifi_network_found = True\n'
  '\n'
  '                        break\n'
  '\n'
  '                if not hidden_wifi_network_found:\n'
  '                    with open(CONNECTED_HIDDEN_WIFI_NETWORKS_FILE_PATH, '
  '"a") as fh:\n'
  '                        fh.write(ssid_org + "\\n")\n'
  '    else:\n'
  '        added_connection_object_path, active_connection_object_path = \\\n'
  '            dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                           dbus_interface = '
  'DBUS_NM_INTERFACE).AddAndActivateConnection(connection_config,\n'
  '                                                                                        '
  'device_object_path,\n'
  '                                                                                        '
  'connection_specific_object)\n'
  '\n'
  '        if not added_connection_object_path or \\\n'
  '           not active_connection_object_path:\n'
  '                exit(1)\n'
  '\n'
  '    # Reload connections.\n'
  '    r = dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_SETTINGS_OBJECT_PATH),\n'
  '                       dbus_interface = '
  'DBUS_NM_SETTINGS_INTERFACE).ReloadConnections()\n'
  '\n'
  '    if not r:\n'
  '        exit(1)\n'
  '\n'
  '    # FIXME: For WiFi connections after the connection is initially '
  'activated,\n'
  '    #\n'
  '    # 1. Rename the connection file on the disk as the name is derived\n'
  '    #    from the AP SSID.\n'
  '    # 2. Modify some security and IPv4 related parameters in the conection '
  'file.\n'
  '    # 3. Deactivate previously activated connection.\n'
  '    # 4. Reload connections.\n'
  '    # 5. Connect to the modified WiFi connection.\n'
  '    #\n'
  '    # This is required because Network Manager handles WiFi connections\n'
  '    # in a dynamic way which heavily depends on the found APs and their\n'
  '    # parameters. Even though the required connection parameters are\n'
  '    # specified they are being modified after adding and activating the\n'
  '    # connection.\n'
  '\n'
  '    if connection_config["connection"]["type"] == "802-11-wireless":\n'
  "        if not connection_config['802-11-wireless']['hidden']:\n"
  '            data_connection_file = None\n'
  '            added_connection_settings = \\\n'
  '                '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'added_connection_object_path),\n'
  '                               dbus_interface = '
  'DBUS_NM_SETTINGS_CONNECTION_INTERFACE).GetSettings()\n'
  '\n'
  '            # Deactivate connection.\n'
  '            try:\n'
  '                '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                               dbus_interface = '
  'DBUS_NM_INTERFACE).DeactivateConnection(active_connection_object_path)\n'
  '            except:\n'
  '                pass\n'
  '\n'
  '            # Rename connection file.\n'
  '            os.rename("/etc/NetworkManager/system-connections/" + '
  'added_connection_settings["connection"]["id"],\n'
  '                      WIFI_CONNECTION_FILE_PATH)\n'
  '\n'
  '            # Modify connection file.\n'
  '            C_PARSER_WIFI.read(WIFI_CONNECTION_FILE_PATH)\n'
  '\n'
  '            C_PARSER_WIFI.set("connection", "id", "_tf_brickv_wifi")\n'
  '            C_PARSER_WIFI.set("connection",\n'
  '                              "interface-name",\n'
  '                              '
  'connection_config["connection"]["interface-name"])\n'
  '\n'
  '            if "802-11-wireless-security" in connection_config:\n'
  '                C_PARSER_WIFI.set("wifi-security", "auth-alg", "open")\n'
  '                C_PARSER_WIFI.set("wifi-security", "psk-flags", 0)\n'
  '                C_PARSER_WIFI.set("wifi-security", "psk", '
  'connection_config["802-11-wireless-security"]["psk"])\n'
  '\n'
  '            if connection_config["ipv4"]["method"] == "manual":\n'
  '                wifi_address1 = '
  'connection_config["ipv4"]["address-data"][0]["address"] + \\\n'
  '                                "/" + \\\n'
  '                                '
  'str(connection_config["ipv4"]["address-data"][0]["prefix"]) + \\\n'
  '                                "," + \\\n'
  '                                connection_config["ipv4"]["gateway"]\n'
  '\n'
  '                C_PARSER_WIFI.set("ipv4", "address1", wifi_address1)\n'
  '                C_PARSER_WIFI.set("ipv4", "dns", dns_org + ";")\n'
  '                C_PARSER_WIFI.set("ipv4", "method", "manual")\n'
  '            else:\n'
  '                C_PARSER_WIFI.set("ipv4", "method", "auto")\n'
  '\n'
  '            with open(WIFI_CONNECTION_FILE_PATH, "w") as fh_connection:\n'
  '                C_PARSER_WIFI.write(fh_connection)\n'
  '\n'
  '            if os.path.isfile(ETHERNET_CONNECTION_FILE_PATH):\n'
  '                C_PARSER_ETHERNET.read(ETHERNET_CONNECTION_FILE_PATH)\n'
  '                C_PARSER_ETHERNET.set("connection", "autoconnect", '
  '"false")\n'
  '\n'
  '                with open(ETHERNET_CONNECTION_FILE_PATH, "w") as '
  'fh_connection:\n'
  '                    C_PARSER_ETHERNET.write(fh_connection)\n'
  '\n'
  '            # Reload connections.\n'
  '            r = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_SETTINGS_OBJECT_PATH),\n'
  '                               dbus_interface = '
  'DBUS_NM_SETTINGS_INTERFACE).ReloadConnections()\n'
  '\n'
  '            if not r:\n'
  '                exit(1)\n'
  '\n'
  '            active_connection_object_path = \\\n'
  '                '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                               dbus_interface = '
  'DBUS_NM_INTERFACE).ActivateConnection(added_connection_object_path,\n'
  '                                                                                      '
  'device_object_path,\n'
  '                                                                                      '
  'connection_specific_object)\n'
  '    else:\n'
  '        if os.path.isfile(WIFI_CONNECTION_FILE_PATH):\n'
  '            C_PARSER_WIFI.read(WIFI_CONNECTION_FILE_PATH)\n'
  '            C_PARSER_WIFI.set("connection", "autoconnect", "false")\n'
  '\n'
  '            with open(WIFI_CONNECTION_FILE_PATH, "w") as fh_connection:\n'
  '                C_PARSER_WIFI.write(fh_connection)\n'
  '\n'
  '        # Reload connections.\n'
  '        r = dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_SETTINGS_OBJECT_PATH),\n'
  '                           dbus_interface = '
  'DBUS_NM_SETTINGS_INTERFACE).ReloadConnections()\n'
  'except:\n'
  '    traceback.print_exc()\n'
  '    exit(1)\n'),
 ('settings_network_change_hostname',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'from sys import argv\n'
  'from reconfigure.configs import HostsConfig\n'
  '\n'
  "CMD_DHCLIENT = '/sbin/dhclient &> /dev/null'\n"
  "FILE_PATH_HOSTS = '/etc/hosts'\n"
  "BIN_HOSTNAMECTL = '/usr/bin/hostnamectl'\n"
  "CMD_HOSTNAMECTL = BIN_HOSTNAMECTL + ' --static set-hostname '\n"
  '\n'
  'if len(argv) < 3:\n'
  '    exit(1)\n'
  '\n'
  'if not os.path.isfile(FILE_PATH_HOSTS) or not '
  'os.path.isfile(BIN_HOSTNAMECTL):\n'
  '    exit(1)\n'
  '\n'
  'hostname_old = unicode(argv[1])\n'
  'hostname_new = unicode(argv[2])\n'
  '\n'
  'if hostname_old == hostname_new:\n'
  '    exit(0)\n'
  '\n'
  'CMD_HOSTNAMECTL = CMD_HOSTNAMECTL + hostname_new\n'
  '\n'
  'try:\n'
  '    config_hosts = HostsConfig(path=FILE_PATH_HOSTS)\n'
  '    config_hosts.load()\n'
  '\n'
  '    for host_entry in config_hosts.tree.hosts:\n'
  '        for alias in host_entry.aliases:\n'
  '            if alias.name != hostname_old:\n'
  '                continue\n'
  '\n'
  '            alias.name = hostname_new\n'
  '\n'
  '        if host_entry.name != hostname_old:\n'
  '            continue\n'
  '\n'
  '        host_entry.name = hostname_new\n'
  '\n'
  '    config_hosts.save()\n'
  '\n'
  '    if os.system(CMD_HOSTNAMECTL) != 0:\n'
  '        exit(1)\n'
  '\n'
  '    try:\n'
  '        os.system(CMD_DHCLIENT)\n'
  '    except:\n'
  '        pass\n'
  'except:\n'
  '    exit(1)\n'),
 ('settings_network_get_interfaces',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import sys\n'
  'import json\n'
  'import netifaces\n'
  'import subprocess\n'
  '\n'
  "return_dict = {'wireless': None,\n"
  "               'wired': None,\n"
  "               'wireless_links': None}\n"
  '\n'
  'wl_links_dict = {}\n'
  'lwireless = []\n'
  '_lwired = []\n'
  '\n'
  'for intf in netifaces.interfaces():\n'
  "    if os.path.isdir('/sys/class/net/'+intf+'/wireless') and intf not in "
  'lwireless:\n'
  '        lwireless.append(intf)\n'
  '        continue\n'
  '\n'
  "    if not os.path.isfile('/sys/class/net/'+intf+'/type'):\n"
  '        continue\n'
  '\n'
  "    with open('/sys/class/net/'+intf+'/type', 'r') as fhtype:\n"
  '        if int(fhtype.read().strip()) == 1 and intf not in _lwired:\n'
  '            _lwired.append(intf)\n'
  '\n'
  'if len(lwireless) > 0:\n'
  "    return_dict['wireless'] = lwireless\n"
  '    for wl_intf in lwireless:\n'
  "        cmd_get_link = '/sbin/iwconfig '+wl_intf+' | /usr/bin/head -n2'\n"
  '        ps_get_link = subprocess.Popen(cmd_get_link, shell=True, '
  'stdout=subprocess.PIPE)\n'
  '        cmd_output = ps_get_link.communicate()[0]\n'
  '        if ps_get_link.returncode:\n'
  '            exit (1)\n'
  '\n'
  "        wl_links_dict[wl_intf] =  {'name': wl_intf,\n"
  "                                   'status': False,\n"
  "                                   'essid': None,\n"
  "                                   'bssid': None}\n"
  '\n'
  '        cmd_output_lines = cmd_output.splitlines()\n'
  '        if len(cmd_output_lines) >= 2 and cmd_output:\n'
  "            if 'off/any' in cmd_output_lines[0] or 'unassociated' in "
  'cmd_output_lines[0]:\n'
  '                continue\n'
  "            cmd_output_line0_array = cmd_output_lines[0].split(' ')\n"
  "            cmd_output_line1_array = cmd_output_lines[1].split('Access "
  "Point: ')\n"
  '            if len(cmd_output_line0_array) >= 0:\n'
  '                for token in cmd_output_line0_array:\n'
  "                    if 'ESSID:' in token:\n"
  "                        _associated_essid = token.split(':')[1]\n"
  '                        associated_essid = '
  'unicode(_associated_essid[1:-1])\n'
  '                        if len(cmd_output_line1_array) > 0:\n'
  '                            associated_bssid = '
  'cmd_output_line1_array[-1:][0].strip()\n'
  "                            wl_links_dict[wl_intf] =  {'name': wl_intf,\n"
  "                                                       'status': True,\n"
  "                                                       'essid': "
  'associated_essid,\n'
  "                                                       'bssid': "
  'associated_bssid}\n'
  '\n'
  '# Remove localhost and tunnel interfaces\n'
  'lwired = []\n'
  '\n'
  'for wired in _lwired:\n'
  "    if wired.startswith('tun') or wired == 'lo':\n"
  '        continue\n'
  '\n'
  '    lwired.append(wired)\n'
  '\n'
  'if len(lwired) > 0:\n'
  "    return_dict['wired'] = lwired\n"
  'if len(wl_links_dict) > 0:\n'
  " return_dict['wireless_links'] = wl_links_dict\n"
  '\n'
  "print json.dumps(return_dict, separators=(',', ':'))\n"),
 ('settings_network_status',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import dbus\n'
  'import json\n'
  'import socket\n'
  'import netifaces\n'
  'from wicd import dbusmanager as wicd_dbusmanager\n'
  'from wicd import misc as wicd_misc\n'
  '\n'
  'TYPE_WIRELESS = 1\n'
  'TYPE_WIRED = 2\n'
  '\n'
  'return_dict = {}\n'
  "return_dict['cstat_hostname'] = None\n"
  "return_dict['cstat_status'] = None\n"
  "return_dict['cstat_intf_active'] = {'name': None, 'type': None, 'ip': None, "
  "'mask': None}\n"
  "return_dict['cstat_gateway'] = None\n"
  "return_dict['cstat_dns'] = None\n"
  '\n'
  'def get_active_interface_info(interface, type):\n'
  '    try:\n'
  '        ip = '
  "netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']\n"
  '        netmask = '
  "netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['netmask']\n"
  "        return_dict['cstat_intf_active']['name'] = interface\n"
  "        return_dict['cstat_intf_active']['type'] = type\n"
  "        return_dict['cstat_intf_active']['ip'] = ip\n"
  "        return_dict['cstat_intf_active']['mask'] = netmask\n"
  '    except:\n'
  "        return_dict['cstat_intf_active']['name'] = None\n"
  "        return_dict['cstat_intf_active']['type'] = '-'\n"
  "        return_dict['cstat_intf_active']['ip'] = '-'\n"
  "        return_dict['cstat_intf_active']['mask'] = '-'\n"
  '\n'
  '# Get hostname\n'
  'try:\n'
  '    hname = unicode(socket.gethostname())\n'
  "    if hname != '':\n"
  "        return_dict['cstat_hostname'] = hname\n"
  'except:\n'
  '    exit(1)\n'
  '\n'
  '# Get status and active interface\n'
  'try:\n'
  "    # Initially return_dict['cstat_intf_active']['name'] None because this "
  'field is\n'
  '    # appended with interface type and to avoid appending interface type '
  'when no interface is found\n'
  "    return_dict['cstat_intf_active']['name'] = None\n"
  "    return_dict['cstat_intf_active']['type'] = '-'\n"
  "    return_dict['cstat_intf_active']['ip'] = '-'\n"
  "    return_dict['cstat_intf_active']['mask'] = '-'\n"
  '\n'
  '    bus = dbus.SystemBus()\n'
  "    daemon = dbus.Interface(bus.get_object('org.wicd.daemon', "
  "'/org/wicd/daemon'), 'org.wicd.daemon')\n"
  '    wicd_dbusmanager.connect_to_dbus()\n'
  '    status = '
  "wicd_dbusmanager.get_dbus_ifaces()['daemon'].GetConnectionStatus()\n"
  '\n'
  '    if status[0] == wicd_misc.NOT_CONNECTED:\n'
  "        return_dict['cstat_status'] = 'Not connected'\n"
  '\n'
  '    elif status[0] == wicd_misc.CONNECTING:\n'
  "        return_dict['cstat_status'] = 'Connecting "
  "({0})...'.format(status[1][0][0].upper() + status[1][0][1:])\n"
  '\n'
  '    elif status[0] == wicd_misc.WIRELESS:\n'
  '        try:\n'
  '            iwconfig = '
  "wicd_dbusmanager.get_dbus_ifaces()['wireless'].GetIwconfig()\n"
  '            ap = '
  "unicode(wicd_dbusmanager.get_dbus_ifaces()['wireless'].GetCurrentNetwork(iwconfig))\n"
  '        except:\n'
  "            return_dict['cstat_status'] = '-'\n"
  '        else:\n'
  "            if ap != 'None':\n"
  '                ap_array = ap.split(\'"\')\n'
  '\n'
  '                if len(ap_array) > 1:\n'
  "                    return_dict['cstat_status'] = 'Connected to ' + "
  'ap_array[0]\n'
  '                else:\n'
  "                    return_dict['cstat_status'] = 'Connected to ' + ap\n"
  '\n'
  '                '
  'get_active_interface_info(unicode(daemon.GetWirelessInterface()), '
  'TYPE_WIRELESS)\n'
  '\n'
  '            else:\n'
  "                return_dict['cstat_status'] = '-'\n"
  '\n'
  '    elif status == wicd_misc.WIRED:\n'
  "        return_dict['cstat_status'] = 'Connected'\n"
  '        get_active_interface_info(unicode(daemon.GetWiredInterface()), '
  'TYPE_WIRED)\n'
  '\n'
  '    elif status[0] == wicd_misc.SUSPENDED:\n'
  "        return_dict['cstat_status'] = 'Suspended'\n"
  '\n'
  '    else:\n'
  '        if status[0] == 3:\n'
  "            return_dict['cstat_status'] = 'Connected'\n"
  '            get_active_interface_info(unicode(daemon.GetWiredInterface()), '
  'TYPE_WIRED)\n'
  '        else:\n'
  "            return_dict['cstat_status'] = 'Unknown "
  "({0})'.format(status[0])\n"
  'except:\n'
  "    return_dict['cstat_status'] = '-'\n"
  '\n'
  '# Get default gateway\n'
  'try:\n'
  '    gws = netifaces.gateways()\n'
  '\n'
  "    if 'default' in gws and netifaces.AF_INET in gws['default']:\n"
  "        return_dict['cstat_gateway']  = "
  "gws['default'][netifaces.AF_INET][0]\n"
  'except:\n'
  '    exit(1)\n'
  '\n'
  '# Get DNS\n'
  'try:\n'
  "    with open('/etc/resolv.conf', 'r') as rcf:\n"
  '        dns_servers = []\n'
  '        lines = rcf.readlines()\n'
  '\n'
  '        for l in lines:\n'
  "            l_splitted = l.split(' ')\n"
  '\n'
  "            if l_splitted[0] == 'nameserver' and l_splitted[1] != '':\n"
  '                dns_servers.append(l_splitted[1].strip())\n'
  '\n'
  '        if len(dns_servers) <= 0:\n'
  "            return_dict['cstat_dns'] = '-'\n"
  '        else:\n'
  "            return_dict['cstat_dns'] = ', '.join(dns_servers)\n"
  'except:\n'
  "    return_dict['cstat_dns'] = None\n"
  '\n'
  "print(json.dumps(return_dict, separators=(',', ':')))\n"),
 ('settings_network_status_nm',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import dbus\n'
  'import json\n'
  'import socket\n'
  'import traceback\n'
  'import netifaces\n'
  '\n'
  'TYPE_WIRELESS = 1\n'
  'TYPE_WIRED = 2\n'
  '\n'
  'NM_STATE_UNKNOWN = 0\n'
  'NM_STATE_ASLEEP = 10\n'
  'NM_STATE_DISCONNECTED = 20\n'
  'NM_STATE_DISCONNECTING = 30\n'
  'NM_STATE_CONNECTING = 40\n'
  'NM_STATE_CONNECTED_LOCAL = 50\n'
  'NM_STATE_CONNECTED_SITE = 60\n'
  'NM_STATE_CONNECTED_GLOBAL = 70\n'
  '\n'
  'NM_DEVICE_TYPE_ETHERNET = 1\n'
  'NM_DEVICE_TYPE_WIFI = 2\n'
  '\n'
  'DBUS_NM_BUS_NAME = "org.freedesktop.NetworkManager"\n'
  'DBUS_NM_INTERFACE = "org.freedesktop.NetworkManager"\n'
  'DBUS_NM_OBJECT_PATH = "/org/freedesktop/NetworkManager"\n'
  'DBUS_PROPERTIES_INTERFACE = "org.freedesktop.DBus.Properties"\n'
  'DBUS_NM_DEVICE_INTERFACE = "org.freedesktop.NetworkManager.Device"\n'
  'DBUS_NM_AP_INTERFACE = "org.freedesktop.NetworkManager.AccessPoint"\n'
  'DBUS_NM_DEVICE_WIRELESS_INTERFACE = '
  '"org.freedesktop.NetworkManager.Device.Wireless"\n'
  '\n'
  'return_dict = {}\n'
  'return_dict["cstat_hostname"] = None\n'
  'return_dict["cstat_status"] = None\n'
  'return_dict["cstat_intf_active"] = {"name": None, "type": None, "ip": None, '
  '"mask": None}\n'
  'return_dict["cstat_gateway"] = None\n'
  'return_dict["cstat_dns"] = None\n'
  '\n'
  'nm_state = None\n'
  'gw_interface = None\n'
  'gw_interface_type = None\n'
  '\n'
  'try:\n'
  '    if DBUS_NM_BUS_NAME not in dbus.SystemBus().list_names():\n'
  '        # NetworkManager not running\n'
  '        exit(1)\n'
  'except:\n'
  '    traceback.print_exc()\n'
  '    exit(1)\n'
  '\n'
  'def get_active_interface_info(interface, intf_type):\n'
  '    try:\n'
  '        ip = '
  'netifaces.ifaddresses(interface)[netifaces.AF_INET][0]["addr"]\n'
  '        netmask = '
  'netifaces.ifaddresses(interface)[netifaces.AF_INET][0]["netmask"]\n'
  '        return_dict["cstat_intf_active"]["name"] = interface\n'
  '        return_dict["cstat_intf_active"]["type"] = intf_type\n'
  '        return_dict["cstat_intf_active"]["ip"] = ip\n'
  '        return_dict["cstat_intf_active"]["mask"] = netmask\n'
  '    except:\n'
  '        return_dict["cstat_intf_active"]["name"] = None\n'
  '        return_dict["cstat_intf_active"]["type"] = "-"\n'
  '        return_dict["cstat_intf_active"]["ip"] = "-"\n'
  '        return_dict["cstat_intf_active"]["mask"] = "-"\n'
  '\n'
  '# Get hostname\n'
  'try:\n'
  '    hname = unicode(socket.gethostname())\n'
  '    if hname != "":\n'
  '        return_dict["cstat_hostname"] = hname\n'
  'except:\n'
  '    traceback.print_exc()\n'
  '    exit(1)\n'
  '\n'
  '# Get default gateway\n'
  'try:\n'
  '    gws = netifaces.gateways()\n'
  '\n'
  '    if "default" in gws and netifaces.AF_INET in gws["default"]:\n'
  '        return_dict["cstat_gateway"] = '
  'gws["default"][netifaces.AF_INET][0]\n'
  '        gw_interface = gws["default"][netifaces.AF_INET][1]\n'
  '\n'
  '        nm_devices = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                                    dbus_interface = '
  'DBUS_NM_INTERFACE).GetDevices()\n'
  '\n'
  '        for device_object_path in nm_devices:\n'
  '            interface_name = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'device_object_path),\n'
  '                                            dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_DEVICE_INTERFACE, "Interface")\n'
  '\n'
  '            interface_type = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'device_object_path),\n'
  '                                            dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_DEVICE_INTERFACE, "DeviceType")\n'
  '\n'
  '            if interface_name != gw_interface:\n'
  '                continue\n'
  '\n'
  '            if interface_type == NM_DEVICE_TYPE_ETHERNET:\n'
  '                gw_interface_type = TYPE_WIRED\n'
  '\n'
  '                break\n'
  '\n'
  '            elif interface_type == NM_DEVICE_TYPE_WIFI:\n'
  '                gw_interface_type = TYPE_WIRELESS\n'
  '\n'
  '                break\n'
  '\n'
  '        get_active_interface_info(gw_interface, gw_interface_type)\n'
  'except:\n'
  '    traceback.print_exc()\n'
  '    exit(1)\n'
  '\n'
  '# Get status and active interface\n'
  'try:\n'
  '    if gw_interface != None and gw_interface_type != None:\n'
  '        nm_state = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                                  dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_INTERFACE, "State")\n'
  '\n'
  '        return_dict["cstat_status"] = ""\n'
  '\n'
  '        if nm_state == NM_STATE_UNKNOWN:\n'
  '            return_dict["cstat_status"] = "Unknown"\n'
  '        elif nm_state == NM_STATE_ASLEEP:\n'
  '            return_dict["cstat_status"] = "Sleeping"\n'
  '        elif nm_state == NM_STATE_DISCONNECTED:\n'
  '            return_dict["cstat_status"] = "Disconnected"\n'
  '        elif nm_state == NM_STATE_DISCONNECTING:\n'
  '            return_dict["cstat_status"] = "Disconnecting"\n'
  '        elif nm_state == NM_STATE_CONNECTING:\n'
  '            return_dict["cstat_status"] = "Connecting"\n'
  '        elif nm_state == NM_STATE_CONNECTED_LOCAL:\n'
  '            return_dict["cstat_status"] = "Disconnected"\n'
  '        elif nm_state == NM_STATE_CONNECTED_SITE:\n'
  '            return_dict["cstat_status"] = "Connected Local"\n'
  '        elif nm_state == NM_STATE_CONNECTED_GLOBAL:\n'
  '            return_dict["cstat_status"] = "Connected"\n'
  '        else:\n'
  '            return_dict["cstat_status"] = "Unknown"\n'
  '\n'
  '        if nm_state == NM_STATE_CONNECTED_SITE or nm_state == '
  'NM_STATE_CONNECTED_GLOBAL:\n'
  '            if gw_interface_type == TYPE_WIRELESS:\n'
  '                nm_devices = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                                            dbus_interface = '
  'DBUS_NM_INTERFACE).GetDevices()\n'
  '                for device_object in nm_devices:\n'
  '                    device_name = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'device_object),\n'
  '                                                 dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_DEVICE_INTERFACE, "Interface")\n'
  '\n'
  '                    device_type = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'device_object),\n'
  '                                                 dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_DEVICE_INTERFACE, "DeviceType")\n'
  '\n'
  '                    if device_type != NM_DEVICE_TYPE_WIFI or device_name != '
  'gw_interface:\n'
  '                        continue\n'
  '\n'
  '                    device_active_ap_object_path = \\\n'
  '                        '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'device_object),\n'
  '                                       dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_DEVICE_WIRELESS_INTERFACE, '
  '"ActiveAccessPoint")\n'
  '\n'
  '                    active_ap_ssid = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'device_active_ap_object_path),\n'
  '                                                    dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_AP_INTERFACE, "Ssid")\n'
  '\n'
  '                    return_dict["cstat_status"] = '
  'return_dict["cstat_status"] + " to " + str(bytearray(active_ap_ssid))\n'
  '\n'
  '                    break\n'
  '    else:\n'
  '        return_dict["cstat_status"] = "Disconnected"\n'
  'except:\n'
  '    return_dict["cstat_status"] = "-"\n'
  '\n'
  '# Get DNS\n'
  'try:\n'
  '    with open("/etc/resolv.conf", "r") as rcf:\n'
  '        dns_servers = []\n'
  '        lines = rcf.readlines()\n'
  '\n'
  '        for l in lines:\n'
  '            l_splitted = l.split(" ")\n'
  '\n'
  '            if l_splitted[0] == "nameserver" and l_splitted[1] != "":\n'
  '                dns_servers.append(l_splitted[1].strip())\n'
  '\n'
  '        if len(dns_servers) <= 0:\n'
  '            return_dict["cstat_dns"] = "-"\n'
  '        else:\n'
  '            return_dict["cstat_dns"] = ", ".join(dns_servers)\n'
  'except:\n'
  '    return_dict["cstat_dns"] = None\n'
  '\n'
  'print(json.dumps(return_dict, separators=(",", ":")))\n'),
 ('settings_network_wireless_scan',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import dbus\n'
  'import ConfigParser\n'
  'import json\n'
  'import subprocess\n'
  'import time\n'
  'from sys import argv\n'
  '\n'
  'if len(argv) < 3:\n'
  '    exit (1)\n'
  '\n'
  'iname_scan_with = unicode(argv[1])\n'
  'iname_restore_to = unicode(argv[2])\n'
  '\n'
  'return_dict = None\n'
  '\n'
  'config = ConfigParser.ConfigParser()\n'
  '\n'
  'def set_wireless_interface(interface):\n'
  '    try:\n'
  "        with open('/etc/wicd/manager-settings.conf', 'r') as msfp_r:\n"
  '            config.readfp(msfp_r)\n'
  "            with open('/etc/wicd/manager-settings.conf', 'w') as msfp_w:\n"
  "                config.set('Settings', 'wireless_interface', interface)\n"
  '                config.write(msfp_w)\n'
  "                wicd_restart_cmd = '/usr/sbin/service wicd restart && :'\n"
  '                wicd_restart_ps = subprocess.Popen(wicd_restart_cmd, '
  'shell=True, stdout=subprocess.PIPE)\n'
  '                wicd_restart_ps.communicate()[0]\n'
  '                if wicd_restart_ps.returncode:\n'
  '                    exit(1)\n'
  '                else:\n'
  '                    time.sleep(10)\n'
  '    except:\n'
  '        exit(1)\n'
  '\n'
  'set_wireless_interface(iname_scan_with)\n'
  '\n'
  'try:\n'
  '    bus = dbus.SystemBus()\n'
  "    wireless = dbus.Interface(bus.get_object('org.wicd.daemon', "
  "'/org/wicd/daemon/wireless'),\n"
  "                                             'org.wicd.daemon.wireless')\n"
  '    wireless.Scan(True)\n'
  'except:\n'
  '    set_wireless_interface(iname_restore_to)\n'
  '    exit(1)\n'
  '\n'
  'return_dict = {}\n'
  '\n'
  'for network_id in range(0, wireless.GetNumberOfNetworks()):\n'
  '    try:\n'
  "        essid = wireless.GetWirelessProperty(network_id, 'essid')\n"
  "        bssid = wireless.GetWirelessProperty(network_id, 'bssid')\n"
  "        channel = wireless.GetWirelessProperty(network_id, 'channel')\n"
  "        quality = wireless.GetWirelessProperty(network_id, 'quality')\n"
  '\n'
  '        # Ignore hidden wireless networks in scan result.\n'
  "        if str(essid) == '<hidden>':\n"
  '            continue\n'
  '\n'
  '        if wireless.GetWirelessProperty(network_id, "encryption"):\n'
  "            encryption = 'On'\n"
  '            encryption_method = wireless.GetWirelessProperty(network_id, '
  '"encryption_method")\n'
  '        else:\n'
  "            encryption = 'Off'\n"
  '            encryption_method = None\n'
  '\n'
  '        ap_exists = False\n'
  '\n'
  '        for key, ap in return_dict.items():\n'
  "            if str(ap['bssid']) == str(bssid):\n"
  '                ap_exists = True\n'
  '                break\n'
  '\n'
  '        if ap_exists:\n'
  '            continue\n'
  '\n'
  "        _apdict = {'essid':essid,\n"
  "                   'bssid':bssid,\n"
  "                   'channel':channel,\n"
  "                   'encryption':encryption,\n"
  "                   'encryption_method':encryption_method,\n"
  "                   'quality':quality}\n"
  '\n'
  '        return_dict[network_id] = _apdict\n'
  '    except:\n'
  '        pass\n'
  '\n'
  'set_wireless_interface(iname_restore_to)\n'
  '\n'
  "print json.dumps(return_dict, separators=(',', ':'))\n"),
 ('settings_network_wireless_scan_cache',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import json\n'
  'import dbus\n'
  'import subprocess\n'
  '\n'
  'return_dict = None\n'
  '\n'
  'try:\n'
  '    bus = dbus.SystemBus()\n'
  "    wireless = dbus.Interface(bus.get_object('org.wicd.daemon', "
  "'/org/wicd/daemon/wireless'),\n"
  "                                             'org.wicd.daemon.wireless')\n"
  'except:\n'
  '    exit(1)\n'
  '\n'
  'return_dict = {}\n'
  '\n'
  'for network_id in range(0, wireless.GetNumberOfNetworks()):\n'
  '    try:\n'
  "        essid = wireless.GetWirelessProperty(network_id, 'essid')\n"
  "        bssid = wireless.GetWirelessProperty(network_id, 'bssid')\n"
  "        channel = wireless.GetWirelessProperty(network_id, 'channel')\n"
  "        quality = wireless.GetWirelessProperty(network_id, 'quality')\n"
  '\n'
  '        # Ignore hidden wireless networks in scan result.\n'
  "        if str(essid) == '<hidden>':\n"
  '            continue\n'
  '\n'
  '        if wireless.GetWirelessProperty(network_id, "encryption"):\n'
  "            encryption = 'On'\n"
  '            encryption_method = wireless.GetWirelessProperty(network_id, '
  '"encryption_method")\n'
  '        else:\n'
  "            encryption = 'Off'\n"
  '            encryption_method = None\n'
  '\n'
  '        ap_exists = False\n'
  '\n'
  '        for key, ap in return_dict.items():\n'
  "            if str(ap['bssid']) == str(bssid):\n"
  '                ap_exists = True\n'
  '                break\n'
  '\n'
  '        if ap_exists:\n'
  '            continue\n'
  '\n'
  "        _apdict = {'essid':essid,\n"
  "                   'bssid':bssid,\n"
  "                   'channel':channel,\n"
  "                   'encryption':encryption,\n"
  "                   'encryption_method':encryption_method,\n"
  "                   'quality':quality}\n"
  '\n'
  '        return_dict[network_id] = _apdict\n'
  '    except:\n'
  '        pass\n'
  '\n'
  "print(json.dumps(return_dict, separators=(',', ':')))\n"),
 ('settings_network_wireless_scan_nm',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import json\n'
  'import dbus\n'
  'import traceback\n'
  'import ConfigParser\n'
  '\n'
  'NM_DEVICE_TYPE_WIFI = 2\n'
  '\n'
  'NM_802_11_AP_SEC_NONE_MASK = 0x00000000\n'
  'NM_802_11_AP_SEC_KEY_MGMT_PSK_MASK = 0x00000100\n'
  '\n'
  'DBUS_NM_BUS_NAME = "org.freedesktop.NetworkManager"\n'
  'DBUS_NM_INTERFACE = "org.freedesktop.NetworkManager"\n'
  'DBUS_NM_OBJECT_PATH = "/org/freedesktop/NetworkManager"\n'
  'DBUS_PROPERTIES_INTERFACE = "org.freedesktop.DBus.Properties"\n'
  'DBUS_NM_DEVICE_INTERFACE = "org.freedesktop.NetworkManager.Device"\n'
  'DBUS_NM_AP_INTERFACE = "org.freedesktop.NetworkManager.AccessPoint"\n'
  'DBUS_NM_DEVICE_WIRELESS_INTERFACE = '
  '"org.freedesktop.NetworkManager.Device.Wireless"\n'
  '\n'
  'FILE_CONNECTED_HIDDEN_WIFI_NETWORKS = '
  '"/etc/tf_connected_hidden_wifi_networks"\n'
  '\n'
  'return_dict = {}\n'
  'config_wifi_ssid = None\n'
  'config_wifi_hidden = None\n'
  'c_parser_wifi_config = None\n'
  'connected_hidden_wifi_networks = []\n'
  '\n'
  'if os.path.isfile(FILE_CONNECTED_HIDDEN_WIFI_NETWORKS):\n'
  '    hidden_wifi_networks = []\n'
  '\n'
  '    with open(FILE_CONNECTED_HIDDEN_WIFI_NETWORKS, "r") as fh:\n'
  '        hidden_wifi_networks = fh.readlines()\n'
  '\n'
  '    if len(hidden_wifi_networks) > 0:\n'
  '        for n in hidden_wifi_networks:\n'
  '            connected_hidden_wifi_networks.append(n.strip())\n'
  '\n'
  'if '
  'os.path.isfile("/etc/NetworkManager/system-connections/_tf_brickv_wifi"):\n'
  '    try:\n'
  '        c_parser_wifi_config = ConfigParser.ConfigParser()\n'
  '\n'
  '        '
  'c_parser_wifi_config.read("/etc/NetworkManager/system-connections/_tf_brickv_wifi")\n'
  '\n'
  '        config_wifi_ssid = c_parser_wifi_config.get("wifi", "ssid", "")\n'
  '        config_wifi_hidden = c_parser_wifi_config.get("wifi", "hidden", '
  '"")\n'
  '    except:\n'
  '        pass\n'
  '\n'
  'try:\n'
  '    if DBUS_NM_BUS_NAME not in dbus.SystemBus().list_names():\n'
  '        # NetworkManager not running\n'
  '        exit(1)\n'
  'except:\n'
  '    traceback.print_exc()\n'
  '    exit(1)\n'
  '\n'
  'try:\n'
  '    # Try to request scan with all available WiFi interfaces. Ignore '
  'errors.\n'
  '    nm_devices = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'DBUS_NM_OBJECT_PATH),\n'
  '                                dbus_interface = '
  'DBUS_NM_INTERFACE).GetDevices()\n'
  '\n'
  '    try:\n'
  '        for device_object_path in nm_devices:\n'
  '            device_type = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'device_object_path),\n'
  '                                         dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_DEVICE_INTERFACE, "DeviceType")\n'
  '\n'
  '            if device_type != NM_DEVICE_TYPE_WIFI:\n'
  '                continue\n'
  '\n'
  '            device_type = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'device_object_path),\n'
  '                                         dbus_interface = '
  'DBUS_NM_DEVICE_WIRELESS_INTERFACE).RequestScan(dbus.Array([], signature = '
  'dbus.Signature("a{sv}")))\n'
  '    except:\n'
  '        pass\n'
  '\n'
  '    for device_object_path in nm_devices:\n'
  '        device_type = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'device_object_path),\n'
  '                                     dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).Get(DBUS_NM_DEVICE_INTERFACE, "DeviceType")\n'
  '\n'
  '        if device_type != NM_DEVICE_TYPE_WIFI:\n'
  '            continue\n'
  '\n'
  '        ap_object_paths = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'device_object_path),\n'
  '                                         dbus_interface = '
  'DBUS_NM_DEVICE_WIRELESS_INTERFACE).GetAccessPoints()\n'
  '\n'
  '        for ap_object_path in ap_object_paths:\n'
  '            nidx = ap_object_path.split("/")[-1]\n'
  '            found_in_connected_hidden_wifi_networks = False\n'
  '            ap_props = '
  'dbus.Interface(dbus.SystemBus().get_object(DBUS_NM_BUS_NAME, '
  'ap_object_path),\n'
  '                                      dbus_interface = '
  'DBUS_PROPERTIES_INTERFACE).GetAll(DBUS_NM_AP_INTERFACE)\n'
  '\n'
  '            if c_parser_wifi_config \\\n'
  '               and config_wifi_ssid \\\n'
  '               and config_wifi_hidden:\n'
  '                    if config_wifi_ssid == '
  'str(bytearray(ap_props["Ssid"])):\n'
  '                        continue\n'
  '\n'
  '            for n in connected_hidden_wifi_networks:\n'
  '                if n == str(bytearray(ap_props["Ssid"])):\n'
  '                    found_in_connected_hidden_wifi_networks = True\n'
  '\n'
  '                    break\n'
  '\n'
  '            if found_in_connected_hidden_wifi_networks:\n'
  '                continue\n'
  '\n'
  '            flags = 0\n'
  '            only_wpa1 = False\n'
  '\n'
  '            if ap_props["WpaFlags"] == 0 and ap_props["RsnFlags"] == 0:\n'
  '                encryption = "Off"\n'
  '                encryption_method = "Unsupported"\n'
  '            else:\n'
  '                if ap_props["RsnFlags"] == 0:\n'
  '                    flags = ap_props["WpaFlags"]\n'
  '                    only_wpa1 = True\n'
  '                elif ap_props["WpaFlags"] == 0:\n'
  '                    flags = ap_props["RsnFlags"]\n'
  '                else:\n'
  '                    flags = ap_props["RsnFlags"]\n'
  '\n'
  '                if flags & NM_802_11_AP_SEC_NONE_MASK:\n'
  '                    encryption = "Off"\n'
  '                else:\n'
  '                    encryption = "On"\n'
  '\n'
  '                if not flags & NM_802_11_AP_SEC_NONE_MASK:\n'
  '                    if flags & NM_802_11_AP_SEC_KEY_MGMT_PSK_MASK:\n'
  '                        if only_wpa1:\n'
  '                            encryption_method = "WPA1"\n'
  '                        else:\n'
  '                            encryption_method = "WPA2"\n'
  '                    else:\n'
  '                        encryption_method = "Unsupported"\n'
  '\n'
  '            apdict = {\n'
  '                        "essid": str(bytearray(ap_props["Ssid"])),\n'
  '                        "bssid": ap_props["HwAddress"],\n'
  '                        "channel": ap_props["Frequency"],\n'
  '                        "encryption": encryption,\n'
  '                        "encryption_method": encryption_method,\n'
  '                        "quality": int(ap_props["Strength"])\n'
  '                     }\n'
  '\n'
  '            return_dict[nidx] = apdict\n'
  '\n'
  '        if len(return_dict) > 0:\n'
  '            break\n'
  'except:\n'
  '    traceback.print_exc()\n'
  '    exit(1)\n'
  '\n'
  'print(json.dumps(return_dict, separators=(",", ":")))\n'),
 ('settings_server_monitoring',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import re\n'
  'import sys\n'
  'import json\n'
  'import stat\n'
  'import shlex\n'
  'import socket\n'
  'import argparse\n'
  'import subprocess\n'
  'from sys import argv\n'
  'from time import sleep\n'
  'from pynag import Model\n'
  'from distutils.version import StrictVersion\n'
  'from tinkerforge.ip_connection import IPConnection\n'
  '\n'
  'from tinkerforge.bricklet_ptc import BrickletPTC\n'
  'try:\n'
  '    from tinkerforge.bricklet_ptc_v2 import BrickletPTCV2\n'
  '    got_ptc_v2  = True\n'
  'except ImportError:\n'
  '    got_ptc_v2 = False\n'
  '\n'
  'from tinkerforge.bricklet_humidity import BrickletHumidity\n'
  'try:\n'
  '    from tinkerforge.bricklet_humidity_v2 import BrickletHumidityV2\n'
  '    got_humidity_v2  = True\n'
  'except ImportError:\n'
  '    got_humidity_v2 = False\n'
  '\n'
  'from tinkerforge.bricklet_temperature import BrickletTemperature\n'
  'try:\n'
  '    from tinkerforge.bricklet_temperature_v2 import BrickletTemperatureV2\n'
  '    got_temperature_v2  = True\n'
  'except ImportError:\n'
  '    got_temperature_v2 = False\n'
  '\n'
  'from tinkerforge.bricklet_ambient_light import BrickletAmbientLight\n'
  'try:\n'
  '    from tinkerforge.bricklet_ambient_light_v2 import '
  'BrickletAmbientLightV2\n'
  '    got_ambient_light_v2 = True\n'
  'except ImportError:\n'
  '    got_ambient_light_v2 = False\n'
  '\n'
  'try:\n'
  '    from tinkerforge.bricklet_ambient_light_v3 import '
  'BrickletAmbientLightV3\n'
  '    got_ambient_light_v3 = True\n'
  'except ImportError:\n'
  '    got_ambient_light_v3 = False\n'
  '\n'
  'from tinkerforge.bricklet_io4 import BrickletIO4\n'
  'try:\n'
  '    from tinkerforge.bricklet_io4_v2 import BrickletIO4V2\n'
  '    got_io4_v2 = True\n'
  'except ImportError:\n'
  '    got_io4_v2 = False\n'
  '\n'
  'from tinkerforge.bricklet_industrial_digital_in_4 import '
  'BrickletIndustrialDigitalIn4\n'
  'try:\n'
  '    from tinkerforge.bricklet_industrial_digital_in_4_v2 import '
  'BrickletIndustrialDigitalIn4V2\n'
  '    got_idi4_v2 = True\n'
  'except ImportError:\n'
  '    got_idi4_v2 = False\n'
  '\n'
  'if len(argv) < 2:\n'
  '    exit(1)\n'
  '\n'
  'IMAGE_VERSION = None\n'
  "MIN_VERSION_WITH_NAGIOS4 = StrictVersion('1.10')\n"
  '\n'
  "with open('/etc/tf_image_version', 'r') as f:\n"
  "    IMAGE_VERSION = StrictVersion(f.read().split(' ')[0].strip())\n"
  '\n'
  "FILE_PATH_CHECK_SCRIPT = '/usr/local/bin/check_tinkerforge.py'\n"
  '\n'
  'if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_NAGIOS4:\n'
  '    FILE_PATH_TF_NAGIOS_CONFIGURATION = '
  "'/usr/local/nagios/etc/objects/tinkerforge.cfg'\n"
  'else:\n'
  '    FILE_PATH_TF_NAGIOS_CONFIGURATION = '
  "'/etc/nagios3/conf.d/tinkerforge.cfg'\n"
  '\n'
  "SCRIPT_TINKERFORGE_CHECK = '''#!/usr/bin/env python2\n"
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import time\n'
  'import argparse\n'
  'from tinkerforge.ip_connection import IPConnection\n'
  '\n'
  'from tinkerforge.bricklet_ptc import BrickletPTC\n'
  'try:\n'
  '    from tinkerforge.bricklet_ptc_v2 import BrickletPTCV2\n'
  '    got_ptc_v2  = True\n'
  'except ImportError:\n'
  '    got_ptc_v2 = False\n'
  '\n'
  'from tinkerforge.bricklet_humidity import BrickletHumidity\n'
  'try:\n'
  '    from tinkerforge.bricklet_humidity_v2 import BrickletHumidityV2\n'
  '    got_humidity_v2  = True\n'
  'except ImportError:\n'
  '    got_humidity_v2 = False\n'
  '\n'
  'from tinkerforge.bricklet_temperature import BrickletTemperature\n'
  'try:\n'
  '    from tinkerforge.bricklet_temperature_v2 import BrickletTemperatureV2\n'
  '    got_temperature_v2  = True\n'
  'except ImportError:\n'
  '    got_temperature_v2 = False\n'
  '\n'
  'from tinkerforge.bricklet_ambient_light import BrickletAmbientLight\n'
  'try:\n'
  '    from tinkerforge.bricklet_ambient_light_v2 import '
  'BrickletAmbientLightV2\n'
  '    got_ambient_light_v2 = True\n'
  'except ImportError:\n'
  '    got_ambient_light_v2 = False\n'
  '\n'
  'try:\n'
  '    from tinkerforge.bricklet_ambient_light_v3 import '
  'BrickletAmbientLightV3\n'
  '    got_ambient_light_v3 = True\n'
  'except ImportError:\n'
  '    got_ambient_light_v3 = False\n'
  '\n'
  'from tinkerforge.bricklet_io4 import BrickletIO4\n'
  'try:\n'
  '    from tinkerforge.bricklet_io4_v2 import BrickletIO4V2\n'
  '    got_io4_v2 = True\n'
  'except ImportError:\n'
  '    got_io4_v2 = False\n'
  '\n'
  'from tinkerforge.bricklet_industrial_digital_in_4 import '
  'BrickletIndustrialDigitalIn4\n'
  'try:\n'
  '    from tinkerforge.bricklet_industrial_digital_in_4_v2 import '
  'BrickletIndustrialDigitalIn4V2\n'
  '    got_idi4_v2 = True\n'
  'except ImportError:\n'
  '    got_idi4_v2 = False\n'
  '\n'
  'RETURN_CODE_OK       = 0\n'
  'RETURN_CODE_WARNING  = 1\n'
  'RETURN_CODE_CRITICAL = 2\n'
  'RETURN_CODE_UNKNOWN  = 3\n'
  '\n'
  "BRICKLET_PTC_2_WIRE    = 'ptc_2_wire'\n"
  "BRICKLET_PTC_3_WIRE    = 'ptc_3_wire'\n"
  "BRICKLET_PTC_4_WIRE    = 'ptc_4_wire'\n"
  "BRICKLET_TEMPERATURE   = 'temperature'\n"
  "BRICKLET_HUMIDITY      = 'humidity'\n"
  "BRICKLET_HUMIDITY_TEMP = 'humidity_temp'\n"
  "BRICKLET_AMBIENT_LIGHT = 'ambient_light'\n"
  "BRICKLET_IO4           = 'io4'\n"
  "BRICKLET_IDI4          = 'idi4'\n"
  '\n'
  "MESSAGE_CRITICAL_ERROR_CONNECTING = 'CRITICAL - Error occured while "
  "connecting'\n"
  "MESSAGE_CRITICAL_AUTHENTICATION_FAILED = 'CRITICAL - Connection "
  "authentication failed'\n"
  "MESSAGE_CRITICAL_NO_PTC_CONNECTED = 'CRITICAL - No PTC sensor connected'\n"
  "MESSAGE_CRITICAL_ERROR_GETTING_PTC_STATE = 'CRITICAL - Error getting PTC "
  "sensor connection state'\n"
  "MESSAGE_CRITICAL_ERROR_SETTING_PTC_MODE = 'CRITICAL - Error setting PTC "
  "wire mode'\n"
  "MESSAGE_CRITICAL_ERROR_READING_VALUE = 'CRITICAL - Error reading value'\n"
  "MESSAGE_CRITICAL_ERROR_GETTING_DEVICE_IDENTITY = 'CRITICAL - Error getting "
  "device identity'\n"
  "MESSAGE_CRITICAL_ERROR_SETTING_AMBIENT_LIGHT_CONFIGURATION = 'CRITICAL - "
  "Error setting Ambient Light Bricklet configuration'\n"
  "MESSAGE_CRITICAL_ERROR_SETTING_IO4_CONFIGURATION = 'CRITICAL - Error "
  "setting IO4 Bricklet configuration'\n"
  "MESSAGE_CRITICAL_ERROR_SETTING_IDI4_CONFIGURATION = 'CRITICAL - Error "
  "setting Industrial Digital In 4 Bricklet configuration'\n"
  '\n'
  "MESSAGE_CRITICAL_READING_TOO_HIGH = 'CRITICAL - Reading too high - %s %s'\n"
  "MESSAGE_CRITICAL_READING_TOO_LOW = 'CRITICAL - Reading too low - %s %s'\n"
  "MESSAGE_WARNING_READING_IS_HIGH = 'WARNING - Reading is high - %s %s'\n"
  "MESSAGE_WARNING_READING_IS_LOW = 'WARNING - Reading is low - %s %s'\n"
  "MESSAGE_OK_READING = 'OK - %s %s'\n"
  "MESSAGE_CRITICAL_IO4_IDI4 = 'CRITICAL - CH0 = %s, CH1 = %s, CH2 = %s, CH3 = "
  "%s'\n"
  "MESSAGE_WARNING_IO4_IDI4  = 'WARNING - CH0 = %s, CH1 = %s, CH2 = %s, CH3 = "
  "%s'\n"
  "MESSAGE_OK_IO4_IDI4 = 'OK - CH0 = %s, CH1 = %s, CH2 = %s, CH3 = %s'\n"
  "MESSAGE_UNKNOWN_READING = 'UNKNOWN - Unknown state'\n"
  '\n'
  'global args\n'
  'global ipcon\n'
  'global return_code\n'
  'global return_message\n'
  'args               = None\n'
  'ipcon              = None\n'
  'return_code        = None\n'
  'return_message     = None\n'
  '\n'
  'def handle_result(message, code):\n'
  '    try:\n'
  '        ipcon.disconnect()\n'
  '    except:\n'
  '        pass\n'
  '\n'
  '    global return_code\n'
  '    global return_message\n'
  '    return_message = message\n'
  '    return_code = code\n'
  '\n'
  'def cb_connect(connect_reason):\n'
  '    if args.secret:\n'
  '        try:\n'
  '            ipcon.authenticate(args.secret)\n'
  '        except:\n'
  '            handle_result(MESSAGE_CRITICAL_AUTHENTICATION_FAILED,\n'
  '                          RETURN_CODE_CRITICAL)\n'
  '\n'
  '    read(args.bricklet,\n'
  '         args.uid,\n'
  '         args.warning,\n'
  '         args.critical,\n'
  '         args.warning2,\n'
  '         args.critical2)\n'
  '\n'
  'def connect():\n'
  '    try:\n'
  '        ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, '
  'cb_connect)\n'
  '        ipcon.connect(args.host, args.port)\n'
  '        time.sleep(1)\n'
  '    except:\n'
  '        handle_result(MESSAGE_CRITICAL_ERROR_CONNECTING,\n'
  '                      RETURN_CODE_CRITICAL)\n'
  '\n'
  'def read(bricklet, uid, warning, critical, warning2, critical2):\n'
  '    reading = None\n'
  '\n'
  '    if bricklet == BRICKLET_PTC_2_WIRE or\\\n'
  '       bricklet == BRICKLET_PTC_3_WIRE or\\\n'
  '       bricklet == BRICKLET_PTC_4_WIRE:\n'
  "            unit = '°C'\n"
  '            bricklet_ptc = BrickletPTC(uid, ipcon)\n'
  '\n'
  '            if got_ptc_v2:\n'
  '                device_identifier = None\n'
  '\n'
  '                try:\n'
  '                    device_identifier = '
  'bricklet_ptc.get_identity().device_identifier\n'
  '                except:\n'
  '                    bricklet_ptc = None\n'
  '                    '
  'handle_result(MESSAGE_CRITICAL_ERROR_GETTING_DEVICE_IDENTITY,\n'
  '                                  RETURN_CODE_CRITICAL)\n'
  '\n'
  '                    return\n'
  '\n'
  '                if device_identifier == BrickletPTCV2.DEVICE_IDENTIFIER:\n'
  '                    bricklet_ptc = BrickletPTCV2(uid, ipcon)\n'
  '\n'
  '            if bricklet_ptc != None:\n'
  '                try:\n'
  '                    if not bricklet_ptc.is_sensor_connected():\n'
  '                        bricklet_ptc = None\n'
  '                        handle_result(MESSAGE_CRITICAL_NO_PTC_CONNECTED,\n'
  '                                      RETURN_CODE_CRITICAL)\n'
  '\n'
  '                        return\n'
  '                except:\n'
  '                    bricklet_ptc = None\n'
  '                    '
  'handle_result(MESSAGE_CRITICAL_ERROR_GETTING_PTC_STATE,\n'
  '                                  RETURN_CODE_CRITICAL)\n'
  '\n'
  '                    return\n'
  '\n'
  '                try:\n'
  '                    if bricklet == BRICKLET_PTC_2_WIRE:\n'
  '                        '
  'bricklet_ptc.set_wire_mode(bricklet_ptc.WIRE_MODE_2)\n'
  '                    elif bricklet == BRICKLET_PTC_3_WIRE:\n'
  '                        '
  'bricklet_ptc.set_wire_mode(bricklet_ptc.WIRE_MODE_3)\n'
  '                    elif bricklet == BRICKLET_PTC_4_WIRE:\n'
  '                        '
  'bricklet_ptc.set_wire_mode(bricklet_ptc.WIRE_MODE_4)\n'
  '                except:\n'
  '                    bricklet_ptc = None\n'
  '                    handle_result(MESSAGE_CRITICAL_ERROR_SETTING_PTC_MODE,\n'
  '                                  RETURN_CODE_CRITICAL)\n'
  '\n'
  '                    return\n'
  '\n'
  '                try:\n'
  '                    reading = bricklet_ptc.get_temperature() / 100.0\n'
  '                except:\n'
  '                    handle_result(MESSAGE_CRITICAL_ERROR_READING_VALUE,\n'
  '                                  RETURN_CODE_CRITICAL)\n'
  '\n'
  '                    return\n'
  '\n'
  '    elif bricklet == BRICKLET_TEMPERATURE:\n'
  "        unit = '°C'\n"
  '        bricklet_temperature = BrickletTemperature(uid, ipcon)\n'
  '\n'
  '        if got_temperature_v2:\n'
  '            device_identifier = None\n'
  '\n'
  '            try:\n'
  '                device_identifier = '
  'bricklet_temperature.get_identity().device_identifier\n'
  '            except:\n'
  '                bricklet_temperature = None\n'
  '                '
  'handle_result(MESSAGE_CRITICAL_ERROR_GETTING_DEVICE_IDENTITY,\n'
  '                              RETURN_CODE_CRITICAL)\n'
  '\n'
  '                return\n'
  '\n'
  '            if device_identifier == '
  'BrickletTemperatureV2.DEVICE_IDENTIFIER:\n'
  '                bricklet_temperature = BrickletTemperatureV2(uid, ipcon)\n'
  '\n'
  '        if bricklet_temperature != None:\n'
  '            try:\n'
  '                reading = bricklet_temperature.get_temperature() / 100.0\n'
  '            except:\n'
  '                handle_result(MESSAGE_CRITICAL_ERROR_READING_VALUE,\n'
  '                            RETURN_CODE_CRITICAL)\n'
  '\n'
  '                return\n'
  '\n'
  '    elif bricklet == BRICKLET_HUMIDITY:\n'
  "        unit = '%RH'\n"
  '        divisor = 10.0\n'
  '        bricklet_humidity = BrickletHumidity(uid, ipcon)\n'
  '\n'
  '        if got_humidity_v2:\n'
  '            device_identifier = None\n'
  '\n'
  '            try:\n'
  '                device_identifier = '
  'bricklet_humidity.get_identity().device_identifier\n'
  '            except:\n'
  '                bricklet_humidity = None\n'
  '                '
  'handle_result(MESSAGE_CRITICAL_ERROR_GETTING_DEVICE_IDENTITY,\n'
  '                              RETURN_CODE_CRITICAL)\n'
  '\n'
  '                return\n'
  '\n'
  '            if device_identifier == BrickletHumidityV2.DEVICE_IDENTIFIER:\n'
  '                divisor = 100.0\n'
  '                bricklet_humidity = BrickletHumidityV2(uid, ipcon)\n'
  '\n'
  '        if bricklet_humidity != None:\n'
  '            try:\n'
  '                reading = bricklet_humidity.get_humidity() / divisor\n'
  '            except:\n'
  '                handle_result(MESSAGE_CRITICAL_ERROR_READING_VALUE,\n'
  '                            RETURN_CODE_CRITICAL)\n'
  '\n'
  '                return\n'
  '\n'
  '    elif bricklet == BRICKLET_HUMIDITY_TEMP:\n'
  "        unit = '°C'\n"
  '        divisor = 100.0\n'
  '        bricklet_humidity = BrickletHumidity(uid, ipcon)\n'
  '\n'
  '        if got_humidity_v2:\n'
  '            device_identifier = None\n'
  '\n'
  '            try:\n'
  '                device_identifier = '
  'bricklet_humidity.get_identity().device_identifier\n'
  '            except:\n'
  '                bricklet_humidity = None\n'
  '                '
  'handle_result(MESSAGE_CRITICAL_ERROR_GETTING_DEVICE_IDENTITY,\n'
  '                              RETURN_CODE_CRITICAL)\n'
  '\n'
  '                return\n'
  '\n'
  '            if device_identifier == BrickletHumidityV2.DEVICE_IDENTIFIER:\n'
  '                bricklet_humidity = BrickletHumidityV2(uid, ipcon)\n'
  '\n'
  '        if bricklet_humidity != None:\n'
  '            try:\n'
  '                reading = bricklet_humidity.get_temperature() / divisor\n'
  '            except:\n'
  '                handle_result(MESSAGE_CRITICAL_ERROR_READING_VALUE,\n'
  '                            RETURN_CODE_CRITICAL)\n'
  '\n'
  '                return\n'
  '\n'
  '    elif bricklet == BRICKLET_AMBIENT_LIGHT:\n'
  "        unit = 'Lux'\n"
  '        divisor = 10.0\n'
  '        bricklet_ambient_light = BrickletAmbientLight(uid, ipcon)\n'
  '        range = None\n'
  '        integration_time = None\n'
  '\n'
  '        try:\n'
  '            device_identifier = '
  'bricklet_ambient_light.get_identity().device_identifier\n'
  '        except:\n'
  '            bricklet_ambient_light = None\n'
  '            handle_result(MESSAGE_CRITICAL_ERROR_GETTING_DEVICE_IDENTITY,\n'
  '                            RETURN_CODE_CRITICAL)\n'
  '            return\n'
  '\n'
  '        if got_ambient_light_v2 and device_identifier == '
  'BrickletAmbientLightV2.DEVICE_IDENTIFIER:\n'
  '            divisor = 100.0\n'
  '            range = BrickletAmbientLightV2.ILLUMINANCE_RANGE_UNLIMITED\n'
  '            integration_time = '
  'BrickletAmbientLightV2.INTEGRATION_TIME_200MS\n'
  '            bricklet_ambient_light = BrickletAmbientLightV2(uid, ipcon)\n'
  '\n'
  '        if got_ambient_light_v3 and device_identifier == '
  'BrickletAmbientLightV3.DEVICE_IDENTIFIER:\n'
  '            divisor = 100.0\n'
  '            range = BrickletAmbientLightV3.ILLUMINANCE_RANGE_UNLIMITED\n'
  '            integration_time = '
  'BrickletAmbientLightV3.INTEGRATION_TIME_200MS\n'
  '            bricklet_ambient_light = BrickletAmbientLightV3(uid, ipcon)\n'
  '\n'
  '        if bricklet_ambient_light != None:\n'
  '            if range is not None and integration_time is not None:\n'
  '                try:\n'
  '                    bricklet_ambient_light.set_configuration(range, '
  'integration_time)\n'
  '                except:\n'
  '                    bricklet_ambient_light = None\n'
  '                    '
  'handle_result(MESSAGE_CRITICAL_ERROR_SETTING_AMBIENT_LIGHT_CONFIGURATION,\n'
  '                                RETURN_CODE_CRITICAL)\n'
  '\n'
  '                    return\n'
  '\n'
  '            try:\n'
  '                reading = bricklet_ambient_light.get_illuminance() / '
  'divisor\n'
  '            except:\n'
  '                handle_result(MESSAGE_CRITICAL_ERROR_READING_VALUE,\n'
  '                              RETURN_CODE_CRITICAL)\n'
  '\n'
  '                return\n'
  '\n'
  '    elif bricklet == BRICKLET_IO4:\n'
  '        bricklet_io4_idi4_version = 1\n'
  '        bricklet_io4 = BrickletIO4(uid, ipcon)\n'
  '\n'
  '        if got_io4_v2:\n'
  '            device_identifier = None\n'
  '\n'
  '            try:\n'
  '                device_identifier = '
  'bricklet_io4.get_identity().device_identifier\n'
  '            except:\n'
  '                bricklet_io4 = None\n'
  '                '
  'handle_result(MESSAGE_CRITICAL_ERROR_GETTING_DEVICE_IDENTITY,\n'
  '                              RETURN_CODE_CRITICAL)\n'
  '\n'
  '                return\n'
  '\n'
  '            if device_identifier == BrickletIO4V2.DEVICE_IDENTIFIER:\n'
  '                bricklet_io4_idi4_version = 2\n'
  '                bricklet_io4 = BrickletIO4V2(uid, ipcon)\n'
  '\n'
  '        if bricklet_io4 != None:\n'
  '            if bricklet_io4_idi4_version == 1:\n'
  '                try:\n'
  '                    bricklet_io4.set_configuration(15, '
  'BrickletIO4V2.DIRECTION_IN, True)\n'
  '                except:\n'
  '                    bricklet_io4 = None\n'
  '                    '
  'handle_result(MESSAGE_CRITICAL_ERROR_SETTING_IO4_CONFIGURATION,\n'
  '                                  RETURN_CODE_CRITICAL)\n'
  '\n'
  '                    return\n'
  '\n'
  '            elif bricklet_io4_idi4_version == 2:\n'
  '                try:\n'
  '                    bricklet_io4.set_configuration(0, '
  'BrickletIO4V2.DIRECTION_IN, True)\n'
  '                    bricklet_io4.set_configuration(1, '
  'BrickletIO4V2.DIRECTION_IN, True)\n'
  '                    bricklet_io4.set_configuration(2, '
  'BrickletIO4V2.DIRECTION_IN, True)\n'
  '                    bricklet_io4.set_configuration(3, '
  'BrickletIO4V2.DIRECTION_IN, True)\n'
  '                except:\n'
  '                    bricklet_io4 = None\n'
  '                    '
  'handle_result(MESSAGE_CRITICAL_ERROR_SETTING_IO4_CONFIGURATION,\n'
  '                                  RETURN_CODE_CRITICAL)\n'
  '\n'
  '                    return\n'
  '\n'
  '            try:\n'
  '                reading = bricklet_io4.get_value()\n'
  '            except:\n'
  '                handle_result(MESSAGE_CRITICAL_ERROR_READING_VALUE,\n'
  '                              RETURN_CODE_CRITICAL)\n'
  '\n'
  '                return\n'
  '\n'
  '    elif bricklet == BRICKLET_IDI4:\n'
  '        bricklet_io4_idi4_version = 1\n'
  '        bricklet_idi4 = BrickletIndustrialDigitalIn4(uid, ipcon)\n'
  '\n'
  '        if got_idi4_v2:\n'
  '            device_identifier = None\n'
  '\n'
  '            try:\n'
  '                device_identifier = '
  'bricklet_idi4.get_identity().device_identifier\n'
  '            except:\n'
  '                bricklet_idi4 = None\n'
  '                '
  'handle_result(MESSAGE_CRITICAL_ERROR_GETTING_DEVICE_IDENTITY,\n'
  '                              RETURN_CODE_CRITICAL)\n'
  '\n'
  '                return\n'
  '\n'
  '            if device_identifier == '
  'BrickletIndustrialDigitalIn4V2.DEVICE_IDENTIFIER:\n'
  '                bricklet_io4_idi4_version = 2\n'
  '                bricklet_idi4 = BrickletIndustrialDigitalIn4V2(uid, ipcon)\n'
  '\n'
  '        try:\n'
  '            reading = bricklet_idi4.get_value()\n'
  '\n'
  '        except:\n'
  '            handle_result(MESSAGE_CRITICAL_ERROR_READING_VALUE,\n'
  '                          RETURN_CODE_CRITICAL)\n'
  '\n'
  '            return\n'
  '\n'
  '    if reading != None:\n'
  '        if bricklet != BRICKLET_IO4 and bricklet != BRICKLET_IDI4:\n'
  '            if reading >= critical:\n'
  '                handle_result(MESSAGE_CRITICAL_READING_TOO_HIGH % (reading, '
  'unit),\n'
  '                              RETURN_CODE_CRITICAL)\n'
  '            elif reading >= warning:\n'
  '                handle_result(MESSAGE_WARNING_READING_IS_HIGH % (reading, '
  'unit),\n'
  '                              RETURN_CODE_WARNING)\n'
  '            elif reading <= critical2:\n'
  '                handle_result(MESSAGE_CRITICAL_READING_TOO_LOW % (reading, '
  'unit),\n'
  '                              RETURN_CODE_CRITICAL)\n'
  '            elif reading <= warning2:\n'
  '                handle_result(MESSAGE_WARNING_READING_IS_LOW % (reading, '
  'unit),\n'
  '                              RETURN_CODE_WARNING)\n'
  '            elif reading > warning2 and reading < warning:\n'
  '                handle_result(MESSAGE_OK_READING % (reading, unit),\n'
  '                              RETURN_CODE_OK)\n'
  '            else:\n'
  '                handle_result(MESSAGE_UNKNOWN_READING, '
  'RETURN_CODE_UNKNOWN)\n'
  '        else:\n'
  '            warnings = []\n'
  '            criticals = []\n'
  '            warning = int(warning)\n'
  '            critical = int(critical)\n'
  '            io4_idi4_warning = False\n'
  '            io4_idi4_critical = False\n'
  '\n'
  '            ch0 =\\\n'
  '                {\n'
  "                    'is_warning': False,\n"
  "                    'is_critical': False,\n"
  "                    'current_state': 0,\n"
  "                    'warning':\n"
  '                        {\n'
  "                            'expected_state': None,\n"
  '                        },\n'
  "                    'critical':\n"
  '                        {\n'
  "                            'expected_state': None,\n"
  '                        }\n'
  '                }\n'
  '            ch1 =\\\n'
  '                {\n'
  "                    'is_warning': False,\n"
  "                    'is_critical': False,\n"
  "                    'current_state': 0,\n"
  "                    'warning':\n"
  '                        {\n'
  "                            'expected_state': None,\n"
  '                        },\n'
  "                    'critical':\n"
  '                        {\n'
  "                            'expected_state': None,\n"
  '                        }\n'
  '                }\n'
  '            ch2 =\\\n'
  '                {\n'
  "                    'is_warning': False,\n"
  "                    'is_critical': False,\n"
  "                    'current_state': 0,\n"
  "                    'warning':\n"
  '                        {\n'
  "                            'expected_state': None,\n"
  '                        },\n'
  "                    'critical':\n"
  '                        {\n'
  "                            'expected_state': None,\n"
  '                        }\n'
  '                }\n'
  '            ch3 =\\\n'
  '                {\n'
  "                    'is_warning': False,\n"
  "                    'is_critical': False,\n"
  "                    'current_state': 0,\n"
  "                    'warning':\n"
  '                        {\n'
  "                            'expected_state': None,\n"
  '                        },\n'
  "                    'critical':\n"
  '                        {\n'
  "                            'expected_state': None,\n"
  '                        }\n'
  '                }\n'
  '\n'
  '            # Warning\n'
  '            if (warning & 0x03) == 0:\n'
  "                ch0['warning']['expected_state'] = False\n"
  '            elif (warning & 0x03) == 1:\n'
  "                ch0['warning']['expected_state']  = True\n"
  '            else:\n'
  "                ch0['warning']['expected_state']  = 'IGN'\n"
  '\n'
  '            if ((warning & 0x0C) >> 2) == 0:\n'
  "                ch1['warning']['expected_state']  = False\n"
  '            elif ((warning & 0x0C) >> 2) == 1:\n'
  "                ch1['warning']['expected_state']  = True\n"
  '            else:\n'
  "                ch1['warning']['expected_state']  = 'IGN'\n"
  '\n'
  '            if ((warning & 0x30) >> 4) == 0:\n'
  "                ch2['warning']['expected_state']  = False\n"
  '            elif ((warning & 0x30) >> 4) == 1:\n'
  "                ch2['warning']['expected_state']  = True\n"
  '            else:\n'
  "                ch2['warning']['expected_state']  = 'IGN'\n"
  '\n'
  '            if ((warning & 0xC0) >> 6) == 0:\n'
  "                ch3['warning']['expected_state']  = False\n"
  '            elif ((warning & 0xC0) >> 6) == 1:\n'
  "                ch3['warning']['expected_state']  = True\n"
  '            else:\n'
  "                ch3['warning']['expected_state']  = 'IGN'\n"
  '\n'
  '            # Critical\n'
  '            if (critical & 0x03) == 0:\n'
  "                ch0['critical']['expected_state'] = False\n"
  '            elif ((critical & 0x03) == 1):\n'
  "                ch0['critical']['expected_state']= True\n"
  '            else:\n'
  "                ch0['critical']['expected_state'] = 'IGN'\n"
  '\n'
  '            if ((critical & 0x0C) >> 2) == 0:\n'
  "                ch1['critical']['expected_state'] = False\n"
  '            elif ((critical & 0x0C) >> 2) == 1:\n'
  "                ch1['critical']['expected_state'] = True\n"
  '            else:\n'
  "                ch1['critical']['expected_state'] = 'IGN'\n"
  '\n'
  '            if ((critical & 0x30) >> 4) == 0:\n'
  "                ch2['critical']['expected_state'] = False\n"
  '            elif ((critical & 0x30) >> 4) == 1:\n'
  "                ch2['critical']['expected_state'] = True\n"
  '            else:\n'
  "                ch2['critical']['expected_state'] = 'IGN'\n"
  '\n'
  '            if ((critical & 0xC0) >> 6) == 0:\n'
  "                ch3['critical']['expected_state'] = False\n"
  '            elif ((critical & 0xC0) >> 6) == 1:\n'
  "                ch3['critical']['expected_state'] = True\n"
  '            else:\n'
  "                ch3['critical']['expected_state'] = 'IGN'\n"
  '\n'
  '            # Current state\n'
  '            if bricklet_io4_idi4_version == 1:\n'
  '                reading = int(reading)\n'
  '\n'
  '                if (reading & 0x01):\n'
  "                    ch0['current_state'] = 1\n"
  '\n'
  '                if (reading & 0x02):\n'
  "                    ch1['current_state'] = 1\n"
  '\n'
  '                if (reading & 0x04):\n'
  "                    ch2['current_state'] = 1\n"
  '\n'
  '                if (reading & 0x08):\n'
  "                    ch3['current_state'] = 1\n"
  '\n'
  '            elif bricklet_io4_idi4_version == 2:\n'
  "                ch0['current_state'] = int(reading[0])\n"
  "                ch1['current_state'] = int(reading[1])\n"
  "                ch2['current_state'] = int(reading[2])\n"
  "                ch3['current_state'] = int(reading[3])\n"
  '\n'
  '            # Warning: For channels\n'
  "            if ch0['warning']['expected_state'] != 'IGN':\n"
  "                if ch0['current_state'] == "
  "ch0['warning']['expected_state']:\n"
  "                    ch0['is_warning'] = True\n"
  '                else:\n'
  "                    ch0['is_warning'] = False\n"
  '            else:\n'
  "                ch0['current_state']= 'IGN'\n"
  "                ch0['is_warning'] = None\n"
  '\n'
  "            if ch0['is_warning'] != None:\n"
  "                warnings.append(ch0['is_warning'])\n"
  '\n'
  "            if ch1['warning']['expected_state'] != 'IGN':\n"
  "                if ch1['current_state'] == "
  "ch1['warning']['expected_state']:\n"
  "                    ch1['is_warning'] = True\n"
  '                else:\n'
  "                    ch1['is_warning'] = False\n"
  '            else:\n'
  "                ch1['current_state']= 'IGN'\n"
  "                ch1['is_warning'] = None\n"
  '\n'
  "            if ch1['is_warning'] != None:\n"
  "                warnings.append(ch1['is_warning'])\n"
  '\n'
  "            if ch2['warning']['expected_state'] != 'IGN':\n"
  "                if ch2['current_state'] == "
  "ch2['warning']['expected_state']:\n"
  "                    ch2['is_warning'] = True\n"
  '                else:\n'
  "                    ch2['is_warning'] = False\n"
  '            else:\n'
  "                ch2['current_state']= 'IGN'\n"
  "                ch2['is_warning'] = None\n"
  '\n'
  "            if ch2['is_warning'] != None:\n"
  "                warnings.append(ch2['is_warning'])\n"
  '\n'
  "            if ch3['warning']['expected_state'] != 'IGN':\n"
  "                if ch3['current_state'] == "
  "ch3['warning']['expected_state']:\n"
  "                    ch3['is_warning'] = True\n"
  '                else:\n'
  "                    ch3['is_warning'] = False\n"
  '            else:\n'
  "                ch3['current_state']= 'IGN'\n"
  "                ch3['is_warning'] = None\n"
  '\n'
  "            if ch3['is_warning'] != None:\n"
  "                warnings.append(ch3['is_warning'])\n"
  '\n'
  '            # Critical: For channels\n'
  "            if ch0['critical']['expected_state'] != 'IGN':\n"
  "                if ch0['current_state'] == "
  "ch0['critical']['expected_state']:\n"
  "                    ch0['is_critical'] = True\n"
  '                else:\n'
  "                    ch0['is_critical'] = False\n"
  '            else:\n'
  "                ch0['current_state']= 'IGN'\n"
  "                ch0['is_critical'] = None\n"
  '\n'
  "            if ch0['is_critical'] != None:\n"
  "                criticals.append(ch0['is_critical'])\n"
  '\n'
  "            if ch1['critical']['expected_state'] != 'IGN':\n"
  "                if ch1['current_state'] == "
  "ch1['critical']['expected_state']:\n"
  "                    ch1['is_critical'] = True\n"
  '                else:\n'
  "                    ch1['is_critical'] = False\n"
  '            else:\n'
  "                ch1['current_state']= 'IGN'\n"
  "                ch1['is_critical'] = None\n"
  '\n'
  "            if ch1['is_critical'] != None:\n"
  "                criticals.append(ch1['is_critical'])\n"
  '\n'
  "            if ch2['critical']['expected_state'] != 'IGN':\n"
  "                if ch2['current_state'] == "
  "ch2['critical']['expected_state']:\n"
  "                    ch2['is_critical'] = True\n"
  '                else:\n'
  "                    ch2['is_critical'] = False\n"
  '            else:\n'
  "                ch2['current_state']= 'IGN'\n"
  "                ch2['is_critical'] = None\n"
  '\n'
  "            if ch2['is_critical'] != None:\n"
  "                criticals.append(ch2['is_critical'])\n"
  '\n'
  "            if ch3['critical']['expected_state'] != 'IGN':\n"
  "                if ch3['current_state'] == "
  "ch3['critical']['expected_state']:\n"
  "                    ch3['is_critical'] = True\n"
  '                else:\n'
  "                    ch3['is_critical'] = False\n"
  '            else:\n'
  "                ch3['current_state']= 'IGN'\n"
  "                ch3['is_critical'] = None\n"
  '\n'
  "            if ch3['is_critical'] != None:\n"
  "                criticals.append(ch3['is_critical'])\n"
  '\n'
  '            if warnings and all(warnings):\n'
  '                io4_idi4_warning = True\n'
  '\n'
  '            if criticals and all(criticals):\n'
  '                io4_idi4_critical = True\n'
  '\n'
  '            if io4_idi4_warning and io4_idi4_critical:\n'
  '                handle_result(MESSAGE_CRITICAL_IO4_IDI4 % '
  "(ch0['current_state'],\n"
  '                                                        '
  "ch1['current_state'],\n"
  '                                                        '
  "ch2['current_state'],\n"
  '                                                        '
  "ch3['current_state']),\n"
  '                            RETURN_CODE_CRITICAL)\n'
  '            elif io4_idi4_warning:\n'
  '                handle_result(MESSAGE_WARNING_IO4_IDI4 % '
  "(ch0['current_state'],\n"
  '                                                        '
  "ch1['current_state'],\n"
  '                                                        '
  "ch2['current_state'],\n"
  '                                                        '
  "ch3['current_state']),\n"
  '                            RETURN_CODE_WARNING)\n'
  '            elif io4_idi4_critical:\n'
  '                handle_result(MESSAGE_CRITICAL_IO4_IDI4 % '
  "(ch0['current_state'],\n"
  '                                                        '
  "ch1['current_state'],\n"
  '                                                        '
  "ch2['current_state'],\n"
  '                                                        '
  "ch3['current_state']),\n"
  '                            RETURN_CODE_CRITICAL)\n'
  '            else:\n'
  "                handle_result(MESSAGE_OK_IO4_IDI4 % (ch0['current_state'],\n"
  "                                                    ch1['current_state'],\n"
  "                                                    ch2['current_state'],\n"
  "                                                    ch3['current_state']),\n"
  '                            RETURN_CODE_OK)\n'
  '\n'
  "if __name__ == '__main__':\n"
  '    parse = argparse.ArgumentParser()\n'
  '\n'
  "    parse.add_argument('-H',\n"
  "                       '--host',\n"
  "                       help = 'Host (default = localhost)',\n"
  '                       required = True)\n'
  '\n'
  "    parse.add_argument('-P',\n"
  "                       '--port',\n"
  "                       help = 'Port (default = 4223)',\n"
  '                       type = int,\n'
  '                       required = True)\n'
  '\n'
  "    parse.add_argument('-S',\n"
  "                       '--secret',\n"
  "                       help = 'Secret (default = None)',\n"
  '                       type = str,\n'
  '                       default = None,\n'
  '                       required = False)\n'
  '\n'
  "    parse.add_argument('-b',\n"
  "                       '--bricklet',\n"
  "                       help = 'Type of bricklet',\n"
  '                       type = str,\n'
  "                       choices = ['ptc_2_wire', 'ptc_3_wire', 'ptc_4_wire', "
  "'temperature', 'humidity', 'humidity_temp', 'ambient_light', 'io4', "
  "'idi4'],\n"
  '                       required = True)\n'
  '\n'
  "    parse.add_argument('-u',\n"
  "                       '--uid',\n"
  "                       help = 'UID of bricklet',\n"
  '                       required = True)\n'
  '\n'
  "    parse.add_argument('-w',\n"
  "                       '--warning',\n"
  "                       help = 'Warning temperature level \\\n"
  '                               (temperatures above this level will trigger '
  'a warning \\\n'
  "                               message)',\n"
  '                       type = float,\n'
  '                       required = True)\n'
  '\n'
  "    parse.add_argument('-c',\n"
  "                       '--critical',\n"
  "                       help = 'Critical temperature level \\\n"
  '                               (temperatures above this level will trigger '
  'a critical \\\n'
  "                               message)',\n"
  '                       type = float,\n'
  '                       required = True)\n'
  '\n'
  "    parse.add_argument('-w2',\n"
  "                       '--warning2',\n"
  "                       help = 'Warning temperature level (temperatures \\\n"
  '                               below this level will trigger a warning '
  "message)',\n"
  '                       type = float,\n'
  '                       required = True)\n'
  '\n'
  "    parse.add_argument('-c2',\n"
  "                       '--critical2',\n"
  "                       help = 'Critical temperature level (temperatures "
  'below \\\n'
  '                               this level will trigger a critical '
  "message)',\n"
  '                       type = float,\n'
  '                       required = True)\n'
  '\n'
  '    args  = parse.parse_args()\n'
  '    ipcon = IPConnection()\n'
  '\n'
  '    if args and ipcon:\n'
  '        connect()\n'
  '        time.sleep(3)\n'
  '        print return_message\n'
  '        exit(return_code)\n'
  "'''\n"
  '\n'
  'TEMPLATE_COMMAND_LINE_NOTIFY_HOST = \'\'\'/usr/bin/printf "%b" "***** '
  'Nagios *****\\\\n\\\\n \\\n'
  'Notification Type: $NOTIFICATIONTYPE$\\\\n \\\n'
  'Host: $HOSTNAME$\\\\n \\\n'
  'State: $HOSTSTATE$\\\\n \\\n'
  'Address: $HOSTADDRESS$\\\\n \\\n'
  'Info: $HOSTOUTPUT$\\\\n\\\\n \\\n'
  'Date/Time: $LONGDATETIME$\\\\n" | \\\n'
  '/usr/bin/sendemail \\\n'
  '-f {0} \\\n'
  '-t {1} \\\n'
  '-u "** $NOTIFICATIONTYPE$ Host Alert: $HOSTNAME$ is $HOSTSTATE$ **" \\\n'
  '-s {2}:{3} \\\n'
  '-o username={4} \\\n'
  '-o password={5} \\\n'
  '-o tls={6} \\\n'
  "-o message-charset=utf-8'''\n"
  '\n'
  'TEMPLATE_COMMAND_LINE_NOTIFY_SERVICE = \'\'\'/usr/bin/printf "%b" "***** '
  'Nagios *****\\\\n\\\\n \\\n'
  'Notification Type: $NOTIFICATIONTYPE$\\\\n\\\\n \\\n'
  'Service: $SERVICEDESC$\\\\n \\\n'
  'Host: $HOSTALIAS$\\\\n \\\n'
  'Address: $HOSTADDRESS$\\\\n \\\n'
  'State: $SERVICESTATE$\\\\n\\\\n \\\n'
  'Date/Time: $LONGDATETIME$\\\\n\\\\n \\\n'
  'Additional Info:\\\\n\\\\n$SERVICEOUTPUT$\\\\n" | \\\n'
  '/usr/bin/sendemail \\\n'
  '-f {0} \\\n'
  '-t {1} \\\n'
  '-u "** $NOTIFICATIONTYPE$ Service Alert: $HOSTALIAS$/$SERVICEDESC$ is '
  '$SERVICESTATE$ **" \\\n'
  '-s {2}:{3} \\\n'
  '-o username={4} \\\n'
  '-o password={5} \\\n'
  '-o tls={6} \\\n'
  "-o message-charset=utf-8'''\n"
  '\n'
  "TEMPLATE_TEST_EMAIL = '''/usr/bin/sendemail \\\n"
  '-f {0} \\\n'
  '-t {1} \\\n'
  '-u ** RED-Brick Server Monitoring Test Email ** \\\n'
  '-m If you received this email message on the target email address then it '
  'means \\\n'
  'that the server monitoring email alert is working on the RED-Brick.\\n\n'
  '-s {2}:{3} \\\n'
  '-o username={4} \\\n'
  '-o password={5} \\\n'
  '-o tls={6} \\\n'
  "-o message-charset=utf-8'''\n"
  '\n'
  'ACTION = argv[1]\n'
  '\n'
  'ipcon  = None\n'
  'host   = None\n'
  'port   = None\n'
  'secret = None\n'
  'global ignore_enumerate_failed_called\n'
  'ignore_enumerate_failed_called = False\n'
  '\n'
  "dict_enumerate = {'host'         : None,\n"
  "                  'port'         : None,\n"
  "                  'secret'       : None,\n"
  "                  'ptc'          : [],\n"
  "                  'temperature'  : [],\n"
  "                  'humidity'     : [],\n"
  "                  'humidity_temp': [],\n"
  "                  'ambient_light': [],\n"
  "                  'io4'          : [],\n"
  "                  'idi4'         : []}\n"
  '\n'
  "_find_unsafe = re.compile(r'[^\\w@%+=:,./-]').search\n"
  '\n'
  'def quote(s):\n'
  '    """Return a shell-escaped version of the string *s*."""\n'
  '    if not s:\n'
  '        return "\'\'"\n'
  '    if _find_unsafe(s) is None:\n'
  '        return s\n'
  '\n'
  '    # use single quotes, and put single quotes into double quotes\n'
  '    # the string $\'b is then quoted as \'$\'"\'"\'b\'\n'
  '    return "\'" + s.replace("\'", "\'\\"\'\\"\'") + "\'"\n'
  '\n'
  'def ignore_enumerate_fail():\n'
  '    global ignore_enumerate_failed_called\n'
  '    ignore_enumerate_failed_called = True\n'
  '\n'
  '    if ipcon:\n'
  '        try:\n'
  '            ipcon.disconnect()\n'
  '        except:\n'
  '            pass\n'
  '\n'
  "    dict_enumerate['host']          = host\n"
  "    dict_enumerate['port']          = port\n"
  "    dict_enumerate['secret']        = secret\n"
  "    dict_enumerate['ptc']           = []\n"
  "    dict_enumerate['temperature']   = []\n"
  "    dict_enumerate['humidity']      = []\n"
  "    dict_enumerate['humidity_temp']      = []\n"
  "    dict_enumerate['ambient_light'] = []\n"
  "    dict_enumerate['io4']           = []\n"
  "    dict_enumerate['idi4']          = []\n"
  '\n'
  '    sys.stdout.write(json.dumps(dict_enumerate))\n'
  '\n'
  'def cb_connect(connect_reason, secret):\n'
  '    if not ipcon:\n'
  '        ignore_enumerate_fail()\n'
  '        exit(0)\n'
  '\n'
  '    if secret:\n'
  '        try:\n'
  '            ipcon.authenticate(secret)\n'
  '        except:\n'
  '            ignore_enumerate_fail()\n'
  '            exit(0)\n'
  '\n'
  '    ipcon.enumerate()\n'
  '\n'
  'def cb_enumerate(uid,\n'
  '                 connected_uid,\n'
  '                 position,\n'
  '                 hardware_version,\n'
  '                 firmware_version,\n'
  '                 device_identifier,\n'
  '                 enumeration_type,\n'
  '                 host,\n'
  '                 port,\n'
  '                 secret):\n'
  '\n'
  '    if not ipcon:\n'
  '        ignore_enumerate_fail()\n'
  '        exit(0)\n'
  '\n'
  '    if device_identifier == BrickletPTC.DEVICE_IDENTIFIER and\\\n'
  "       uid not in dict_enumerate['ptc']:\n"
  "            dict_enumerate['ptc'].append(uid)\n"
  '\n'
  '    elif got_ptc_v2 and\\\n'
  '         device_identifier == BrickletPTCV2.DEVICE_IDENTIFIER and\\\n'
  "         uid not in dict_enumerate['ptc']:\n"
  "            dict_enumerate['ptc'].append(uid)\n"
  '\n'
  '    elif device_identifier == BrickletTemperature.DEVICE_IDENTIFIER and\\\n'
  "         uid not in dict_enumerate['temperature']:\n"
  "            dict_enumerate['temperature'].append(uid)\n"
  '\n'
  '    elif got_temperature_v2 and\\\n'
  '         device_identifier == BrickletTemperatureV2.DEVICE_IDENTIFIER '
  'and\\\n'
  "         uid not in dict_enumerate['temperature']:\n"
  "            dict_enumerate['temperature'].append(uid)\n"
  '\n'
  '    elif device_identifier == BrickletHumidity.DEVICE_IDENTIFIER and\\\n'
  "         uid not in dict_enumerate['humidity']:\n"
  "            dict_enumerate['humidity'].append(uid)\n"
  '\n'
  '    elif got_humidity_v2 and\\\n'
  '         device_identifier == BrickletHumidityV2.DEVICE_IDENTIFIER and\\\n'
  "         uid not in dict_enumerate['humidity']:\n"
  "            dict_enumerate['humidity'].append(uid)\n"
  "            dict_enumerate['humidity_temp'].append(uid)\n"
  '\n'
  '    elif device_identifier == BrickletAmbientLight.DEVICE_IDENTIFIER and\\\n'
  "         uid not in dict_enumerate['ambient_light']:\n"
  "            dict_enumerate['ambient_light'].append(uid)\n"
  '\n'
  '    elif got_ambient_light_v2 and\\\n'
  '         device_identifier == BrickletAmbientLightV2.DEVICE_IDENTIFIER '
  'and\\\n'
  "         uid not in dict_enumerate['ambient_light']:\n"
  "            dict_enumerate['ambient_light'].append(uid)\n"
  '\n'
  '    elif got_ambient_light_v3 and\\\n'
  '         device_identifier == BrickletAmbientLightV3.DEVICE_IDENTIFIER '
  'and\\\n'
  "         uid not in dict_enumerate['ambient_light']:\n"
  "            dict_enumerate['ambient_light'].append(uid)\n"
  '\n'
  '    elif device_identifier == BrickletIO4.DEVICE_IDENTIFIER and\\\n'
  "         uid not in dict_enumerate['io4']:\n"
  "            dict_enumerate['io4'].append(uid)\n"
  '\n'
  '    elif got_io4_v2 and\\\n'
  '         device_identifier == BrickletIO4V2.DEVICE_IDENTIFIER and\\\n'
  "         uid not in dict_enumerate['io4']:\n"
  "            dict_enumerate['io4'].append(uid)\n"
  '\n'
  '    elif device_identifier == '
  'BrickletIndustrialDigitalIn4.DEVICE_IDENTIFIER and\\\n'
  "         uid not in dict_enumerate['idi4']:\n"
  "            dict_enumerate['idi4'].append(uid)\n"
  '\n'
  '    elif got_idi4_v2 and\\\n'
  '         device_identifier == '
  'BrickletIndustrialDigitalIn4V2.DEVICE_IDENTIFIER and\\\n'
  "         uid not in dict_enumerate['idi4']:\n"
  "            dict_enumerate['idi4'].append(uid)\n"
  '\n'
  "if ACTION == 'GET':\n"
  '    try:\n'
  '        dict_return = {}\n'
  '        list_rules  = []\n'
  '        dict_email = \\\n'
  '            {\n'
  "                'from'    : '',\n"
  "                'to'      : '',\n"
  "                'server'  : '',\n"
  "                'port'    : '25',\n"
  "                'username': '',\n"
  "                'password': '',\n"
  "                'tls'     : ''\n"
  '            }\n'
  '\n'
  "        dict_return['rules'] = None\n"
  "        dict_return['email'] = None\n"
  "        dict_return['hosts'] = {}\n"
  '\n'
  '        for command in '
  'Model.Command.objects.filter(command_name__startswith = '
  "'tinkerforge-command-'):\n"
  '            for service in Model.Service.objects.filter(check_command = '
  'command.command_name):\n'
  '                parse = argparse.ArgumentParser()\n'
  '\n'
  "                parse.add_argument('-H')\n"
  "                parse.add_argument('-P')\n"
  "                parse.add_argument('-S')\n"
  "                parse.add_argument('-b')\n"
  "                parse.add_argument('-u')\n"
  "                parse.add_argument('-m')\n"
  "                parse.add_argument('-w')\n"
  "                parse.add_argument('-c')\n"
  "                parse.add_argument('-w2')\n"
  "                parse.add_argument('-c2')\n"
  '\n'
  '                map_args = '
  "parse.parse_args(command.command_line.split('/usr/local/bin/check_tinkerforge.py "
  "')[1].split(' '))\n"
  '\n'
  "                a_rule = {'name'                      : "
  'service.service_description,\n'
  "                          'host'                      : map_args.H,\n"
  "                          'bricklet'                  : map_args.b,\n"
  "                          'uid'                       : map_args.u,\n"
  "                          'warning_low'               : map_args.w2,\n"
  "                          'warning_high'              : map_args.w,\n"
  "                          'critical_low'              : map_args.c2,\n"
  "                          'critical_high'             : map_args.c,\n"
  "                          'email_notification_enabled': "
  'service.notifications_enabled,\n'
  "                          'email_notifications'       : "
  'service.notification_options}\n'
  '\n'
  '                list_rules.append(a_rule)\n'
  '\n'
  '                if not map_args.S:\n'
  "                    secret = ''\n"
  '                else:\n'
  '                    secret = map_args.S\n'
  '\n'
  "                if map_args.H not in dict_return['hosts']:\n"
  "                    dict_return['hosts'][map_args.H] = {'port':map_args.P, "
  "'secret':secret}\n"
  '\n'
  '        for command in Model.Command.objects.filter(command_name = '
  "'tinkerforge-notify-service-by-email'):\n"
  '            arguments = '
  "command.command_line.partition('/usr/bin/sendemail')[2]\n"
  '            tokens = shlex.split(arguments)\n'
  '\n'
  '            while len(tokens) >= 2:\n'
  "                if tokens[0] == '-f':\n"
  "                    dict_email['from'] = tokens[1]\n"
  "                elif tokens[0] == '-t':\n"
  "                    dict_email['to'] = tokens[1]\n"
  "                elif tokens[0] == '-s':\n"
  "                    server_port = tokens[1].split(':')\n"
  "                    dict_email['server'] = server_port[0]\n"
  "                    dict_email['port']   = server_port[1]\n"
  "                elif tokens[0] == '-o':\n"
  "                    if tokens[1].startswith('username='):\n"
  "                        dict_email['username'] = "
  "tokens[1][len('username='):]\n"
  "                    elif tokens[1].startswith('password='):\n"
  "                        dict_email['password'] = "
  "tokens[1][len('password='):]\n"
  "                    elif tokens[1].startswith('tls='):\n"
  "                        dict_email['tls'] = tokens[1][len('tls='):]\n"
  '                    else:\n'
  '                        tokens = tokens[1:]\n'
  '                        continue\n'
  '                else:\n'
  '                    tokens = tokens[1:]\n'
  '                    continue\n'
  '\n'
  '                tokens = tokens[2:]\n'
  '\n'
  '        if len(list_rules) > 0:\n'
  "            dict_return['rules'] = list_rules\n"
  '\n'
  '        if len(dict_email) == 7:\n'
  "            dict_return['email'] = dict_email\n"
  '\n'
  '        sys.stdout.write(json.dumps(dict_return))\n'
  '    except Exception as e:\n'
  '        sys.stderr.write(unicode(e))\n'
  '        exit(1)\n'
  '\n'
  "elif ACTION == 'APPLY':\n"
  '    try:\n'
  '        if len(argv) < 3:\n'
  '            exit(1)\n'
  '\n'
  '        apply_dict = json.loads(argv[2])\n'
  '\n'
  "        with open(FILE_PATH_CHECK_SCRIPT, 'w') as fh_cs:\n"
  '            fh_cs.write(SCRIPT_TINKERFORGE_CHECK)\n'
  '\n'
  '        os.chmod(FILE_PATH_CHECK_SCRIPT,\n'
  '                 stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH | \\\n'
  '                 stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)\n'
  '\n'
  '        if os.path.isfile(FILE_PATH_TF_NAGIOS_CONFIGURATION):\n'
  '            os.remove(FILE_PATH_TF_NAGIOS_CONFIGURATION)\n'
  '\n'
  "        for rule in apply_dict['rules']:\n"
  '            tf_command = Model.Command()\n'
  '            tf_service = Model.Service()\n'
  '            tf_command.set_filename(FILE_PATH_TF_NAGIOS_CONFIGURATION)\n'
  '            tf_service.set_filename(FILE_PATH_TF_NAGIOS_CONFIGURATION)\n'
  "            tf_command.command_name = rule['check_command']\n"
  "            tf_command.command_line = rule['command_line']\n"
  "            tf_service.use                      = 'generic-service'\n"
  "            tf_service.host_name                = 'localhost'\n"
  '            tf_service.service_description      = '
  "rule['service_description']\n"
  "            tf_service.check_command            = rule['check_command']\n"
  "            tf_service.max_check_attempts       = '4'\n"
  "            tf_service.check_interval           = '1'\n"
  "            tf_service.retry_interval           = '1'\n"
  "            tf_service.check_period             = '24x7'\n"
  "            tf_service.notification_interval    = '5'\n"
  "            tf_service.first_notification_delay = '0'\n"
  "            tf_service.notification_period      = '24x7'\n"
  '            tf_service.notification_options     = '
  "rule['notification_options']\n"
  '            tf_service.notifications_enabled    = '
  "rule['notifications_enabled']\n"
  "            tf_service.contact_groups           = rule['contact_groups']\n"
  '            tf_command.save()\n'
  '            tf_service.save()\n'
  '\n'
  "        if apply_dict['email']:\n"
  '            tf_command_notify_service = Model.Command()\n'
  '            tf_command_notify_host    = Model.Command()\n'
  '            tf_contact                = Model.Contact()\n'
  '            tf_contact_group          = Model.Contactgroup()\n'
  '            '
  'tf_command_notify_service.set_filename(FILE_PATH_TF_NAGIOS_CONFIGURATION)\n'
  '            '
  'tf_command_notify_host.set_filename(FILE_PATH_TF_NAGIOS_CONFIGURATION)\n'
  '            tf_contact.set_filename(FILE_PATH_TF_NAGIOS_CONFIGURATION)\n'
  '            '
  'tf_contact_group.set_filename(FILE_PATH_TF_NAGIOS_CONFIGURATION)\n'
  '            tf_command_notify_service.command_name = '
  "'tinkerforge-notify-service-by-email'\n"
  '            tf_command_notify_service.command_line = '
  "TEMPLATE_COMMAND_LINE_NOTIFY_SERVICE.format(quote(apply_dict['email']['from']),\n"
  '                                                                                                 '
  "quote(apply_dict['email']['to']),\n"
  '                                                                                                 '
  "quote(apply_dict['email']['server']),\n"
  '                                                                                                 '
  "quote(apply_dict['email']['port']),\n"
  '                                                                                                 '
  "quote(apply_dict['email']['username']),\n"
  '                                                                                                 '
  "quote(apply_dict['email']['password']),\n"
  '                                                                                                 '
  "quote(apply_dict['email']['tls']))\n"
  '            tf_command_notify_host.command_name = '
  "'tinkerforge-notify-host-by-email'\n"
  '            tf_command_notify_host.command_line = '
  "TEMPLATE_COMMAND_LINE_NOTIFY_HOST.format(quote(apply_dict['email']['from']),\n"
  '                                                                                           '
  "quote(apply_dict['email']['to']),\n"
  '                                                                                           '
  "quote(apply_dict['email']['server']),\n"
  '                                                                                           '
  "quote(apply_dict['email']['port']),\n"
  '                                                                                           '
  "quote(apply_dict['email']['username']),\n"
  '                                                                                           '
  "quote(apply_dict['email']['password']),\n"
  '                                                                                           '
  "quote(apply_dict['email']['tls']))\n"
  '            tf_contact.contact_name                  = '
  "'tinkerforge-contact'\n"
  "            tf_contact.host_notifications_enabled    = '0'\n"
  "            tf_contact.service_notifications_enabled = '1'\n"
  "            tf_contact.host_notification_period      = '24x7'\n"
  "            tf_contact.service_notification_period   = '24x7'\n"
  "            tf_contact.host_notification_options     = 'd,u,r'\n"
  "            tf_contact.service_notification_options  = 'w,u,c,r'\n"
  '            tf_contact.host_notification_commands    = '
  "'tinkerforge-notify-host-by-email'\n"
  '            tf_contact.service_notification_commands = '
  "'tinkerforge-notify-service-by-email'\n"
  '            tf_contact_group.contactgroup_name       = '
  "'tinkerforge-contact-group'\n"
  "            tf_contact_group.alias                   = 'Tinkerforge Contact "
  "Group'\n"
  '            tf_contact_group.members                 = '
  "'tinkerforge-contact'\n"
  '            tf_command_notify_service.save()\n'
  '            tf_command_notify_host.save()\n'
  '            tf_contact.save()\n'
  '            tf_contact_group.save()\n'
  '\n'
  '        if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_NAGIOS4:\n'
  "            if os.system('/bin/systemctl restart nagios') != 0:\n"
  '                exit(1)\n'
  '        else:\n'
  "            if os.system('/bin/systemctl restart nagios3') != 0:\n"
  '                exit(1)\n'
  '\n'
  '    except Exception as e:\n'
  '        sys.stderr.write(unicode(e))\n'
  '        exit(1)\n'
  '\n'
  "elif ACTION == 'APPLY_EMPTY':\n"
  '    try:\n'
  '        if os.path.isfile(FILE_PATH_CHECK_SCRIPT):\n'
  '            os.remove(FILE_PATH_CHECK_SCRIPT)\n'
  '\n'
  '        if os.path.isfile(FILE_PATH_TF_NAGIOS_CONFIGURATION):\n'
  '            os.remove(FILE_PATH_TF_NAGIOS_CONFIGURATION)\n'
  '\n'
  '        if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_NAGIOS4:\n'
  "            if os.system('/bin/systemctl restart nagios') != 0:\n"
  '                exit(1)\n'
  '        else:\n'
  "            if os.system('/bin/systemctl restart nagios3') != 0:\n"
  '                exit(1)\n'
  '\n'
  '    except Exception as e:\n'
  '        sys.stderr.write(unicode(e))\n'
  '        exit(1)\n'
  '\n'
  "elif ACTION == 'GET_LOCALHOST':\n"
  '    try:\n'
  '        hostname = unicode(socket.gethostname())\n'
  '\n'
  '        if hostname:\n'
  '            sys.stdout.write(hostname)\n'
  '        else:\n'
  '            exit(1)\n'
  '    except Exception as e:\n'
  '        sys.stderr.write(unicode(e))\n'
  '        exit(1)\n'
  '\n'
  "elif ACTION == 'ENUMERATE':\n"
  '    try:\n'
  '        if len(argv) < 5:\n'
  '            exit(1)\n'
  '\n'
  '        host   = argv[2]\n'
  '        port   = argv[3]\n'
  '        secret = argv[4]\n'
  '\n'
  "        dict_enumerate['host']   = host\n"
  "        dict_enumerate['port']   = port\n"
  "        dict_enumerate['secret'] = secret\n"
  '\n'
  '        ipcon = IPConnection()\n'
  '        ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, lambda '
  'connect_reason: cb_connect(connect_reason, secret))\n'
  '        ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, lambda '
  'uid,\n'
  '                                                                        '
  'connected_uid,\n'
  '                                                                        '
  'position,\n'
  '                                                                        '
  'hardware_version,\n'
  '                                                                        '
  'firmware_version,\n'
  '                                                                        '
  'device_identifier,\n'
  '                                                                        '
  'enumeration_type: cb_enumerate(uid,\n'
  '                                                                                                       '
  'connected_uid,\n'
  '                                                                                                       '
  'position,\n'
  '                                                                                                       '
  'hardware_version,\n'
  '                                                                                                       '
  'firmware_version,\n'
  '                                                                                                       '
  'device_identifier,\n'
  '                                                                                                       '
  'enumeration_type,\n'
  '                                                                                                       '
  'host,\n'
  '                                                                                                       '
  'port,\n'
  '                                                                                                       '
  'secret))\n'
  '        ipcon.connect(host, int(port))\n'
  '        sleep(2)\n'
  '    except:\n'
  '        ignore_enumerate_fail()\n'
  '        exit(0)\n'
  '\n'
  "elif ACTION == 'TEST_EMAIL':\n"
  '    if len(argv) != 3:\n'
  "        sys.stderr.write(unicode('Too many or too few arguments provided "
  "for sending test email'))\n"
  '        exit(1)\n'
  '    try:\n'
  '        test_email_dict = json.loads(argv[2])\n'
  "        test_email_from = test_email_dict['test_email_from']\n"
  "        test_email_to = test_email_dict['test_email_to']\n"
  "        test_email_server = test_email_dict['test_email_server']\n"
  "        test_email_port = test_email_dict['test_email_port']\n"
  "        test_email_username = test_email_dict['test_email_username']\n"
  "        test_email_password = test_email_dict['test_email_password']\n"
  "        test_email_tls = test_email_dict['test_email_tls']\n"
  '\n'
  '        test_email_cmd = '
  'TEMPLATE_TEST_EMAIL.format(quote(test_email_from),\n'
  '                                                    quote(test_email_to),\n'
  '                                                    '
  'quote(test_email_server),\n'
  '                                                    '
  'quote(test_email_port),\n'
  '                                                    '
  'quote(test_email_username),\n'
  '                                                    '
  'quote(test_email_password),\n'
  '                                                    quote(test_email_tls))\n'
  '\n'
  '        p_sendemail = subprocess.Popen(shlex.split(test_email_cmd),\n'
  '                                       universal_newlines = True,\n'
  '                                       stdout = subprocess.PIPE,\n'
  '                                       stderr = subprocess.PIPE)\n'
  '        p_sendemail_comm = p_sendemail.communicate()\n'
  '\n'
  '    except Exception as e:\n'
  '        sys.stderr.write(unicode(e))\n'
  '        exit(1)\n'
  '\n'
  '    if p_sendemail.returncode != 0:\n'
  '        if p_sendemail_comm[1]:\n'
  '            sys.stderr.write(unicode(p_sendemail_comm[1]))\n'
  '        else:\n'
  '            sys.stderr.write(unicode(p_sendemail_comm[0]))\n'
  '        exit(1)\n'
  '\n'
  'else:\n'
  '    exit(1)\n'
  '\n'
  "if ACTION == 'ENUMERATE':\n"
  '    if ipcon:\n'
  '        try:\n'
  '            ipcon.disconnect()\n'
  '        except:\n'
  '            pass\n'
  '\n'
  '    if not ignore_enumerate_failed_called:\n'
  '        sys.stdout.write(json.dumps(dict_enumerate))\n'),
 ('settings_services',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import sys\n'
  'import json\n'
  'import time\n'
  'import subprocess\n'
  'from distutils.version import StrictVersion\n'
  '\n'
  'IMAGE_VERSION = None\n'
  "MIN_VERSION_WITH_NAGIOS4 = StrictVersion('1.10')\n"
  "MAX_VERSION_WITH_CHKCONFIG = StrictVersion('1.9')\n"
  "MAX_VERSION_WITH_ASPLASH_SCREEN = StrictVersion('1.9')\n"
  "MAX_VERSION_WITH_GPU_2D_3D = StrictVersion('1.9')\n"
  "MIN_VERSION_WITH_OPENHAB2 = StrictVersion('1.10')\n"
  "MIN_VERSION_WITH_NM = StrictVersion('1.10')\n"
  '\n'
  "with open('/etc/tf_image_version', 'r') as f:\n"
  "    IMAGE_VERSION = StrictVersion(f.read().split(' ')[0].strip())\n"
  '\n'
  'if len(sys.argv) < 2:\n'
  "    sys.stderr.write(u'Missing parameters'.encode('utf-8'))\n"
  '    exit(2)\n'
  '\n'
  'command = sys.argv[1]\n'
  '\n'
  "SUNXI_FBDEV_X11_DRIVER_CONF = '''\n"
  '# This configuration file is copied to the following locations,\n'
  '#   /etc/X11/xorg.conf\n'
  '#   /usr/share/X11/xorg.conf.d/99-sunxifb.conf\n'
  '\n'
  '# When troubleshooting, check /var/log/Xorg.0.log for the debugging\n'
  '# output and error messages.\n'
  '#\n'
  '# Run "man fbdev" to get additional information about the extra\n'
  '# configuration options for tuning the driver.\n'
  '\n'
  'Section "ServerLayout"\n'
  '    Identifier      "Default Layout"\n'
  '    Screen          "Screen 0" 0 0\n'
  'EndSection\n'
  '\n'
  'Section "Device"\n'
  '    Identifier      "Allwinner A10/A13 FBDEV"\n'
  '    Driver          "fbdev"\n'
  '    Option          "fbdev" "/dev/fb0"\n'
  '    Option          "ShadowFB" "false"\n'
  'EndSection\n'
  '\n'
  'Section "Monitor"\n'
  '    Identifier      "Default Monitor"\n'
  '    Option          "DPMS" "false"\n'
  'EndSection\n'
  '\n'
  'Section "Screen"\n'
  '    Identifier      "Screen 0"\n'
  '    Device          "Allwinner A10/A13 FBDEV"\n'
  '    Monitor         "Default Monitor"\n'
  '    DefaultDepth    24\n'
  '    Option          "AllowEmptyInitialConfiguration"\n'
  '\n'
  '    SubSection      "Display"\n'
  '        Depth       24\n'
  '    EndSubSection\n'
  'EndSection\n'
  "'''\n"
  '\n'
  "SUNXI_FBTURBO_X11_DRIVER_CONF = '''\n"
  '# This configuration file is copied to the following locations,\n'
  '#   /etc/X11/xorg.conf\n'
  '#   /usr/share/X11/xorg.conf.d/99-sunxifb.conf\n'
  '\n'
  '# When troubleshooting, check /var/log/Xorg.0.log for the debugging\n'
  '# output and error messages.\n'
  '#\n'
  '# Run "man fbturbo" to get additional information about the extra\n'
  '# configuration options for tuning the driver.\n'
  '\n'
  'Section "ServerLayout"\n'
  '    Identifier      "Default Layout"\n'
  '    Screen          "Screen 0" 0 0\n'
  'EndSection\n'
  '\n'
  'Section "Device"\n'
  '    Identifier      "Allwinner A10/A13 FBDEV"\n'
  '    Driver          "fbturbo"\n'
  '    Option          "fbdev" "/dev/fb0"\n'
  '    Option          "ShadowFB" "false"\n'
  '    Option          "DRI2" "false"\n'
  '    Option          "SwapbuffersWait" "true"\n'
  '    Option          "AccelMethod" "CPU"\n'
  'EndSection\n'
  '\n'
  'Section "Monitor"\n'
  '    Identifier      "Default Monitor"\n'
  '    Option          "DPMS" "false"\n'
  'EndSection\n'
  '\n'
  'Section "Screen"\n'
  '    Identifier      "Screen 0"\n'
  '    Device          "Allwinner A10/A13 FBDEV"\n'
  '    Monitor         "Default Monitor"\n'
  '    DefaultDepth    24\n'
  '    Option          "AllowEmptyInitialConfiguration"\n'
  '\n'
  '    SubSection      "Display"\n'
  '        Depth       24\n'
  '    EndSubSection\n'
  'EndSection\n'
  "'''\n"
  '\n'
  "INTERFACES_CONF = '''# interfaces(5) file used by ifup(8) and ifdown(8)\n"
  'auto lo\n'
  'iface lo inet loopback\n'
  "'''\n"
  '\n'
  'is_enabled_mi = None\n'
  'is_enabled_wicd = None\n'
  'is_enabled_mi_nm = None\n'
  'is_enabled_ap_nat = None\n'
  'is_enabled_nagios = None\n'
  'is_enabled_hostapd = None\n'
  'is_enabled_dnsmasq = None\n'
  'is_enabled_openhab = None\n'
  'is_enabled_web_server = None\n'
  'is_enabled_mi_nm_timer = None\n'
  'is_enabled_ap_nat_timer = None\n'
  'is_enabled_splashscreen = None\n'
  '\n'
  'def get_svc_states():\n'
  '    ps = None\n'
  '    ps_stdout = None\n'
  '\n'
  '    global is_enabled_mi\n'
  '    global is_enabled_wicd\n'
  '    global is_enabled_mi_nm\n'
  '    global is_enabled_ap_nat\n'
  '    global is_enabled_nagios\n'
  '    global is_enabled_hostapd\n'
  '    global is_enabled_dnsmasq\n'
  '    global is_enabled_openhab\n'
  '    global is_enabled_web_server\n'
  '    global is_enabled_mi_nm_timer\n'
  '    global is_enabled_ap_nat_timer\n'
  '    global is_enabled_splashscreen\n'
  '\n'
  '    # Sakis3G mobile internet\n'
  '    if not IMAGE_VERSION or IMAGE_VERSION < MIN_VERSION_WITH_NM:\n'
  '        if '
  "os.path.isfile('/etc/systemd/system/tf_mobile_internet.service'):\n"
  "            ps = subprocess.Popen('/bin/systemctl is-enabled "
  "tf_mobile_internet.service',\n"
  '                                  shell=True,\n'
  '                                  stdout=subprocess.PIPE,\n'
  '                                  stderr=subprocess.PIPE)\n'
  '\n'
  '            ps_stdout = ps.communicate()[0].strip()\n'
  '\n'
  "            if ps_stdout and ps_stdout == 'disabled':\n"
  '                is_enabled_mi = False\n'
  "            elif ps_stdout and ps_stdout == 'enabled':\n"
  '                is_enabled_mi = True\n'
  '\n'
  '        # WICD\n'
  "        ps = subprocess.Popen('/bin/systemctl is-enabled wicd.service',\n"
  '                              shell=True,\n'
  '                              stdout=subprocess.PIPE,\n'
  '                              stderr=subprocess.PIPE)\n'
  '\n'
  '        ps_stdout = ps.communicate()[0].strip()\n'
  '\n'
  "        if ps_stdout and ps_stdout == 'disabled':\n"
  '            is_enabled_wicd = False\n'
  "        elif ps_stdout and ps_stdout == 'enabled':\n"
  '            is_enabled_wicd = True\n'
  '\n'
  '    # NetworkManager mobile internet service and timer\n'
  '    if '
  "os.path.isfile('/etc/systemd/system/tf_mobile_internet_nm.service'):\n"
  "        ps = subprocess.Popen('/bin/systemctl is-enabled "
  "tf_mobile_internet_nm.service',\n"
  '                              shell=True,\n'
  '                              stdout=subprocess.PIPE,\n'
  '                              stderr=subprocess.PIPE)\n'
  '\n'
  '        ps_stdout = ps.communicate()[0].strip()\n'
  '\n'
  "        if ps_stdout and ps_stdout == 'disabled':\n"
  '            is_enabled_mi_nm = False\n'
  "        elif ps_stdout and ps_stdout == 'enabled':\n"
  '            is_enabled_mi_nm = True\n'
  '\n'
  "    if os.path.isfile('/etc/systemd/system/tf_mobile_internet_nm.timer'):\n"
  "        ps = subprocess.Popen('/bin/systemctl is-enabled "
  "tf_mobile_internet_nm.timer',\n"
  '                              shell=True,\n'
  '                              stdout=subprocess.PIPE,\n'
  '                              stderr=subprocess.PIPE)\n'
  '\n'
  '        ps_stdout = ps.communicate()[0].strip()\n'
  '\n'
  "        if ps_stdout and ps_stdout == 'disabled':\n"
  '            is_enabled_mi_nm_timer = False\n'
  "        elif ps_stdout and ps_stdout == 'enabled':\n"
  '            is_enabled_mi_nm_timer = True\n'
  '\n'
  '    # AP NAT setup service and timer\n'
  "    if os.path.isfile('/etc/systemd/system/tf_setup_ap_nat.service'):\n"
  "        ps = subprocess.Popen('/bin/systemctl is-enabled "
  "tf_setup_ap_nat.service',\n"
  '                              shell=True,\n'
  '                              stdout=subprocess.PIPE,\n'
  '                              stderr=subprocess.PIPE)\n'
  '\n'
  '        ps_stdout = ps.communicate()[0].strip()\n'
  '\n'
  "        if ps_stdout and ps_stdout == 'disabled':\n"
  '            is_enabled_ap_nat = False\n'
  "        elif ps_stdout and ps_stdout == 'enabled':\n"
  '            is_enabled_ap_nat = True\n'
  '    else:\n'
  '        is_enabled_ap_nat = False\n'
  '\n'
  "    if os.path.isfile('/etc/systemd/system/tf_setup_ap_nat.timer'):\n"
  "        ps = subprocess.Popen('/bin/systemctl is-enabled "
  "tf_setup_ap_nat.timer',\n"
  '                              shell=True,\n'
  '                              stdout=subprocess.PIPE,\n'
  '                              stderr=subprocess.PIPE)\n'
  '\n'
  '        ps_stdout = ps.communicate()[0].strip()\n'
  '\n'
  "        if ps_stdout and ps_stdout == 'disabled':\n"
  '            is_enabled_ap_nat_timer = False\n'
  "        elif ps_stdout and ps_stdout == 'enabled':\n"
  '            is_enabled_ap_nat_timer = True\n'
  '    else:\n'
  '        is_enabled_ap_nat_timer = False\n'
  '\n'
  '    # Nagios\n'
  '    if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_NAGIOS4:\n'
  "        ps = subprocess.Popen('/bin/systemctl is-enabled nagios.service',\n"
  '                              shell=True,\n'
  '                              stdout=subprocess.PIPE,\n'
  '                              stderr=subprocess.PIPE)\n'
  '\n'
  '        ps_stdout = ps.communicate()[0].strip()\n'
  '\n'
  "        if ps_stdout and ps_stdout == 'disabled':\n"
  '            is_enabled_nagios = False\n'
  "        elif ps_stdout and ps_stdout == 'enabled':\n"
  '            is_enabled_nagios = True\n'
  '    else:\n'
  "        ps = subprocess.Popen('/bin/systemctl is-enabled nagios3.service',\n"
  '                              shell=True,\n'
  '                              stdout=subprocess.PIPE,\n'
  '                              stderr=subprocess.PIPE)\n'
  '\n'
  '        ps_stdout = ps.communicate()[0].strip()\n'
  '\n'
  "        if ps_stdout and ps_stdout == 'disabled':\n"
  '            is_enabled_nagios = False\n'
  "        elif ps_stdout and ps_stdout == 'enabled':\n"
  '            is_enabled_nagios = True\n'
  '\n'
  '    # Hostpad\n'
  "    ps = subprocess.Popen('/bin/systemctl is-enabled hostapd.service',\n"
  '                          shell=True,\n'
  '                          stdout=subprocess.PIPE,\n'
  '                          stderr=subprocess.PIPE)\n'
  '\n'
  '    ps_stdout = ps.communicate()[0].strip()\n'
  '\n'
  "    if ps_stdout and ps_stdout == 'disabled':\n"
  '        is_enabled_hostapd = False\n'
  "    elif ps_stdout and ps_stdout == 'enabled':\n"
  '        is_enabled_hostapd = True\n'
  '\n'
  '    # Dnsmasq\n'
  "    ps = subprocess.Popen('/bin/systemctl is-enabled dnsmasq.service',\n"
  '                          shell=True,\n'
  '                          stdout=subprocess.PIPE,\n'
  '                          stderr=subprocess.PIPE)\n'
  '\n'
  '    ps_stdout = ps.communicate()[0].strip()\n'
  '\n'
  "    if ps_stdout and ps_stdout == 'disabled':\n"
  '        is_enabled_dnsmasq = False\n'
  "    elif ps_stdout and ps_stdout == 'enabled':\n"
  '        is_enabled_dnsmasq = True\n'
  '\n'
  '    # OpenHAB\n'
  '    if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_OPENHAB2:\n'
  "        ps = subprocess.Popen('/bin/systemctl is-enabled "
  "openhab2.service',\n"
  '                              shell=True,\n'
  '                              stdout=subprocess.PIPE,\n'
  '                              stderr=subprocess.PIPE)\n'
  '        ps_stdout = ps.communicate()[0].strip()\n'
  '\n'
  "        if ps_stdout and ps_stdout == 'disabled':\n"
  '            is_enabled_openhab = False\n'
  "        elif ps_stdout and ps_stdout == 'enabled':\n"
  '            is_enabled_openhab = True\n'
  '    else:\n'
  "        ps = subprocess.Popen('/bin/systemctl is-enabled openhab.service',\n"
  '                              shell=True,\n'
  '                              stdout=subprocess.PIPE,\n'
  '                              stderr=subprocess.PIPE)\n'
  '        ps_stdout = ps.communicate()[0].strip()\n'
  '\n'
  "        if ps_stdout and ps_stdout == 'disabled':\n"
  '            is_enabled_openhab = False\n'
  "        elif ps_stdout and ps_stdout == 'enabled':\n"
  '            is_enabled_openhab = True\n'
  '\n'
  '    # Webserver\n'
  "    ps = subprocess.Popen('/bin/systemctl is-enabled apache2.service',\n"
  '                          shell=True,\n'
  '                          stdout=subprocess.PIPE,\n'
  '                          stderr=subprocess.PIPE)\n'
  '\n'
  '    ps_stdout = ps.communicate()[0].strip()\n'
  '\n'
  "    if ps_stdout and ps_stdout == 'disabled':\n"
  '        is_enabled_web_server = False\n'
  "    elif ps_stdout and ps_stdout == 'enabled':\n"
  '        is_enabled_web_server = True\n'
  '\n'
  '    # Splashscreen\n'
  '    if IMAGE_VERSION and IMAGE_VERSION > MAX_VERSION_WITH_ASPLASH_SCREEN:\n'
  "        ps = subprocess.Popen('/bin/systemctl is-enabled "
  "splashscreen.service',\n"
  '                              shell=True,\n'
  '                              stdout=subprocess.PIPE,\n'
  '                              stderr=subprocess.PIPE)\n'
  '\n'
  '        ps_stdout = ps.communicate()[0].strip()\n'
  '\n'
  "        if ps_stdout and ps_stdout == 'disabled':\n"
  '            is_enabled_splashscreen = False\n'
  "        elif ps_stdout and ps_stdout == 'enabled':\n"
  '            is_enabled_splashscreen = True\n'
  '    else:\n'
  "        ps = subprocess.Popen('/bin/systemctl is-enabled "
  "asplashscreen.service',\n"
  '                              shell=True,\n'
  '                              stdout=subprocess.PIPE,\n'
  '                              stderr=subprocess.PIPE)\n'
  '\n'
  '        ps_stdout = ps.communicate()[0].strip()\n'
  '\n'
  "        if ps_stdout and ps_stdout == 'disabled':\n"
  '            is_enabled_splashscreen = False\n'
  "        elif ps_stdout and ps_stdout == 'enabled':\n"
  '            is_enabled_splashscreen = True\n'
  '\n'
  'get_svc_states()\n'
  '\n'
  "if command == 'CHECK':\n"
  '    try:\n'
  "        return_dict = {'gpu'              : None,\n"
  "                       'desktopenv'       : None,\n"
  "                       'webserver'        : None,\n"
  "                       'splashscreen'     : None,\n"
  "                       'ap'               : None,\n"
  "                       'servermonitoring' : None,\n"
  "                       'openhab'          : None,\n"
  "                       'mobileinternet'   : None}\n"
  '\n'
  '        if IMAGE_VERSION and IMAGE_VERSION > MAX_VERSION_WITH_CHKCONFIG:\n'
  '            if is_enabled_web_server:\n'
  "                return_dict['webserver'] = True\n"
  '            else:\n'
  "                return_dict['webserver'] = False\n"
  '\n'
  '            if is_enabled_splashscreen:\n'
  "                return_dict['splashscreen'] = True\n"
  '            else:\n'
  "                return_dict['splashscreen'] = False\n"
  '\n'
  '            if is_enabled_openhab:\n'
  "                return_dict['openhab'] = True\n"
  '            else:\n'
  "                return_dict['openhab'] = False\n"
  '\n'
  "            return_dict['gpu'] = os.path.isfile('/etc/tf_gpu_2d_only')\n"
  '        else:\n'
  '            cmd = \'/sbin/chkconfig | awk -F " " \\\'{print $1 "<==>" '
  "$2}\\''\n"
  '            cmd_ps = subprocess.Popen(cmd, shell=True,\n'
  '                                      stdout=subprocess.PIPE,\n'
  '                                      stderr=subprocess.PIPE)\n'
  '\n'
  '            if cmd_ps.returncode:\n'
  '                exit(3)\n'
  '\n'
  '            init_script_list_str = cmd_ps.communicate()[0].strip()\n'
  '            init_script_list_list = init_script_list_str.splitlines()\n'
  '\n'
  '            for script in init_script_list_list:\n'
  "                script_stat = script.split('<==>')\n"
  '                if len(script_stat) == 2:\n'
  "                    if script_stat[0] == 'apache2':\n"
  "                        return_dict['webserver'] = script_stat[1] == 'on'\n"
  "                    elif script_stat[0] == 'asplashscreen':\n"
  "                        return_dict['splashscreen'] = script_stat[1] == "
  "'on'\n"
  "                    elif script_stat[0] == 'openhab':\n"
  "                        return_dict['openhab'] = script_stat[1] == 'on'\n"
  '\n'
  "            if return_dict['openhab'] == None:\n"
  "                return_dict['openhab'] = False # openHAB is not installed "
  'at all\n'
  '\n'
  "            return_dict['gpu'] = not "
  "os.path.isfile('/etc/modprobe.d/mali-blacklist.conf')\n"
  '\n'
  "        return_dict['desktopenv'] = os.path.isfile('/etc/tf_x11_enabled')\n"
  "        return_dict['ap'] = os.path.isfile('/etc/tf_ap_enabled')\n"
  "        return_dict['servermonitoring'] = "
  "os.path.isfile('/etc/tf_server_monitoring_enabled')\n"
  "        return_dict['mobileinternet'] = "
  "os.path.isfile('/etc/tf_mobile_internet_enabled')\n"
  '\n'
  "        sys.stdout.write(json.dumps(return_dict, separators=(',', ':')))\n"
  '        exit(0)\n'
  '\n'
  '    except Exception as e:\n'
  "        sys.stderr.write(unicode(e).encode('utf-8'))\n"
  '        exit(4)\n'
  '\n'
  "elif command == 'APPLY':\n"
  '    if len(sys.argv) < 3:\n'
  "        sys.stderr.write(u'Missing parameters'.encode('utf-8'))\n"
  '        exit(5)\n'
  '\n'
  '    try:\n'
  '        apply_dict = json.loads(sys.argv[2])\n'
  '\n'
  "        if apply_dict['gpu']:\n"
  '            lines = []\n'
  '\n'
  '            if IMAGE_VERSION and IMAGE_VERSION > '
  'MAX_VERSION_WITH_GPU_2D_3D:\n'
  "                with open('/etc/tf_gpu_2d_only', 'w') as fd_gpu_2d_only:\n"
  '                    pass\n'
  '            else:\n'
  "                with open('/etc/modules', 'r') as fd_r_modules:\n"
  '                    lines = fd_r_modules.readlines()\n'
  '                    for i, l in enumerate(lines):\n'
  "                        if l.strip() == '#mali':\n"
  '                            lines[i] = l[1:]\n'
  '\n'
  "                with open('/etc/modules', 'w') as fd_w_modules:\n"
  "                    fd_w_modules.write(''.join(lines))\n"
  '\n'
  "                if os.path.isfile('/etc/modprobe.d/mali-blacklist.conf'):\n"
  "                    os.remove('/etc/modprobe.d/mali-blacklist.conf')\n"
  '\n'
  "            with open('/etc/X11/xorg.conf', 'w') as fd_fbconf:\n"
  '                fd_fbconf.write(SUNXI_FBTURBO_X11_DRIVER_CONF)\n'
  '\n'
  "            with open('/usr/share/X11/xorg.conf.d/99-sunxifb.conf', 'w') as "
  'fd_fbconf:\n'
  '                fd_fbconf.write(SUNXI_FBTURBO_X11_DRIVER_CONF)\n'
  '\n'
  '        else:\n'
  '            if IMAGE_VERSION and IMAGE_VERSION > '
  'MAX_VERSION_WITH_GPU_2D_3D:\n'
  "                if os.path.isfile('/etc/tf_gpu_2d_only'):\n"
  "                    os.remove('/etc/tf_gpu_2d_only')\n"
  '            else:\n'
  '                lines = []\n'
  "                with open('/etc/modules', 'r') as fd_r_modules:\n"
  '                    lines = fd_r_modules.readlines()\n'
  '\n'
  '                    for i, l in enumerate(lines):\n'
  "                        if l.strip() == 'mali':\n"
  "                            lines[i] = '#'+l\n"
  '\n'
  "                with open('/etc/modules', 'w') as fd_w_modules:\n"
  "                    fd_w_modules.write(''.join(lines))\n"
  '\n'
  "                with open('/etc/modprobe.d/mali-blacklist.conf', 'w') as "
  'fd_w_malibl:\n'
  "                    fd_w_malibl.write('blacklist mali')\n"
  '\n'
  "            with open('/etc/X11/xorg.conf', 'w') as fd_fbconf:\n"
  '                fd_fbconf.write(SUNXI_FBDEV_X11_DRIVER_CONF)\n'
  '\n'
  "            with open('/usr/share/X11/xorg.conf.d/99-sunxifb.conf', 'w') as "
  'fd_fbconf:\n'
  '                fd_fbconf.write(SUNXI_FBDEV_X11_DRIVER_CONF)\n'
  '\n'
  "        if apply_dict['desktopenv']:\n"
  "            with open('/etc/tf_x11_enabled', 'w') as fd_x11_enabled:\n"
  '                pass\n'
  '        else:\n'
  "            if os.path.isfile('/etc/tf_x11_enabled'):\n"
  "                os.remove('/etc/tf_x11_enabled')\n"
  '\n'
  "        if apply_dict['webserver']:\n"
  '            if is_enabled_web_server != None and not '
  'is_enabled_web_server:\n'
  "                if os.system('/bin/systemctl enable apache2') != 0:\n"
  '                    exit(6)\n'
  '        else:\n'
  '            if is_enabled_web_server != None and is_enabled_web_server:\n'
  "                if os.system('/bin/systemctl disable apache2') != 0:\n"
  '                    exit(7)\n'
  '\n'
  "        if apply_dict['splashscreen']:\n"
  '            if IMAGE_VERSION and IMAGE_VERSION > '
  'MAX_VERSION_WITH_ASPLASH_SCREEN:\n'
  '                if is_enabled_splashscreen != None and not '
  'is_enabled_splashscreen:\n'
  "                    if os.system('/bin/systemctl enable splashscreen') != "
  '0:\n'
  '                        exit(8)\n'
  '            else:\n'
  '                if is_enabled_splashscreen != None and not '
  'is_enabled_splashscreen:\n'
  "                    if os.system('/bin/systemctl enable asplashscreen') != "
  '0:\n'
  '                        exit(8)\n'
  '        else:\n'
  '            if IMAGE_VERSION and IMAGE_VERSION > '
  'MAX_VERSION_WITH_ASPLASH_SCREEN:\n'
  '                if is_enabled_splashscreen != None and '
  'is_enabled_splashscreen:\n'
  "                    if os.system('/bin/systemctl disable splashscreen') != "
  '0:\n'
  '                        exit(8)\n'
  '            else:\n'
  '                if is_enabled_splashscreen != None and '
  'is_enabled_splashscreen:\n'
  "                    if os.system('/bin/systemctl disable asplashscreen') != "
  '0:\n'
  '                        exit(9)\n'
  '\n'
  "        if apply_dict['ap']:\n"
  "            with open('/etc/tf_ap_enabled', 'w') as fd_ap_enabled:\n"
  '                pass\n'
  '\n'
  '            if is_enabled_hostapd != None and not is_enabled_hostapd:\n'
  "                if os.system('/bin/systemctl enable hostapd') != 0:\n"
  '                    exit(10)\n'
  '\n'
  '            if is_enabled_dnsmasq != None and not is_enabled_dnsmasq:\n'
  "                if os.system('/bin/systemctl enable dnsmasq') != 0:\n"
  '                    exit(11)\n'
  '\n'
  '            if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_NM:\n'
  "                if os.system('/usr/bin/nmcli radio wifi off') != 0:\n"
  '                    exit(12)\n'
  '            else:\n'
  '                if is_enabled_wicd != None and is_enabled_wicd:\n'
  "                    if os.system('/bin/systemctl disable wicd') != 0:\n"
  '                        exit(12)\n'
  '\n'
  "            if os.path.isfile('/etc/network/interfaces.ap'):\n"
  "                os.rename('/etc/network/interfaces.ap', "
  "'/etc/network/interfaces')\n"
  '\n'
  '            if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_NM:\n'
  '                pass\n'
  '            else:\n'
  "                if os.path.isfile('/etc/xdg/autostart/wicd-tray.desktop'):\n"
  "                    os.rename('/etc/xdg/autostart/wicd-tray.desktop',\n"
  '                              '
  "'/etc/xdg/autostart/wicd-tray.desktop.block')\n"
  '\n'
  '            if '
  "os.path.isfile('/etc/systemd/system/tf_setup_ap_nat.service') and \\\n"
  '               '
  "os.path.isfile('/etc/systemd/system/tf_setup_ap_nat.timer'):\n"
  '                    if is_enabled_ap_nat != None and not '
  'is_enabled_ap_nat:\n'
  "                        os.system('/bin/systemctl enable "
  "/etc/systemd/system/tf_setup_ap_nat.service &> /dev/null')\n"
  '\n'
  '                    if is_enabled_ap_nat_timer != None and not '
  'is_enabled_ap_nat_timer:\n'
  "                        os.system('/bin/systemctl enable "
  "/etc/systemd/system/tf_setup_ap_nat.timer &> /dev/null')\n"
  '\n'
  '        else:\n'
  "            if os.path.isfile('/etc/tf_ap_enabled'):\n"
  "                os.remove('/etc/tf_ap_enabled')\n"
  '\n'
  '            if is_enabled_hostapd != None and is_enabled_hostapd:\n'
  "                if os.system('/bin/systemctl disable hostapd') != 0:\n"
  '                    exit(13)\n'
  '\n'
  '            if is_enabled_dnsmasq != None and is_enabled_dnsmasq:\n'
  "                if os.system('/bin/systemctl disable dnsmasq') != 0:\n"
  '                    exit(14)\n'
  '\n'
  '            if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_NM:\n'
  "                if os.system('/usr/bin/nmcli radio wifi on') != 0:\n"
  '                    exit(15)\n'
  '            else:\n'
  '                if is_enabled_wicd != None and not is_enabled_wicd:\n'
  "                    if os.system('/bin/systemctl enable wicd') != 0:\n"
  '                        exit(15)\n'
  '\n'
  "            with open('/etc/network/interfaces', 'w') as fd_interfaces:\n"
  '                fd_interfaces.write(INTERFACES_CONF)\n'
  '\n'
  '            if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_NM:\n'
  '                pass\n'
  '            else:\n'
  '                if '
  "os.path.isfile('/etc/xdg/autostart/wicd-tray.desktop.block'):\n"
  '                    '
  "os.rename('/etc/xdg/autostart/wicd-tray.desktop.block',\n"
  "                              '/etc/xdg/autostart/wicd-tray.desktop')\n"
  '\n'
  '            if '
  "os.path.isfile('/etc/systemd/system/tf_setup_ap_nat.service') and \\\n"
  '               '
  "os.path.isfile('/etc/systemd/system/tf_setup_ap_nat.timer'):\n"
  '                    if is_enabled_ap_nat != None and is_enabled_ap_nat:\n'
  "                        os.system('/bin/systemctl disable "
  "/etc/systemd/system/tf_setup_ap_nat.service &> /dev/null')\n"
  '\n'
  '                    if is_enabled_ap_nat_timer != None and '
  'is_enabled_ap_nat_timer:\n'
  "                        os.system('/bin/systemctl disable "
  "/etc/systemd/system/tf_setup_ap_nat.timer &> /dev/null')\n"
  '\n'
  "        if apply_dict['servermonitoring']:\n"
  "            if not apply_dict['webserver']:\n"
  "                if os.system('/bin/systemctl enable apache2') != 0:\n"
  '                    exit(16)\n'
  '\n'
  "            with open('/etc/tf_server_monitoring_enabled', 'w') as "
  'fd_server_monitoring_enabled:\n'
  '                pass\n'
  '\n'
  '            if IMAGE_VERSION and IMAGE_VERSION >= '
  'MIN_VERSION_WITH_NAGIOS4:\n'
  '                if is_enabled_nagios != None and not is_enabled_nagios:\n'
  "                    if os.system('/bin/systemctl enable nagios') != 0:\n"
  '                        exit(17)\n'
  '            else:\n'
  '                if is_enabled_nagios != None and not is_enabled_nagios:\n'
  "                    if os.system('/bin/systemctl enable nagios3') != 0:\n"
  '                        exit(17)\n'
  '\n'
  '        else:\n'
  "            if os.path.isfile('/etc/tf_server_monitoring_enabled'):\n"
  "                os.remove('/etc/tf_server_monitoring_enabled')\n"
  '\n'
  '            if IMAGE_VERSION and IMAGE_VERSION >= '
  'MIN_VERSION_WITH_NAGIOS4:\n'
  '                if is_enabled_nagios != None and is_enabled_nagios:\n'
  "                    if os.system('/bin/systemctl disable nagios') != 0:\n"
  '                        exit(18)\n'
  '            else:\n'
  '                if is_enabled_nagios != None and is_enabled_nagios:\n'
  "                    if os.system('/bin/systemctl disable nagios3') != 0:\n"
  '                        exit(18)\n'
  '\n'
  "        if apply_dict['openhab']:\n"
  '            if IMAGE_VERSION and IMAGE_VERSION >= '
  'MIN_VERSION_WITH_OPENHAB2:\n'
  '                if is_enabled_openhab != None and not is_enabled_openhab:\n'
  "                    if os.system('/bin/systemctl enable openhab2') != 0:\n"
  '                        exit(19)\n'
  '            else:\n'
  '                if is_enabled_openhab != None and not is_enabled_openhab:\n'
  "                    if os.system('/bin/systemctl enable openhab') != 0:\n"
  '                        exit(19)\n'
  '        else:\n'
  '            if IMAGE_VERSION and IMAGE_VERSION >= '
  'MIN_VERSION_WITH_OPENHAB2:\n'
  '                if is_enabled_openhab != None and is_enabled_openhab:\n'
  "                    if os.system('/bin/systemctl disable openhab2') != 0:\n"
  '                        exit(20)\n'
  '            else:\n'
  '                if is_enabled_openhab != None and is_enabled_openhab:\n'
  "                    if os.system('/bin/systemctl disable openhab') != 0:\n"
  '                        exit(20)\n'
  '\n'
  "        if apply_dict['mobileinternet']:\n"
  '            if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_NM:\n'
  '                if not '
  "os.path.isfile('/etc/tf_mobile_internet_enabled.disabled'):\n"
  '                    if not '
  "os.path.isfile('/etc/tf_mobile_internet_enabled'):\n"
  "                        with open('/etc/tf_mobile_internet_enabled', 'w') "
  'as fd_ap_enabled:\n'
  '                            pass\n'
  '                else:\n'
  "                    os.rename('/etc/tf_mobile_internet_enabled.disabled',\n"
  "                              '/etc/tf_mobile_internet_enabled')\n"
  '\n'
  '                if '
  "os.path.isfile('/etc/systemd/system/tf_mobile_internet_nm.service') \\\n"
  '                   and '
  "os.path.isfile('/etc/systemd/system/tf_mobile_internet_nm.timer'):\n"
  '                        if is_enabled_mi_nm != None and not '
  'is_enabled_mi_nm:\n'
  "                            if os.system('/bin/systemctl enable "
  "tf_mobile_internet_nm.service') != 0:\n"
  '                                exit(21)\n'
  '\n'
  '                        if is_enabled_mi_nm_timer != None and not '
  'is_enabled_mi_nm_timer:\n'
  "                            if os.system('/bin/systemctl enable "
  "tf_mobile_internet_nm.timer') != 0:\n"
  '                                exit(21)\n'
  '            else:\n'
  "                with open('/etc/tf_mobile_internet_enabled', 'w') as "
  'fd_ap_enabled:\n'
  '                    pass\n'
  '\n'
  '                if '
  "os.path.isfile('/etc/systemd/system/tf_mobile_internet.service'):\n"
  '                    if is_enabled_mi != None and not is_enabled_mi:\n'
  "                        if os.system('/bin/systemctl enable "
  "tf_mobile_internet') != 0:\n"
  '                            exit(21)\n'
  '        else:\n'
  '            if IMAGE_VERSION and IMAGE_VERSION >= MIN_VERSION_WITH_NM:\n'
  "                if not os.path.isfile('/etc/tf_mobile_internet_enabled'):\n"
  '                    if not '
  "os.path.isfile('/etc/tf_mobile_internet_enabled.disabled'):\n"
  '                        with '
  "open('/etc/tf_mobile_internet_enabled.disabled', 'w') as fd_ap_disabled:\n"
  '                            pass\n'
  '                else:\n'
  "                    os.rename('/etc/tf_mobile_internet_enabled',\n"
  "                              '/etc/tf_mobile_internet_enabled.disabled')\n"
  '\n'
  '                if '
  "os.path.isfile('/etc/systemd/system/tf_mobile_internet_nm.service') \\\n"
  '                   and '
  "os.path.isfile('/etc/systemd/system/tf_mobile_internet_nm.timer'):\n"
  '                        if is_enabled_mi_nm != None and is_enabled_mi_nm:\n'
  "                            if os.system('/bin/systemctl disable "
  "tf_mobile_internet_nm.service') != 0:\n"
  '                                exit(22)\n'
  '\n'
  '                        if is_enabled_mi_nm_timer != None and '
  'is_enabled_mi_nm_timer:\n'
  "                            if os.system('/bin/systemctl disable "
  "tf_mobile_internet_nm.timer') != 0:\n"
  '                                exit(22)\n'
  '            else:\n'
  "                if os.path.isfile('/etc/tf_mobile_internet_enabled'):\n"
  "                    os.remove('/etc/tf_mobile_internet_enabled')\n"
  '\n'
  '                if '
  "os.path.isfile('/etc/systemd/system/tf_mobile_internet.service'):\n"
  '                    if is_enabled_mi != None and is_enabled_mi:\n'
  "                        if os.system('/bin/systemctl disable "
  "tf_mobile_internet') != 0:\n"
  '                            exit(22)\n'
  '\n'
  '        exit(0)\n'
  '\n'
  '    except Exception as e:\n'
  "        sys.stderr.write(unicode(e).encode('utf-8'))\n"
  '        exit(23)\n'
  '\n'
  'else:\n'
  "    sys.stderr.write(u'Invalid parameters'.encode('utf-8'))\n"
  '    exit(22)\n'),
 ('settings_time_get',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import datetime\n'
  'import time\n'
  'import os\n'
  '\n'
  'def time_utc_offset(t):\n'
  '    if time.localtime(t).tm_isdst and time.daylight:\n'
  '        return -time.altzone\n'
  '\n'
  '    return -time.timezone\n'
  '\n'
  'def convert_from_posix(tz):\n'
  "    tz = tz.replace('Etc/', '')\n"
  "    #.startswith('GMT') breaks the GMT timezone (without offset)\n"
  "    if tz.startswith('GMT+') or tz.startswith('GMT-'):\n"
  "        gmt_offset = -int(tz.replace('GMT', '')) # Convert from POSIX "
  'offset\n'
  "        tz = 'UTC' + ('+' if gmt_offset > 0 else '') + str(gmt_offset)\n"
  '    return tz\n'
  '\n'
  'def timezone():\n'
  '    try:\n'
  '        from tzlocal import get_localzone\n'
  '        return get_localzone().zone\n'
  '    except:\n'
  '        pass\n'
  '\n'
  '    try:\n'
  "        if not os.path.islink('/etc/localtime'):\n"
  "            return 'not set'\n"
  '\n'
  "        tz = os.readlink('/etc/localtime')\n"
  "        return convert_from_posix(tz.replace('/usr/share/zoneinfo/', ''))\n"
  '    except:\n'
  '        pass\n'
  '\n'
  "    return 'could not be queried'\n"
  '\n'
  'def localtime_as_iso8601():\n'
  '    utc_offset_sec = -(time.altzone if time.localtime().tm_isdst else '
  'time.timezone)\n'
  '    utc_offset_hours = (utc_offset_sec // 3600)\n'
  '    utc_offset_minutes = (utc_offset_sec % 3600 // 60)\n'
  '    return '
  '"{}{}{:02}:{:02}".format(datetime.datetime.now().replace(microsecond=0).isoformat(),\n'
  "                                    '+' if utc_offset_sec > 0 else '',\n"
  '                                    utc_offset_hours,\n'
  '                                    utc_offset_minutes)\n'
  '\n'
  't = time.time()\n'
  '\n'
  'print(int(t))\n'
  'print(localtime_as_iso8601())\n'
  'print(timezone())\n'),
 ('update_tf_software_copy_bindings',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import sys\n'
  'import shutil\n'
  '\n'
  'if len(sys.argv) != 3:\n'
  "    sys.stderr.write(u'Wrong number of parameters "
  "provided'.encode('utf-8'))\n"
  '    exit(1)\n'
  '\n'
  'for di in os.listdir(sys.argv[1]):\n'
  '    if not os.path.isdir(os.path.join(sys.argv[1], di)):\n'
  '        continue\n'
  '\n'
  '    if di != sys.argv[2]:\n'
  '        continue\n'
  '\n'
  "    bindings_path = os.path.join('/usr/tinkerforge/bindings', sys.argv[2])\n"
  '\n'
  '    if not os.path.isdir(bindings_path):\n'
  '        continue\n'
  '\n'
  '    shutil.rmtree(bindings_path)\n'
  '    shutil.copytree(os.path.join(sys.argv[1], sys.argv[2]), '
  'bindings_path)\n'),
 ('update_tf_software_get_installed_versions',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import re\n'
  'import sys\n'
  'import json\n'
  'import subprocess\n'
  '\n'
  "BINDINGS_DIR = '/usr/tinkerforge/bindings/'\n"
  "BINDINGS = ['c', 'csharp', 'delphi', 'java',\n"
  "            'javascript', 'matlab', 'perl', 'php',\n"
  "            'python', 'ruby', 'shell', 'vbnet']\n"
  '\n'
  "return_dict = {'brickv': None, 'bindings':{}}\n"
  '\n'
  'err = False\n'
  "err_msg = ''\n"
  '\n'
  "with open(os.devnull, 'w') as dev_null:\n"
  "    dpkg = subprocess.Popen(['/usr/bin/dpkg','-s', 'brickv'],\n"
  '                            stdout=subprocess.PIPE,\n'
  '                            stderr=dev_null)\n'
  '\n'
  "    grep = subprocess.Popen(['/bin/grep', 'Version:'],\n"
  '                            stdin=dpkg.stdout,\n'
  '                            stdout=subprocess.PIPE,\n'
  '                            stderr=dev_null)\n'
  '\n'
  'output_grep = None\n'
  '(output_grep, _) = grep.communicate()\n'
  '\n'
  'if output_grep is not None and type(output_grep) is str:\n'
  "    output_grep_split = output_grep.split(':')\n"
  '\n'
  '    if len(output_grep_split) != 2:\n'
  '        err = True\n'
  "        return_dict['brickv'] = '-'\n"
  "        err_msg += 'Could not read Brick Viewer installed version\\n'\n"
  '    else:\n'
  "        return_dict['brickv'] = output_grep_split[1].strip()\n"
  'else:\n'
  '    err = True\n'
  "    err_msg += 'Could not read Brick Viewer installed version\\n'\n"
  '\n'
  'def get_changelog_version(bindings_root_directory):\n'
  '    r1 = '
  "re.compile('^\\d{4}-\\d{2}-\\d{2}:\\s(\\d+)\\.(\\d+)\\.(\\d+)\\s\\(')\n"
  "    r2 = re.compile('^(\\d+)\\.(\\d+)\\.(\\d+):')\n"
  '    last = None\n'
  '\n'
  "    with open(os.path.join(bindings_root_directory, 'changelog.txt'), 'rb') "
  'as f:\n'
  '        for line in f.readlines():\n'
  '            m = r1.match(line)\n'
  '\n'
  '            if m == None:\n'
  '                m = r2.match(line)\n'
  '\n'
  '            if m is not None:\n'
  '                last = (m.group(1), m.group(2), m.group(3))\n'
  '\n'
  '    return last\n'
  '\n'
  'for b in BINDINGS:\n'
  '    try:\n'
  '        path = os.path.join(BINDINGS_DIR, b)\n'
  "        return_dict['bindings'][b] = "
  "'.'.join(get_changelog_version(path)).strip()\n"
  '    except:\n'
  '        err = True\n'
  "        display_name = ''\n"
  "        return_dict['bindings'][b] = '-'\n"
  '\n'
  "        if b == 'c':\n"
  "            display_name = 'C/C++ Bindings'\n"
  "        elif b == 'csharp':\n"
  "            display_name = 'C#/Mono Bindings'\n"
  "        elif b == 'delphi':\n"
  "            display_name = 'Delphi/Lazarus Bindings'\n"
  "        elif b == 'java':\n"
  "            display_name = 'Java Bindings'\n"
  "        elif b == 'javascript':\n"
  "            display_name = 'JavaScript Bindings'\n"
  "        elif b == 'matlab':\n"
  "            display_name = 'Octave Bindings'\n"
  "        elif b == 'perl':\n"
  "            display_name = 'Perl Bindings'\n"
  "        elif b == 'php':\n"
  "            display_name = 'PHP Bindings'\n"
  "        elif b == 'python':\n"
  "            display_name = 'Python Bindings'\n"
  "        elif b == 'ruby':\n"
  "            display_name = 'Ruby Bindings'\n"
  "        elif b == 'shell':\n"
  "            display_name = 'Shell Bindings'\n"
  "        elif b == 'vbnet':\n"
  "            display_name = 'VB.NET Bindings'\n"
  '\n'
  "        err_msg += 'Could not read ' + display_name + ' installed "
  "version\\n'\n"
  '\n'
  'if err:\n'
  "    sys.stderr.write(unicode(err_msg).encode('utf-8'))\n"
  '    exit(1)\n'
  '\n'
  "sys.stdout.write(json.dumps(return_dict, separators=(',', ':')))\n"),
 ('update_tf_software_mkdtemp',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import sys\n'
  'import shutil\n'
  'import tempfile\n'
  '\n'
  't = tempfile.mkdtemp()\n'
  "bindings = os.path.join(t, 'bindings')\n"
  '\n'
  'if os.path.exists(bindings):\n'
  '    shutil.rmtree(bindings)\n'
  '\n'
  'os.makedirs(bindings)\n'
  '\n'
  "sys.stdout.write(unicode(t).encode('utf-8'))\n"),
 ('versions_main',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import os\n'
  'import re\n'
  '\n'
  "BINDINGS_DIR = '/usr/tinkerforge/bindings/'\n"
  "BINDINGS = ['c', 'csharp', 'delphi', 'java', 'javascript', 'matlab', "
  "'perl', 'php', 'python', 'ruby', 'shell', 'vbnet']\n"
  '\n'
  'def get_changelog_version(bindings_root_directory):\n'
  '    r1 = '
  "re.compile('^\\d{4}-\\d{2}-\\d{2}:\\s(\\d+)\\.(\\d+)\\.(\\d+)\\s\\(')\n"
  "    r2 = re.compile('^(\\d+)\\.(\\d+)\\.(\\d+):')\n"
  '    last = None\n'
  '\n'
  "    with open(os.path.join(bindings_root_directory, 'changelog.txt'), 'rb') "
  'as f:\n'
  '        for line in f.readlines():\n'
  '            m = r1.match(line)\n'
  '\n'
  '            if m == None:\n'
  '                m = r2.match(line)\n'
  '\n'
  '            if m != None:\n'
  '                last = (m.group(1), m.group(2), m.group(3))\n'
  '\n'
  '    return last\n'
  '\n'
  "os.system('/usr/bin/brickd --version')\n"
  "os.system('/usr/bin/redapid --version')\n"
  "os.system('/bin/cat /etc/tf_image_version')\n"
  '\n'
  'for b in BINDINGS:\n'
  '    try:\n'
  '        path = os.path.join(BINDINGS_DIR, b)\n'
  "        print('.'.join(get_changelog_version(path)))\n"
  '    except:\n'
  "        print('Unknown')\n"),
 ('walk',
  '.py',
  '#!/usr/bin/env python2\n'
  '# -*- coding: utf-8 -*-\n'
  '\n'
  'import json\n'
  'import os\n'
  'import sys\n'
  'import zlib\n'
  '\n'
  'result = {}\n'
  '\n'
  'if len(sys.argv) < 2 or not os.path.isdir(sys.argv[1]):\n'
  "    sys.stderr.write(u'Missing or invalid parameters'.encode('utf-8'))\n"
  '    exit(2)\n'
  '\n'
  'base = sys.argv[1]\n'
  '\n'
  'try:\n'
  '    for root, directories, files in os.walk(base):\n'
  '        relative_root = os.path.relpath(root, base)\n'
  "        children      = result.setdefault('c', {})\n"
  '\n'
  "        if relative_root != '.':\n"
  "            for part in relative_root.split('/'):\n"
  '                directory = children.setdefault(part, {})\n'
  "                children  = directory.setdefault('c', {})\n"
  '\n'
  "                if 'l' not in directory:\n"
  '                    st             = os.lstat(root)\n'
  "                    directory['l'] = int(st.st_mtime)\n"
  "                    directory['p'] = int(st.st_mode)\n"
  '\n'
  '        for filename in files:\n'
  '            absolute           = os.path.join(root, filename)\n'
  '            st                 = os.lstat(absolute)\n'
  "            children[filename] = {'s': st.st_size, 'l': int(st.st_mtime), "
  "'p': int(st.st_mode)}\n"
  'except Exception as e:\n'
  "    sys.stderr.write(unicode(e).encode('utf-8'))\n"
  '    exit(3)\n'
  '\n'
  "sys.stdout.write(zlib.compress(json.dumps(result, separators=(',', ':'))))\n"
  'exit(0)\n'),
 ('fpc_versions', '.sh', '#!/bin/sh\n\n/usr/bin/fpc -i V\n'),
 ('fpcmake_helper',
  '.sh',
  '#!/bin/sh -e\n'
  '\n'
  'export FPCDIR=/usr/lib/fpc/default\n'
  '\n'
  'cd $1\n'
  'shift\n'
  'fpcmake\n'
  'make $@\n'),
 ('gcc_versions',
  '.sh',
  '#!/bin/sh\n\n/usr/bin/gcc --version\n/usr/bin/g++ --version\n'),
 ('java_versions', '.sh', '#!/bin/sh\n\n/usr/bin/java -version\n\n'),
 ('lazbuild_helper',
  '.sh',
  '#!/bin/sh -e\n'
  '\n'
  'export FPCDIR=/usr/lib/fpc/default\n'
  '\n'
  'cd $1\n'
  'shift\n'
  'lazbuild $@ *.lpi\n'),
 ('lazbuild_versions', '.sh', '#!/bin/sh\n\n/usr/bin/lazbuild --version\n\n'),
 ('make_helper', '.sh', '#!/bin/sh -e\n\ncd $1\nshift\nmake $@\n'),
 ('mono_versions', '.sh', '#!/bin/sh\n\n/usr/bin/mono --version\n'),
 ('nodejs_versions', '.sh', '#!/bin/sh\n\n/usr/local/bin/node --version\n'),
 ('octave_versions', '.sh', '#!/bin/sh\n\n/usr/bin/octave --version\n'),
 ('perl_versions', '.sh', '#!/bin/sh\n\n/usr/bin/perl --version\n'),
 ('php_versions', '.sh', '#!/bin/sh\n\n/usr/bin/php --version\n'),
 ('pkill_ttyGS0',
  '.sh',
  '#!/bin/sh -e\n\n/usr/bin/pkill --signal $1 --terminal ttyGS0\n'),
 ('python_versions',
  '.sh',
  '#!/bin/sh\n\n/usr/bin/python2 --version\n/usr/bin/python3 --version\n'),
 ('restart_brickd', '.sh', '#!/bin/sh\n\n/etc/init.d/brickd restart\n'),
 ('ruby_versions', '.sh', '#!/bin/sh\n\n/usr/bin/ruby --version\n'),
 ('settings_fs_expand',
  '.sh',
  '#!/bin/sh -e\n'
  '\n'
  'PART_START=$(/bin/cat /sys/block/mmcblk0/mmcblk0p1/start)\n'
  '\n'
  '# prefer parted if available (since image version 1.4), because fdisk\n'
  '# on debian jessie reports a warning and exits with an error. this makes\n'
  '# it harder to automatically tell real errors apart from simple warnings\n'
  '\n'
  'if [ -x "/sbin/parted" ]; then\n'
  '\n'
  '/sbin/parted /dev/mmcblk0 <<EOF\n'
  'resizepart 1 -1s\n'
  'I\n'
  'quit\n'
  'EOF\n'
  '\n'
  'else\n'
  '\n'
  '/sbin/fdisk /dev/mmcblk0 <<EOF\n'
  'd\n'
  'n\n'
  'p\n'
  '1\n'
  '$PART_START\n'
  '\n'
  'w\n'
  'EOF\n'
  '\n'
  'fi\n'
  '\n'
  't=$(tempfile)\n'
  '\n'
  '/bin/echo -e "#!/bin/sh\n'
  '### BEGIN INIT INFO\n'
  '# Provides:          brickv-expand-filesystem\n'
  '# Required-Start:    \\$remote_fs \\$syslog\n'
  '# Required-Stop:     \\$remote_fs \\$syslog\n'
  '# Default-Start:     2 3 4 5\n'
  '# Default-Stop:      0 1 6\n'
  '# X-Start-Before:    redapid brickd\n'
  '# Short-Description: brickv-expand-filesystem\n'
  '# Description:       Finishes filesystem expansion before RED Brick API '
  'Daemon starts\n'
  '### END INIT INFO\n'
  '\n'
  '. /lib/lsb/init-functions\n'
  '\n'
  'case \\"\\$1\\" in\n'
  '  start)\n'
  '\tlog_daemon_msg \\"Finishes filesystem expansion\\" '
  '\\"brickv-expand-filesystem\\"\n'
  '\n'
  '\t/sbin/resize2fs -p /dev/mmcblk0p1\n'
  '\n'
  '\tif [ -x /bin/systemctl ]; then\n'
  '\t\tsystemctl disable brickv-expand-filesystem\n'
  '\telse\n'
  '\t\tupdate-rc.d -f brickv-expand-filesystem remove\n'
  '\tfi\n'
  '\n'
  '\trm -f /etc/init.d/brickv-expand-filesystem\n'
  '\n'
  '\tif [ -x /bin/systemctl ]; then\n'
  '\t\tsystemctl daemon-reload\n'
  '\tfi\n'
  '\n'
  '\tlog_end_msg 0\n'
  '\t;;\n'
  '  stop)\n'
  '\t;;\n'
  '  restart|force-reload)\n'
  '\t;;\n'
  '  status)\n'
  '\t;;\n'
  '  *)\n'
  '\techo \\"Usage: /etc/init.d/brickv-expand-filesystem '
  '{{start|stop|restart|force-reload|status}}\\" >&2\n'
  '\texit 1\n'
  '\t;;\n'
  'esac\n'
  '\n'
  'exit 0\n'
  '" > $t\n'
  '\n'
  'chmod 0755 $t\n'
  'mv $t /etc/init.d/brickv-expand-filesystem\n'
  '\n'
  'if [ -x /bin/systemctl ]; then\n'
  '\tsystemctl daemon-reload\n'
  '\tsystemctl enable brickv-expand-filesystem\n'
  'else\n'
  '\tupdate-rc.d brickv-expand-filesystem defaults\n'
  'fi\n'),
 ('shell_versions', '.sh', '#!/bin/sh\n\n/bin/bash --version\n'),
 ('update_tf_software_install',
  '.sh',
  '#!/bin/sh\n'
  '\n'
  'if [ $# -ne 3 ]; then\n'
  '    exit 1\n'
  'fi\n'
  '\n'
  'echostderr() { echo "$@" 1>&2; }\n'
  '\n'
  'case "$1" in\n'
  '  "brickv")\n'
  '    $(/usr/bin/which apt-get) remove --purge brickv -y &> /dev/null; \\\n'
  '    $(/usr/bin/which dpkg) -i $3 &> /dev/null\n'
  '\n'
  '    if [ $? -eq 0 ]; then\n'
  '      exit 0\n'
  '    else\n'
  '      exit 1\n'
  '    fi\n'
  '\n'
  '    ;;\n'
  '\n'
  '  "c")\n'
  '    $(/usr/bin/which unzip) -q -d $2/bindings/c $3 &> /dev/null && \\\n'
  '    cd $2/bindings/c/source &> /dev/null && \\\n'
  '    $(/usr/bin/which rm) -f /usr/lib/libtinkerforge.so &> /dev/null; \\\n'
  '    $(/usr/bin/which make) &> /dev/null && \\\n'
  '    $(/usr/bin/which make) prefix=/usr install &> /dev/null && \\\n'
  '    $(/usr/bin/which make) clean &> /dev/null\n'
  '\n'
  '    if [ $? -eq 0 ]; then\n'
  '      exit 0\n'
  '    else\n'
  '      exit 1\n'
  '    fi\n'
  '\n'
  '    ;;\n'
  '\n'
  '  "csharp")\n'
  '    $(/usr/bin/which unzip) -q -d $2/bindings/csharp $3 &> /dev/null && \\\n'
  '    cd $2/bindings/csharp &> /dev/null && \\\n'
  '    $(/usr/bin/which rm) -f /usr/lib/Tinkerforge.dll &> /dev/null; \\\n'
  '    $(/usr/bin/which cp) -f Tinkerforge.dll /usr/lib &> /dev/null\n'
  '\n'
  '    if [ $? -eq 0 ]; then\n'
  '      exit 0\n'
  '    else\n'
  '      exit 1\n'
  '    fi\n'
  '\n'
  '    ;;\n'
  '\n'
  '  "delphi")\n'
  '    $(/usr/bin/which unzip) -q -d $2/bindings/delphi $3 &> /dev/null && \\\n'
  '    cd $2/bindings/delphi/source &> /dev/null && \\\n'
  '    $(/usr/bin/which rm) -rf '
  '/usr/lib/fpc/default/units/arm-linux/tinkerforge &> /dev/null; \\\n'
  '    $(/usr/bin/which fpcmake) &> /dev/null && \\\n'
  '    $(/usr/bin/which make) FPCDIR=/usr/lib/fpc/default &> /dev/null && \\\n'
  '    $(/usr/bin/which make) FPCDIR=/usr/lib/fpc/default install &> /dev/null '
  '&& \\\n'
  '    $(/usr/bin/which make) clean &> /dev/null\n'
  '\n'
  '    if [ $? -eq 0 ]; then\n'
  '      exit 0\n'
  '    else\n'
  '      exit 1\n'
  '    fi\n'
  '\n'
  '    ;;\n'
  '\n'
  '  "java")\n'
  '    $(/usr/bin/which unzip) -q -d $2/bindings/java $3 &> /dev/null\n'
  '\n'
  '    if [ $? -eq 0 ]; then\n'
  '      exit 0\n'
  '    else\n'
  '      exit 1\n'
  '    fi\n'
  '\n'
  '    ;;\n'
  '\n'
  '  "javascript")\n'
  '    $(/usr/bin/which unzip) -q -d $2/bindings/javascript $3 &> /dev/null && '
  '\\\n'
  '    cd $2/bindings/javascript/nodejs &> /dev/null && \\\n'
  '    $(/usr/bin/which npm) uninstall -g tinkerforge &> /dev/null; \\\n'
  '    $(/usr/bin/which npm) install -g ./tinkerforge.tgz &> /dev/null\n'
  '\n'
  '    if [ $? -eq 0 ]; then\n'
  '      exit 0\n'
  '    else\n'
  '      exit 1\n'
  '    fi\n'
  '\n'
  '    ;;\n'
  '\n'
  '  "matlab")\n'
  '    $(/usr/bin/which unzip) -q -d $2/bindings/matlab $3 &> /dev/null\n'
  '\n'
  '    if [ $? -eq 0 ]; then\n'
  '      exit 0\n'
  '    else\n'
  '      exit 1\n'
  '    fi\n'
  '\n'
  '    ;;\n'
  '\n'
  '  "perl")\n'
  '    $(/usr/bin/which unzip) -q -d $2/bindings/perl $3 &> /dev/null && \\\n'
  '    cd $2/bindings/perl/source &> /dev/null && \\\n'
  '    $(/usr/bin/which cpanm) -f --uninstall Tinkerforge &> /dev/null; \\\n'
  '    $(/usr/bin/which find) . -exec $(/usr/bin/which touch) {} \\; &> '
  '/dev/null && \\\n'
  '    $(/usr/bin/which perl) Makefile.PL &> /dev/null && \\\n'
  '    $(/usr/bin/which make) all &> /dev/null\n'
  '\n'
  '    if [ $? -ne 0 ]; then\n'
  '      $(/usr/bin/which make) all &> /dev/null\n'
  '    fi\n'
  '\n'
  '    $(/usr/bin/which make) install &> /dev/null\n'
  '\n'
  '    if [ $? -eq 0 ]; then\n'
  '      exit 0\n'
  '    else\n'
  '      exit 1\n'
  '    fi\n'
  '\n'
  '    ;;\n'
  '\n'
  '  "php")\n'
  '    $(/usr/bin/which unzip) -q -d $2/bindings/php $3 &> /dev/null && \\\n'
  '    cd $2/bindings/php &> /dev/null && \\\n'
  '    $(/usr/bin/which pear) uninstall __uri/Tinkerforge &> /dev/null; \\\n'
  '    $(/usr/bin/which pear) install ./Tinkerforge.tgz &> /dev/null\n'
  '\n'
  '    if [ $? -eq 0 ]; then\n'
  '      exit 0\n'
  '    else\n'
  '      exit 1\n'
  '    fi\n'
  '\n'
  '    ;;\n'
  '\n'
  '  "python")\n'
  '    # Some python bindings release use "setuptools"(older) and some\n'
  '    # "distutils"(newer) to install the bindings. If the currently '
  'installed\n'
  '    # Python bindings were installed with "setuptools" then it is installed '
  'as\n'
  '    # ".egg" file.\n'
  '    #\n'
  '    # After an update if the newer bindings were installed with "distutils" '
  'then\n'
  '    # it will be installed as an ".egg-info".\n'
  '    #\n'
  '    # The ".egg" file seem to have priority while resolving for Python '
  'modules.\n'
  '    # As a result in this case the older modules will be loaded even after '
  'the\n'
  '    # update.\n'
  '    #\n'
  '    # To fix this problem first "pip uninstall" is used before updating '
  'the\n'
  '    # bindings.\n'
  '    $(/usr/bin/which unzip) -q -d $2/bindings/python $3 &> /dev/null && \\\n'
  '    cd $2/bindings/python/source &> /dev/null && \\\n'
  '    $(/usr/bin/which pip) uninstall tinkerforge -y &> /dev/null; \\\n'
  '    $(/usr/bin/which pip3) uninstall tinkerforge -y &> /dev/null; \\\n'
  '    $(/usr/bin/which python2) setup.py install &> /dev/null && \\\n'
  '    $(/usr/bin/which python3) setup.py install &> /dev/null\n'
  '\n'
  '    if [ $? -eq 0 ]; then\n'
  '      exit 0\n'
  '    else\n'
  '      exit 1\n'
  '    fi\n'
  '\n'
  '    ;;\n'
  '\n'
  '  "ruby")\n'
  '    $(/usr/bin/which unzip) -q -d $2/bindings/ruby $3 &> /dev/null && \\\n'
  '    cd $2/bindings/ruby &> /dev/null && \\\n'
  '    $(/usr/bin/which gem) uninstall tinkerforge &> /dev/null; \\\n'
  '    $(/usr/bin/which gem) install --local --no-document ./tinkerforge.gem '
  '&> /dev/null\n'
  '\n'
  '    if [ $? -eq 0 ]; then\n'
  '      exit 0\n'
  '    else\n'
  '      exit 1\n'
  '    fi\n'
  '\n'
  '    ;;\n'
  '\n'
  '  "shell")\n'
  '    $(/usr/bin/which unzip) -q -d $2/bindings/shell $3 &> /dev/null && \\\n'
  '    cd $2/bindings/shell &> /dev/null && \\\n'
  '    $(/usr/bin/which rm) -f /usr/local/bin/tinkerforge &> /dev/null; \\\n'
  '    $(/usr/bin/which rm) -f '
  '/etc/bash_completion.d/tinkerforge-bash-completion.sh &> /dev/null; \\\n'
  '    $(/usr/bin/which cp) -f tinkerforge /usr/local/bin &> /dev/null && \\\n'
  '    $(/usr/bin/which cp) -f tinkerforge-bash-completion.sh '
  '/etc/bash_completion.d &> /dev/null\n'
  '\n'
  '    if [ $? -eq 0 ]; then\n'
  '      exit 0\n'
  '    else\n'
  '      exit 1\n'
  '    fi\n'
  '\n'
  '    ;;\n'
  '\n'
  '  "vbnet")\n'
  '    $(/usr/bin/which unzip) -q -d $2/bindings/vbnet $3 &> /dev/null\n'
  '\n'
  '    if [ $? -eq 0 ]; then\n'
  '      exit 0\n'
  '    else\n'
  '      exit 1\n'
  '    fi\n'
  '\n'
  '    ;;\n'
  'esac\n'
  '\n'
  'exit 0\n')]