#!/usr/bin/python3

import bcrypt
import subprocess
import sys

file_path = "/docker/data/settings.js"
salt_rounds = 8

# Read in password
password = subprocess.check_output("cat /var/config/eurogard_nodered | grep '^password =' | awk -F' = ' '{print $2}'", shell=True, text=True).strip()
if password is None or password == "":
    sys.exit(1)

hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(salt_rounds))

print(hashed_password.decode('utf-8'))

escaped_password = hashed_password.decode('utf-8').replace('\\', '\\\\').replace('/', '\\/').replace('&', '\\&')

sed_command = f"sed -i '/username: \"admin\"/,/permissions:/s/password: \"[^\"]*\"/password: \"{escaped_password}\"/' {file_path}"

result = subprocess.run(sed_command, shell=True, capture_output=True, text=True)

if result.returncode != 0:
    print("Error running sed command:", result.stderr)
    sys.exit(1)
else:
    print("Password updated successfully.")

subprocess.call("uci set eurogard_nodered.password ''" , shell=True)
subprocess.call("docker stop nodered" , shell=True)
subprocess.call("systemctl restart docker" , shell=True)
subprocess.call("docker start nodered" , shell=True)