#!/usr/bin/env python3

import os
import sys
import subprocess
from tempfile import mkstemp
from shutil import move
from os import close


def write_setting(setting, value):
    """

    """
    CONFIG = "/boot/config.txt"

    command = "{}={}".format(setting, value)
    key = setting
    matched_key = False

    filepath = CONFIG
    # Create a temporary file
    fh, tmp_absolute_path = mkstemp()

    with open(tmp_absolute_path, 'w') as tmp_stream:
        with open(filepath, 'r') as stream:
            for line in stream:
                if key in line:
                    matched_key = True
                    tmp_stream.write(command + '\n')
                else:
                    tmp_stream.write(line)

        if not matched_key:
            tmp_stream.write(command + '\n')

    close(fh)
    move(tmp_absolute_path, filepath)


def enable_camera():
    """
    Enable raspi camera interface
    Identical to sudo raspi-config nonint do_camera 0
    """
    subprocess.run(["raspi-config", "nonint", "do_camera", "0"])


def enable_i2c():
    """
    """
    subprocess.run(["raspi-config", "nonint", "do_i2c", "0"])

    write_setting("dtparam=i2c_vc", "on")


def is_root():
    """
    returns True if script has root priviliges
    """
    return os.getuid() == 0


def main():

    if not is_root():
        print("Script requires root priviliges.")
        return 1

    enable_camera()
    enable_i2c()


if __name__ == "__main__":
    sys.exit(main())
