#include <security/pam_appl.h>
#include <security/pam_modules.h>
#include <security/pam_ext.h>

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pwd.h>

#include <sys/stat.h>

#include <syslog.h>

PAM_EXTERN int pam_sm_authenticate( pam_handle_t *pamh, int flags,int argc, const char **argv ) {
    (void)flags; (void)argc; (void)argv;
     struct passwd *pw;

    const char* user;
    pam_get_user(pamh,&user,NULL);
    pw = getpwnam(user);
    uid_t uid = pw->pw_uid;

    char dir_path[1024];
    sprintf(dir_path, "/run/etap/%d", uid);

    mkdir(dir_path, 0700);
    chown(dir_path, uid, 0);
    syslog (LOG_NOTICE, "dir %s", dir_path);

    // read auto user file
    FILE *userfile = fopen("/run/etap/user", "r");
    if(userfile == NULL) {
        return PAM_AUTH_ERR;
    }

    char autouser[128];
    size_t readed = fread(autouser, sizeof(char), 128, userfile);
    fclose(userfile);
    unlink("/run/etap/user");
    if(readed == 0) {
        return PAM_AUTH_ERR;
    }

    openlog ("etap", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1);
    syslog (LOG_NOTICE, "user %s:%s", autouser, user);


    if(strncmp(user,autouser, strlen(user))==0){
        syslog (LOG_NOTICE, "success %s:%s", autouser, user);
        closelog ();
        return PAM_SUCCESS;
    }
    syslog (LOG_NOTICE, "error %s:%s", autouser, user);
    closelog ();
    return PAM_AUTH_ERR;
}

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