#include <security/pam_appl.h>
#include <security/pam_modules.h>
#include <security/pam_ext.h>
#include <sys/stat.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>

PAM_EXTERN int pam_sm_close_session(pam_handle_t *pamh, int flags, int argc, const char **argv) {
    return PAM_SUCCESS;
}
PAM_EXTERN int pam_sm_open_session(pam_handle_t *pamh, int flags, int argc, const char **argv) {
    return PAM_SUCCESS;
}

PAM_EXTERN int pam_sm_authenticate( pam_handle_t *pamh, int flags,int argc, const char **argv ) {
    const char* user;
    pam_get_user(pamh,&user,NULL);
    if(strcmp(user,"root")!=0){
        setlogmask (LOG_UPTO (LOG_NOTICE));
        openlog ("etap", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1);
        syslog (LOG_NOTICE, "WINE :%s", user);
        char cmd[1024];
        sprintf(cmd, "chown -R '%s:%s' /var/lib/wine-prefix 2>/dev/null &", user, user);
        uid_t u = setuid(0);
        system(cmd);
        setuid(u);
        closelog ();
    }
    if(strcmp(user,"ogrenci")==0){
        return PAM_SUCCESS;
    }
    return PAM_AUTH_ERR;
}

PAM_EXTERN int pam_sm_setcred( pam_handle_t *pamh, int flags,int argc, const char **argv ) {
    return PAM_SUCCESS;
}
