1/*
2 * Copyright (c) 2008 Apple Computer, Inc.  All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * The contents of this file constitute Original Code as defined in and
7 * are subject to the Apple Public Source License Version 1.1 (the
8 * "License").  You may not use this file except in compliance with the
9 * License.  Please obtain a copy of the License at
10 * http://www.apple.com/publicsource and read it before using this file.
11 *
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
17 * License for the specific language governing rights and limitations
18 * under the License.
19 *
20 * @APPLE_LICENSE_HEADER_END@
21 */
22
23#include <stdbool.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27#include <curses.h>
28#include <pwd.h>
29#include "userinput_user.h"
30#include "preferences.h"
31
32static void user_completion(void *tinst, struct user_input_state *s) {
33    struct passwd *pwd;
34
35    if(!strlen(s->buf)) {
36	/* The user entered an empty string, so they don't want a user. */
37	top_prefs_set_user(s->buf);
38	user_input_set_state(NULL);
39	return;
40    }
41
42    pwd = getpwnam(s->buf);
43
44    if(NULL == pwd) {
45     	user_input_set_error_state("invalid user");
46	endpwent();
47	return;
48    }
49
50    top_prefs_set_user(s->buf);
51    top_prefs_set_user_uid(pwd->pw_uid);
52
53    endpwent();
54
55    user_input_set_state(NULL);
56}
57
58static void user_draw(void *tinst, struct user_input_state *s, WINDOW *win,
59		      int row, int column) {
60    const char *curuser = top_prefs_get_user();
61
62    char display[60];
63
64    if(-1 == snprintf(display, sizeof(display), "user [%s]: %s\n",
65		      curuser ? curuser : "", s->buf))
66        return;
67
68    mvwaddstr(win, row, column, display);
69}
70
71struct user_input_state top_user_input_user_state = {
72    .offset = 0,
73    .completion = user_completion,
74    .draw = user_draw
75};
76