#!/usr/bin/python3

import subprocess
import crypt
import glob
import os
import sys
import time
from pathlib import Path

robustelKeyFingerprint = "3072 SHA256:pukdlvQsdNu7r99Thpu/y8Y4QomQ0neLigruUM76UmU root@Router (RSA)"
adminUsername = "admin"
superAdminUsername = "eurogard"
#superAdminUsername = "testuser"
superAdminGroup = "sudo"
userGroup = "web_editor"

uciChanged = False

def user_in_group(username, groupname):
    try:
        subprocess.check_output(['id', '-nG', username])
        groups = subprocess.check_output(['id', '-nG', username]).decode().strip().split()
        return groupname in groups
    except subprocess.CalledProcessError:
        return False
    
def add_user_to_group(username, groupname):
    subprocess.call(['usermod', '-aG', groupname, username])

def user_exists(username):
    try:
        subprocess.check_output(['id', username])
        return True
    except subprocess.CalledProcessError:
        return False

def create_user(username):
    subprocess.call(['useradd', '-m', username, '-s', '/bin/bash'])
    
def remove_user_from_group(username, groupname):
    subprocess.call(['gpasswd', '-d', username, groupname])
    print(f"User '{username}' removed from group '{groupname}'")

def set_user_password_encrypted(username, password):
    subprocess.call(f"echo '{username}:{password}' | chpasswd -e", shell=True)
    print(f"Password set for user '{username}'")
   
def get_sudo_password():
    try:
        username = subprocess.check_output('uci get user_management.sudo_list[1].password', shell=True, text=True)
        return username.strip()
    except subprocess.CalledProcessError:
        return ""
    
def get_admin_password_uci():
    try:
        password = subprocess.check_output('uci get user_management.password', shell=True, text=True)
        return password.strip()
    except subprocess.CalledProcessError:
        return ""
    
def get_admin_password_shadow():
    try:
        password = subprocess.check_output('cat /etc/shadow | grep admin | cut -d: -f2', shell=True, text=True)
        return password.strip()
    except subprocess.CalledProcessError:
        return ""
    
def set_sudo_password(password):
    subprocess.call(f"uci set user_management.sudo_list[1].password '{password}'", shell=True)
    
def set_admin_password(password):
    subprocess.call(f"uci set user_management.password '{password}'", shell=True)
    
def get_sudo_username():
    try:
        username = subprocess.check_output('uci get user_management.sudo_list[1].name', shell=True, text=True)
        return username.strip()
    except subprocess.CalledProcessError:
        try:
            subprocess.call("uci add user_management.sudo_list 1", shell=True, text=True)
        except subprocess.CalledProcessError:
            return ""
        return ""
    
def set_sudo_username(username):
    subprocess.call(f'uci set user_management.sudo_list[1].name {username}', shell=True)
    
    
def get_default_password() -> str:
    try:
        password = subprocess.check_output('devcfg | grep pwd | cut -d= -f2', shell=True, text=True)
        return password.strip()
    except subprocess.CalledProcessError:
        return ""
    
def modify_string(input_string, key):
    modified_string = ""
    key_length = len(key)
    for i, char in enumerate(input_string):
        char_code = ord(char)
        key_char = key[i % key_length]
        key_code = ord(key_char)
        modified_code = (char_code + key_code) % 36  # Ensure result is within alphanumeric ASCII range
        modified_char = chr(modified_code + 48) if modified_code < 10 else chr(modified_code + 87)
        modified_string += modified_char if modified_char.isalnum() else 'a'  # Replace non-alphanumeric with 'a'
    return modified_string

def using_robustel_key() -> bool:
    try:
        return subprocess.check_output('ssh-keygen -lf /etc/ssh/ssh_host_rsa_key.pub', shell=True, text=True).strip() == robustelKeyFingerprint
    except subprocess.CalledProcessError:
        return False
    
def delete_default_sshd_keys():
    files = glob.glob("/etc/ssh/ssh_host_*")
    for f in files:
        os.remove(f)
        
def generate_sshd_keys():
    subprocess.call(f'ssh-keygen -A', shell=True)

def user_has_ssh_key() -> bool:
    return os.path.isfile("/home/eurogard/.ssh/id_rsa")

def generate_user_ssh_key():
    Path("/home/eurogard/.ssh").mkdir(parents=True, exist_ok=True)
    subprocess.call(f'ssh-keygen -t rsa -f /home/eurogard/.ssh/id_rsa -N ""', shell=True)


if len(sys.argv) > 1:
    print(f"Sleeping for {sys.argv[1]}s")
    time.sleep(int(sys.argv[1]))
    
if len(sys.argv) > 2:
    for i in range(10):
        if user_in_group(adminUsername, superAdminGroup):
            remove_user_from_group(adminUsername, superAdminGroup)
            sys.exit(0)
        else:
            time.sleep(0.2)
    sys.exit(0)


# Get factory password, modify it a bit and encrypt it
defaultPassword = get_default_password()
defaultCryptedPassword = crypt.crypt(defaultPassword)
modifiedPassword = modify_string(defaultPassword, "eurogard")
cryptedPassword = crypt.crypt(modifiedPassword)
    
# Check if user eurogard exists
if not user_exists(superAdminUsername):
    # Create user eurogard and add to sudo group if needed
    create_user(superAdminUsername)
    add_user_to_group(superAdminUsername, superAdminGroup)
    # Set password of eurogard user to some derivative of the default password
    print(f"New sudo user password: {modifiedPassword}")
    print(cryptedPassword)
    set_user_password_encrypted(superAdminUsername, cryptedPassword)
    set_user_password_encrypted("root", cryptedPassword)

# Add user to sudo group    
if not user_in_group(superAdminUsername, superAdminGroup):
    add_user_to_group(superAdminUsername, superAdminGroup)
    
# Set sudo user in uci
if get_sudo_username() != superAdminUsername:
    set_sudo_username(superAdminUsername)
    set_sudo_password(cryptedPassword)
    uciChanged = True
    
if uciChanged:
    subprocess.call("uci commit", shell=True)
    time.sleep(2)
    
# Remove admin user from group sudo and add to group web_editor if needed
if user_in_group(adminUsername, superAdminGroup):
    remove_user_from_group(adminUsername, superAdminGroup)
# Check if admin user is still member of group web_editor
if not user_in_group(adminUsername, userGroup):
    add_user_to_group(adminUsername, userGroup)
    
# Set admin password if not set already
if get_admin_password_uci() != get_admin_password_shadow():
    adminPassword = get_admin_password_uci() if get_admin_password_uci() != "" else defaultCryptedPassword
    set_user_password_encrypted("admin", adminPassword)
    #set_admin_password(defaultCryptedPassword)
    #uciChanged = True


# Check if default ssh cert is in use
if using_robustel_key():
    delete_default_sshd_keys()
    generate_sshd_keys()
    
# Check if user eurogard has a ssh key pair
if not user_has_ssh_key():
    generate_user_ssh_key()