#!/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 (UID >= 1000 and not 'nobody')
    passwd_path = f"{DESTDIR}/etc/passwd"
    if os.path.isfile(passwd_path):
        with open(passwd_path, "r") as f:
            for line in f.read().splitlines():
                parts = line.split(":")
                if len(parts) >= 3 and parts[2].isdigit():
                    uid = int(parts[2])
                    if uid >= 1000 and uid != 65534:
                        user = parts[0]
                        break

if not user:
    print("Error: No valid user found to reset password.")
    subprocess.run(["umount", "-lf", DESTDIR], check=False)
    if os.path.isdir(DESTDIR):
        try:
            os.rmdir(DESTDIR)
        except OSError:
            pass
    exit(1)

# 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)
if os.path.isdir(DESTDIR):
    try:
        os.rmdir(DESTDIR)
    except OSError:
        pass
