summaryrefslogtreecommitdiff
path: root/setup-user.in
blob: 789ff84b6b18f5d2df83204dc6b967893e176ace (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#!/bin/sh

PREFIX=@PREFIX@
: ${LIBDIR=$PREFIX/lib}
. "$LIBDIR/libalpine.sh"

usage() {
	cat <<-__EOF__
		usage: setup-user [-h] [-f FULLNAME] [-g GROUPS] [-k SSHKEY] [USERNAME]

		Create user account

		options:
		 -h  Show this help
		 -f  Set full name for user
		 -g  Comma or space separated list of groups to add user to
		 -k  ssh key or URL to ssh key (eg. https://gitlab.alpinelinux.org/user.keys)
		     or 'none' for no key

		If USERNAME is not specified user will be prompted.
	__EOF__
	exit $1
}

while getopts "f:g:hk:" opt; do
	case $opt in
		h) usage 0;;
		f) fullname="$OPTARG";;
		g) groups="$OPTARG";;
		k) keysopt="$OPTARG";;
		'?') usage "1" >&2;;
	esac
done
shift $(($OPTIND - 1))

if [ $# -gt 1 ]; then
	usage "1" >&2
elif [ $# -eq 1 ]; then
	username="$1"
	nopassword="-D"
else
	interactive=1
fi

if [ -n "$interactive" ] && [ -z "$fullname" ]; then
	ask "Enter full name for user account (or 'skip')"
	case "$resp" in
		skip) exit 0;;
		*) fullname="$resp";;
	esac
fi

if [ -n "$interactive" ] && [ -z "$username" ]; then
	while true; do
		ask "Enter username for $fullname:"
		username="$resp"
		if [ -n "$fullname" ]; then
			$MOCK adduser -g "$fullname" $nopassword "$username" && break
		else
			$MOCK adduser $nopassword "$username" && break
		fi
	done
else
	if [ -n "$fullname" ]; then
		$MOCK adduser -g "$fullname" $nopassword "$username"
	else
		$MOCK adduser $nopassword "$username"
	fi
fi

if [ -n "$interactive" ] && [ -z "$keysopt" ]; then
	while true; do
		ask "Enter ssh key or URL for $username (or 'none')"
		case "$resp" in
			none) break;;
			https://*|http://*) sshkeys=$(wget -q -O- $resp | grep ^ssh-);;
			*) sshkeys="$resp";;
		esac
		if echo "$sshkeys" | grep -q ^ssh-; then
			break
		fi
		echo "Did not find any key in '$resp'"
	done
else
	case "$keysopt" in
		https://*|http://*)
			sshkeys=$(wget -q -O- "$sshkeys" | grep ^ssh-);;
		none)
			sshkeys="" ;;
		*)
			sshkeys="$keysopt";;
	esac
	if [ -n "$sshkeys" ] && ! echo "$sshkeys" | grep -q ^ssh-; then
		echo "Could not find any keys in '$resp'" >&2
		exit 1
	fi
fi

if [ -n "$sshkeys" ] && [ "$sshkeys" != "none" ]; then
	mkdir -p "$ROOT"/home/$username/.ssh
	echo "$sshkeys" > "$ROOT"/home/$username/.ssh/authorized_keys
fi

if [ -n "$groups" ] && [ "$groups" != "none" ]; then
	for i in $(echo $groups | tr ',' ' '); do
		$MOCK addgroup "$username" "$i" || exit
	done
fi