summaryrefslogtreecommitdiff
path: root/doasedit
blob: f2deae07890e9f686c6055a96fefcd264b5a83c0 (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
#!/bin/sh
# Copy an existing text file to a temporary location, then edit the file.
# Attempt to then transfer the temporary file back to the original location if
# the temprary file has been altered. Conclude with a little clean-up. Try to
# avoid deleting any changes.

if [ $# -lt 1 ]
then
   echo "usage: $0 text-file"
   exit 1
fi

if [ ! -f "$1" ]
then
   echo "File does not exist or is a special file/link."
   exit 2
fi

if [ -L "$1" ]
then
   echo "File is a symbolic link. Refusing to edit."
   exit 2
fi

if [ ! -r "$1" ]
then
   echo "This user is unable to read the specified file."
   exit 3
fi

temp_file=$(mktemp --tmpdir doasedit.XXXXXXXX)
if [ ! $? ]
then
   echo "Could not create temporary file."
   exit 4
fi

cp "$1" "$temp_file"
if [ ! $? ]
then
   echo "Unable to copy file $1"
   exit 5
fi

# Attempt to run editor on the file
${EDITOR:-ed} "$temp_file"
if [ ! $? ]
then
   echo "Could not run editor $EDITOR"
   echo "Please make sure the EDITOR variable is set."
   rm -f "$temp_file"
   exit 6
fi

# Check to see if the file has been changed.
cmp -s "$1" "$temp_file"
status=$?
if [ $status -eq 0 ]
then
   echo "File unchanged. Not writing back to original location."
   rm -f "$temp_file"
   exit 0
fi

# At this point the file has been changed. Make sure it still exists.
if [ -f "$temp_file" ]
then
    doas cp "$temp_file" "$1"
    cmp -s "$temp_file" "$1"
    status=$?
    # If file fails to copy, do not do clean-up
    while [ $status -ne 0 ]
    do
       echo "Copying file back to $1 failed. Press Ctrl-C to abort or Enter to try again."
       read abc
       doas cp "$temp_file" "$1"
       cmp -s "$temp_file" "$1"
       status=$?
    done
fi

# Clean up
rm -f "$temp_file"
exit 0