#!/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 read_debian_version():
    with open("/etc/debian_version") as f:
        DEBIAN_VERSION = f.readline().strip()
    major_version = DEBIAN_VERSION.split(".")[0]
    return int(major_version)


def enable_camera_buster():
    """
    Enable raspi camera interface

    Identical to sudo raspi-config nonint do_camera 0
    """
    subprocess.run(["raspi-config", "nonint", "do_legacy", "0"])

def enable_camera_bullseye():
    """
    Enable raspi camera interface

    Identical to sudo raspi-config nonint do_legacy 0
    """
    subprocess.run(["raspi-config", "nonint", "do_legacy", "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

    if read_debian_version() > 10:
        enable_camera_bullseye()
    else:
        enable_camera_buster()

    enable_i2c()

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