#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#   SPDX-FileCopyrightText: 2026 Arjen Balfoort <solydxk.abalfoort@tuta.com>
#   SPDX-License-Identifier: GPL-3.0-or-later
#

import os
import subprocess
import libcalamares

def shell_exec(command):
    """Execute command in shell"""
    libcalamares.utils.debug(f"Executing: {command}")
    try:
        return subprocess.check_call(command, shell=True)
    except subprocess.CalledProcessError as exc:
        libcalamares.utils.debug(str(exc))
        return exc.returncode

def run():
    """ Fix permission on user home directory """
    user = libcalamares.globalstorage.value("username")
    root = libcalamares.globalstorage.value("rootMountPoint")
    user_path = os.path.join(root, "home", user)

    if not os.path.isdir(user_path):
        libcalamares.utils.error(f"User path not found: {user_path}")
        return None

    # Remove all ACLs
    shell_exec(f"setfacl -b '{user_path}'")

    # Set permission (default = 700)
    user_permission = libcalamares.job.configuration.get("userPermission", "700")
    rc = shell_exec(f"chmod {user_permission} '{user_path}'")
    if rc != 0:
        libcalamares.utils.error(f"Unable to set permission {user_permission} on {user_path}")

    libcalamares.utils.debug(f"Permissions fixed for {user_path}")
    return None
