<?php

class security_wrapper {

    public $user;
    public $homedir;

    private $logindb;

    function __construct() {
        session_start();
        if ( file_exists("/docker/whp/sql/login.db") ){
            $this->logindb = new SQLite3('/docker/whp/sql/login.db');
        }else {
            $this->logindb = new SQLite3('/docker/whp/sql/login.db');
            $this->logindb->busyTimeout(6000);
            $this->logindb->exec('CREATE TABLE nonces(nonce STRING,user STRING,ip STRING,last_time String)');
        }
    }

    function pam_login($user,$password) {
        $error = '';
        $result = pam_auth( $user, $password, $error );
        if ( $result ) {
            $this->user = $user;
        }
        return $result;
    }

    function get_home_dir($user) {
        // Sanitize user input to prevent command injection
        $user = escapeshellarg($user);
        $homedir = trim(shell_exec("cat /etc/passwd |grep $user |awk -F ':' {'print \$6'}|head -1"));
        
        // If homedir is empty or not found, try to construct it based on username
        if (empty($homedir)) {
            // For root user, use /root
            if ($user === "'root'" || $user === "root") {
                $homedir = '/root';
            } else {
                // For regular users in WHP, use /docker/users/username pattern
                // Remove quotes from escapeshellarg for path construction
                $clean_user = trim($user, "'");
                $homedir = '/docker/users/' . $clean_user;
            }
            error_log("Warning: Could not find home directory for user $user in /etc/passwd, using fallback: $homedir");
        }
        
        $this->homedir = $homedir;
        return $homedir;
    }

    function check_nonce($nonce, $ip) {
        //check if $nonce is vaild
        $stmt = $this->logindb->prepare('SELECT user,ip,last_time FROM nonces WHERE nonce=:n');
        $stmt->bindValue(':n', $nonce,SQLITE3_TEXT);
        $result = $stmt->execute();
        if ( $result != FALSE ) {
            $row = $result->fetchArray(SQLITE3_ASSOC);
            if ( $row['ip'] == $ip ) {
                $time_diff = time() - $row['last_time'];
                if ( $time_diff > 900) {
                    return false;
                }else {
                    $dlte = $this->logindb->prepare('DELETE FROM nonces WHERE nonce=:n');
                    $dlte->bindValue(':n', $nonce,SQLITE3_TEXT);
                    $dlte->execute();
                    return $row;
                }
            }else {
                return false;
            }
        }else { 
            return false;
        }
    }

    function create_nonce($user,$ip, $salt) {
        //Create nounce using prepared statements to prevent SQL injection
        $last_time = time();
        $nonce = hash("sha1","$salt.$user.$ip.$last_time");
        $stmt = $this->logindb->prepare("INSERT INTO nonces (nonce, user, ip, last_time) VALUES (:nonce, :user, :ip, :last_time)");
        $stmt->bindValue(':nonce', $nonce, SQLITE3_TEXT);
        $stmt->bindValue(':user', $user, SQLITE3_TEXT);
        $stmt->bindValue(':ip', $ip, SQLITE3_TEXT);
        $stmt->bindValue(':last_time', $last_time, SQLITE3_INTEGER);
        $stmt->execute();
        return $nonce;
    }

    function __destruct() {
        $this->logindb->close();
    }

}

