xref: /freebsd/usr.sbin/vigr/vigr.sh (revision 257e70f1d5ee61037c8c59b116538d3b6b1427a2)
1#!/bin/sh
2#-
3# Copyright (c) 2014 Dag-Erling Smørgrav
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions
8# are met:
9# 1. Redistributions of source code must retain the above copyright
10#    notice, this list of conditions and the following disclaimer.
11# 2. Redistributions in binary form must reproduce the above copyright
12#    notice, this list of conditions and the following disclaimer in the
13#    documentation and/or other materials provided with the distribution.
14#
15# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25# SUCH DAMAGE.
26#
27#
28
29error() {
30	echo "$@" >&2
31	exit 1
32}
33
34usage() {
35	error "usage: vigr [-d dir]"
36}
37
38# Check arguments
39while getopts d: opt ; do
40	case $opt in
41	d)
42		etcdir="${OPTARG}"
43		;;
44	*)
45		usage
46		;;
47	esac
48done
49
50# Look for the current group file
51grpfile="${etcdir:-/etc}/group"
52if [ ! -f "${grpfile}" ] ; then
53	error "Missing group file"
54fi
55
56# Create a secure temporary working directory
57tmpdir=$(mktemp -d -t vigr)
58if [ -z "${tmpdir}" -o ! -d "${tmpdir}" ] ; then
59	error "Unable to create the temporary directory"
60fi
61tmpfile="${tmpdir}/group"
62
63# Clean up on exit
64trap "exit 1" INT
65trap "rm -rf '${tmpdir}'" EXIT
66set -e
67
68# Make a copy of the group file for the user to edit
69cp "${grpfile}" "${tmpfile}"
70
71while :; do
72	# Let the user edit the file
73	${EDITOR:-/usr/bin/vi} "${tmpfile}"
74
75	# If the result is valid, install it and exit
76	if chkgrp -q "${tmpfile}" ; then
77		install -b -m 0644 -C -S "${tmpfile}" "${grpfile}"
78		exit 0
79	fi
80
81	# If it is not, offer to re-edit
82	while :; do
83		echo -n "Re-edit the group file? "
84		read ans
85		case $ans in
86		[Yy]|[Yy][Ee][Ss])
87			break
88			;;
89		[Nn]|[Nn][Oo])
90			exit 1
91			;;
92		esac
93	done
94done
95