1/*	$NetBSD: ex_mkexrc.c,v 1.1.1.2 2008/05/18 14:31:16 aymeric Exp $ */
2
3/*-
4 * Copyright (c) 1992, 1993, 1994
5 *	The Regents of the University of California.  All rights reserved.
6 * Copyright (c) 1992, 1993, 1994, 1995, 1996
7 *	Keith Bostic.  All rights reserved.
8 *
9 * See the LICENSE file for redistribution information.
10 */
11
12#include "config.h"
13
14#ifndef lint
15static const char sccsid[] = "Id: ex_mkexrc.c,v 10.13 2001/06/25 15:19:17 skimo Exp (Berkeley) Date: 2001/06/25 15:19:17";
16#endif /* not lint */
17
18#include <sys/types.h>
19#include <sys/queue.h>
20#include <sys/stat.h>
21
22#include <bitstring.h>
23#include <errno.h>
24#include <fcntl.h>
25#include <limits.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29#include <unistd.h>
30
31#include "../common/common.h"
32#include "pathnames.h"
33
34/*
35 * ex_mkexrc -- :mkexrc[!] [file]
36 *
37 * Create (or overwrite) a .exrc file with the current info.
38 *
39 * PUBLIC: int ex_mkexrc __P((SCR *, EXCMD *));
40 */
41int
42ex_mkexrc(SCR *sp, EXCMD *cmdp)
43{
44	struct stat sb;
45	FILE *fp;
46	int fd, sverrno;
47	const char *fname;
48	size_t flen;
49
50	switch (cmdp->argc) {
51	case 0:
52		fname = _PATH_EXRC;
53		INT2CHAR(sp, cmdp->argv[0]->bp, cmdp->argv[0]->len + 1,
54			    fname, flen);
55		set_alt_name(sp, fname);
56		break;
57	default:
58		abort();
59	}
60
61	if (!FL_ISSET(cmdp->iflags, E_C_FORCE) && !stat(fname, &sb)) {
62		msgq_str(sp, M_ERR, fname,
63		    "137|%s exists, not written; use ! to override");
64		return (1);
65	}
66
67	/* Create with max permissions of rw-r--r--. */
68	if ((fd = open(fname, O_CREAT | O_TRUNC | O_WRONLY,
69	    S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) {
70		msgq_str(sp, M_SYSERR, fname, "%s");
71		return (1);
72	}
73
74	if ((fp = fdopen(fd, "w")) == NULL) {
75		sverrno = errno;
76		(void)close(fd);
77		goto e2;
78	}
79
80	if (seq_save(sp, fp, "abbreviate ", SEQ_ABBREV) || ferror(fp))
81		goto e1;
82	if (seq_save(sp, fp, "map ", SEQ_COMMAND) || ferror(fp))
83		goto e1;
84	if (seq_save(sp, fp, "map! ", SEQ_INPUT) || ferror(fp))
85		goto e1;
86	if (opts_save(sp, fp) || ferror(fp))
87		goto e1;
88	if (fclose(fp)) {
89		sverrno = errno;
90		goto e2;
91	}
92
93	msgq_str(sp, M_INFO, fname, "138|New exrc file: %s");
94	return (0);
95
96e1:	sverrno = errno;
97	(void)fclose(fp);
98e2:	errno = sverrno;
99	msgq_str(sp, M_SYSERR, fname, "%s");
100	return (1);
101}
102