#!/usr/bin/env python3
import os
import uuid
import subprocess

DESTDIR="/tmp/{}".format(str(uuid.uuid4()))
os.makedirs(DESTDIR, exist_ok=True)

subprocess.run([
    "/usr/bin/env",
    f"DESTDIR={DESTDIR}",
    "/usr/bin/pardus-mount-rootfs"], check=True)

pass1 = os.environ.get("pass1")
pass2 = os.environ.get("pass2")
while pass1 is None or pass2 is None or pass1 != pass2:
    pass1 = input("Enter new password:")
    pass2 = input("Confirm password:")

user = os.environ.get("user", None)

if user is None:
    # Get the username of the first non-root user
    with open(f"{DESTDIR}/etc/passwd", "r") as f:
        for line in f.read().split("\n"):
            uid = line.split(":")[3]
            if int(uid) >= 1000:
                user = line.split(":")[0]
                break

# Change the password of the user in the chroot environment
sp = subprocess.run(
    ["openssl", "passwd", "-6", pass1],
    stdout=subprocess.PIPE, check=True)
hash = sp.stdout.decode("utf-8").strip()

subprocess.run(["chroot", DESTDIR, "usermod", "-p", hash, user],
    check=True)

# Unmount the partition
subprocess.run(["umount", "-lf", DESTDIR], check=True)
os.rmdir(DESTDIR)
