#!/bin/sh
# liner 0.3 - a small line editor for configuration files.
# Run: sh liner.sh [FILE]       Help: sh liner.sh --help
# Requires /bin/sh, awk, and ordinary Linux/OpenBSD base utilities.
# No compiler, curses, readline, Python, Bash, or another editor is used.
# A private temporary directory holds exact-byte undo snapshots.
# Writes are staged beside the destination. Symlinks and multiple hard
# links require saving to a new filename. No power-loss durability claim.

ln_help() {
    cat <<'HELP'
liner 0.3 - one file, typed commands, undo and redo
Usage: sh liner.sh [FILE]

show [FIRST [LAST]]  Show all lines, one line, or an inclusive range.
page [FIRST [LAST]]  Browse the same text in an optional scrolling pager.
change LINE         Show a line, then ask for its replacement.
insert LINE         Ask for one new line, inserted before LINE.
                    Use the line count plus one to append.
delete FIRST [LAST]  Delete one line or an inclusive range.
undo                Undo one change.
redo                Redo one change.
write [FILE]        Save; FILE is literal text, including spaces.
help                Show this help.
quit                Leave if saved.
quit!               Discard unsaved changes and leave.

At Text>, enter exactly one line; an empty line is valid text.
In page: Up/Down scroll one row; Page Up/Page Down scroll one screen.
Enter or Space goes forward one screen; q returns to commands immediately.
Hold a scrolling key to repeat. The pager stays open at either end.
Text that fits on one screen is printed without entering the pager.
show remains unpaused. Paging is skipped when input/output is redirected.
Do not add shell quotes around a filename in the write command.
Display escapes backslashes, tabs, control and non-ASCII bytes.
Text entered at Text> is literal: backslashes are not escape codes.

Unchanged text and its line endings are preserved.
Inserted lines use the first existing newline style (LF for new files).
Missing final newlines stay absent unless the final line becomes empty.
A blank final line needs a terminating newline to remain a line.
8 MiB file limit. NUL bytes in input files are refused.
Undo survives writes and lasts until you leave this process.
An unexpected exit keeps unsaved text in a private temporary directory.
New files are private (mode 600); existing permissions are copied.
Save-as does not overwrite an unrelated existing file.
HELP
}

case $# in
    0|1) ;;
    *) printf '%s\n' 'Usage: sh liner.sh [FILE]' >&2; exit 2 ;;
esac
case ${1-} in
    -h|--help) ln_help; exit 0 ;;
    --version) printf '%s\n' 'liner 0.3'; exit 0 ;;
esac

LC_ALL=C
export LC_ALL
IFS=' 	
'
set -f
umask 077
ln_work=
ln_stage=
ln_file=
ln_current=0
ln_last=0
ln_ready=no
ln_discard=no
ln_existing=no
ln_saved_meta=
ln_tty=
ln_key_pid=
ln_page_pid=
ln_page_input=no
ln_alt=no
ln_newline='
'
ln_cr=$(printf '\r')

ln_say() { printf '%s\n' "$*"; }
ln_error() { printf 'liner: %s\n' "$*" >&2; }
ln_dirty() { ! cmp -s "$ln_work/$ln_current" "$ln_work/saved"; }

ln_page_restore() {
    # Stop children before restoring cooked input or leaving the display.
    if [ -n "$ln_key_pid" ]; then
        kill "$ln_key_pid" 2>/dev/null
        wait "$ln_key_pid" 2>/dev/null
        ln_key_pid=
    fi
    if [ -n "$ln_page_pid" ]; then
        kill "$ln_page_pid" 2>/dev/null
        wait "$ln_page_pid" 2>/dev/null
        ln_page_pid=
    fi
    if [ "$ln_page_input" = yes ]; then exec 4<&-; ln_page_input=no; fi
    if [ -n "$ln_tty" ]; then stty "$ln_tty" 2>/dev/null; ln_tty=; fi
    if [ "$ln_alt" = yes ]; then printf '\033[?1049l'; ln_alt=no; fi
}

ln_cleanup() {
    ln_status=$?
    trap - 0 HUP INT QUIT TERM PIPE
    ln_page_restore
    if [ -n "$ln_stage" ]; then rm -f "$ln_stage"; fi
    if [ -n "$ln_work" ] && [ -d "$ln_work" ]; then
        if [ "$ln_ready" = yes ] && [ "$ln_discard" != yes ] && ln_dirty; then
            printf '\nUnsaved text kept at: %s/%s\n' "$ln_work" "$ln_current" >&2
            printf 'Undo snapshots are in the same private directory.\n' >&2
        else
            rm -rf "$ln_work"
        fi
    fi
    exit "$ln_status"
}
trap ln_cleanup 0
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 131' QUIT
trap 'exit 143' TERM
trap 'exit 141' PIPE

# Normalize the parent without interpreting the final name as shell code.
ln_path() {
    case $1 in
        ''|*"$ln_newline"*|*"$ln_cr"*) return 1 ;;
        /*) ln_path_input=$1 ;;
        *) ln_path_input=$(pwd -P)/$1 ;;
    esac
    ln_parent=${ln_path_input%/*}
    ln_base=${ln_path_input##*/}
    [ -n "$ln_base" ] || return 1
    ln_parent=$(CDPATH= cd -P "$ln_parent" 2>/dev/null && pwd -P) || return 1
    printf '%s/%s\n' "${ln_parent%/}" "$ln_base"
}

# Numeric ls fields work with both Linux and OpenBSD; names are not parsed.
ln_metadata() {
    ln_listing=$(ls -idn "$1" 2>/dev/null) || return 1
    printf '%s\n' "$ln_listing" | awk 'NR == 1 {print $1, $2, $3, $4, $5, $6; exit}'
}

ln_work=$(mktemp -d "${TMPDIR:-/tmp}/liner.XXXXXXXX") || exit 1
case $ln_work in /*) ;; *) ln_work=$(pwd -P)/$ln_work ;; esac
if [ $# -eq 1 ]; then
    ln_file=$(ln_path "$1") || { ln_error 'Cannot resolve filename or parent directory.'; exit 1; }
    if [ -e "$ln_file" ] || [ -L "$ln_file" ]; then
        [ -f "$ln_file" ] && [ -r "$ln_file" ] || { ln_error 'Input must be a readable regular file.'; exit 1; }
        ln_size=$(wc -c < "$ln_file") || exit 1
        [ "$ln_size" -le 8388608 ] || { ln_error 'File limit: 8 MiB.'; exit 1; }
        cp "$ln_file" "$ln_work/0" || exit 1
        ln_existing=yes
        ln_saved_meta=$(ln_metadata "$ln_file") || exit 1
    else
        : > "$ln_work/0" || exit 1
    fi
else
    : > "$ln_work/0" || exit 1
fi
chmod 600 "$ln_work/0" || exit 1
ln_size=$(wc -c < "$ln_work/0") || exit 1
[ "$ln_size" -le 8388608 ] || { ln_error 'File limit: 8 MiB.'; exit 1; }
tr -d '\000' < "$ln_work/0" > "$ln_work/checked" || exit 1
cmp -s "$ln_work/0" "$ln_work/checked" || { ln_error 'NUL byte or read error; input refused.'; exit 1; }
mv "$ln_work/checked" "$ln_work/saved" || exit 1
ln_ready=yes

# awk handles records; the last byte tells it whether the last record had LF.
# Replacement text travels in a file, never in awk -v or shell source code.
ln_engine() {
    ln_end_byte=$(tail -c 1 "$ln_work/$ln_current" | od -An -tu1)
    LINER_MODE=$1 LINER_OP=${2-} LINER_FIRST=${3-} LINER_LAST=${4-} \
    LINER_END_BYTE=$ln_end_byte LINER_INPUT=$ln_work/input \
    awk '
    function error(s) { print "liner: " s > "/dev/stderr"; exit 1 }
    function number(s) { return s ~ /^[0-9]+$/ && length(s) <= 10 }
    function shown(s,    i, c, v, result) {
        result = ""
        for (i = 1; i <= length(s); i++) {
            c = substr(s, i, 1); v = byte[c]
            if (c == "\\") result = result "\\\\"
            else if (c == "\t") result = result "\\t"
            else if (v < 32 || v > 126) result = result sprintf("\\x%02X", v)
            else result = result c
        }
        return result
    }
    { line[++n] = $0 }
    END {
        mode = ENVIRON["LINER_MODE"]; op = ENVIRON["LINER_OP"]
        first = ENVIRON["LINER_FIRST"]; last = ENVIRON["LINER_LAST"]
        ended = ENVIRON["LINER_END_BYTE"] + 0 == 10
        style = ""
        for (i = 1; i <= n; i++) {
            ending[i] = i < n || ended ? "\n" : ""
            if (ending[i] != "" && substr(line[i], length(line[i]), 1) == "\r") {
                line[i] = substr(line[i], 1, length(line[i]) - 1)
                ending[i] = "\r\n"
            }
            if (style == "" && ending[i] != "") style = ending[i]
        }
        if (style == "") style = "\n"
        if (mode == "count") { print n + 0; exit }
        if (mode == "show" && first == "") {
            if (!n) { print "(empty)"; exit }
            first = 1; last = n
        }
        if (last == "") last = first
        maximum = op == "insert" ? n + 1 : n
        if (!number(first) || !number(last) || first + 0 < 1 ||
            last + 0 < first + 0 || last + 0 > maximum)
            error("Line range must be between 1 and " maximum ".")
        first += 0; last += 0
        if (mode == "check") exit
        if (mode == "show") {
            for (i = 1; i <= 255; i++) byte[sprintf("%c", i)] = i
            for (i = first; i <= last; i++) print sprintf("%6d  %s", i, shown(line[i]))
            if (last == n && !ended) print "(last line has no final newline)"
            exit
        }
        if (op == "change" || op == "insert") {
            input = ENVIRON["LINER_INPUT"]
            if ((getline replacement < input) != 1) error("Cannot read new text.")
            if (close(input) != 0) error("Cannot close new text.")
        }
        if (op == "change") line[first] = replacement
        else if (op == "insert") {
            for (i = n; i >= first; i--) { line[i+1] = line[i]; ending[i+1] = ending[i] }
            line[first] = replacement; ending[first] = style
            if (first == n + 1 && n && !ended) {
                ending[n] = style
                ending[first] = length(replacement) ? "" : style
            }
            n++
        } else if (op == "delete") {
            old_n = n
            for (i = last + 1; i <= n; i++) {
                line[i-(last-first+1)] = line[i]; ending[i-(last-first+1)] = ending[i]
            }
            n -= last - first + 1
            if (last == old_n && n && !ended) ending[n] = ""
        } else error("Invalid operation.")
        if (n && ending[n] == "" && line[n] == "") ending[n] = style
        size = 0
        for (i = 1; i <= n; i++) size += length(line[i]) + length(ending[i])
        if (size > 8388608) error("File limit: 8 MiB.")
        for (i = 1; i <= n; i++) printf "%s%s", line[i], ending[i]
    }' "$ln_work/$ln_current"
}

ln_page_size() {
    set -- $(stty size 2>/dev/null)
    ln_rows=${1-}; ln_columns=${2-}
    case $ln_rows in ''|*[!0-9]*|?????*) ln_rows=24 ;; esac
    case $ln_columns in ''|*[!0-9]*|?????*) ln_columns=80 ;; esac
    ln_rows=${ln_rows#"${ln_rows%%[!0]*}"}
    ln_columns=${ln_columns#"${ln_columns%%[!0]*}"}
    [ "${ln_rows:-0}" -ge 1 ] && [ "$ln_rows" -le 1000 ] || ln_rows=24
    [ "${ln_columns:-0}" -ge 2 ] && [ "$ln_columns" -le 4096 ] || ln_columns=80
    ln_height=$((ln_rows > 2 ? ln_rows - 2 : 1))
    ln_width=$((ln_columns - 1))
}

ln_read_key() {
    # Exactly one byte: a continuous reader could steal the next command.
    # Waiting for a tracked child also lets TERM interrupt a blocked read.
    dd bs=1 count=1 <&4 > "$ln_work/key" 2>/dev/null &
    ln_key_pid=$!
    if wait "$ln_key_pid"; then ln_key_status=0; else ln_key_status=$?; fi
    ln_key_pid=
    [ "$ln_key_status" -eq 0 ] && [ -s "$ln_work/key" ] || return 1
    ln_key=
    IFS= read -r ln_key < "$ln_work/key" || :
}

ln_page() {
    if [ ! -t 0 ] || [ ! -t 1 ]; then ln_engine show '' "$1" "$2"; return; fi
    ln_engine show '' "$1" "$2" > "$ln_work/page-text" || return
    ln_page_size
    # A short result needs no screen takeover or immediate-key input.
    if awk -v h="$ln_height" -v w="$ln_width" '
        { rows += int((length($0) + w - 1) / w); if (rows > h) exit 1 }
    ' "$ln_work/page-text"; then cat "$ln_work/page-text"; return; fi
    rm -f "$ln_work/page-events"
    mkfifo "$ln_work/page-events" || { ln_error 'Cannot start pager.'; return; }
    ln_tty=$(stty -g) || { cat "$ln_work/page-text"; return; }
    exec 4<&0
    ln_page_input=yes
    if ! stty -echo -echonl -icanon -ixon min 1 time 0; then ln_page_restore; return; fi
    ln_alt=yes
    printf '\033[?1049h\033[H\033[J'
    # The renderer never reads the terminal. It keeps unpadded rows in memory,
    # so each held-key redraw costs only a screenful, even near the file end.
    LINER_PAGE_TEXT=$ln_work/page-text LINER_PAGE_EVENTS=$ln_work/page-events awk '
    function draw(height, next_width, move,    i, at, anchor, offset, last_top, hint) {
        if (width != next_width) {
            anchor = source[top]; offset = start[top]
            for (i in row) { delete row[i]; delete source[i]; delete start[i] }
            width = next_width; count = 0; top = 1
            for (i = 1; i <= n; i++) {
                for (at = 1; at <= length(text[i]); at += width) {
                    row[++count] = substr(text[i], at, width)
                    source[count] = i; start[count] = at
                    if (i == anchor && at <= offset) top = count
                }
            }
        }
        if (move == 2) top += height
        else if (move == -2) top -= height
        else top += move
        last_top = count - height + 1
        if (last_top < 1) last_top = 1
        if (top > last_top) top = last_top
        if (top < 1) top = 1
        printf "\033[H"
        for (i = top; i <= count && i < top + height; i++) printf "%s\033[K\r\n", row[i]
        hint = "Up/Down: row  PgUp/PgDn: screen  Enter/Space: next  q: return"
        if (length(hint) > width) hint = "Up/Down PgUp/PgDn q: return"
        if (length(hint) > width) hint = "q: return"
        printf "\033[J%s", substr(hint, 1, width)
        fflush()
    }
    BEGIN {
        file = ENVIRON["LINER_PAGE_TEXT"]; events = ENVIRON["LINER_PAGE_EVENTS"]
        while ((getline s < file) > 0) text[++n] = s
        close(file); top = 1
        # Closing each request also works with awks that buffer pipe input.
        while ((getline request < events) > 0) {
            close(events); split(request, part)
            draw(part[1], part[2], part[3])
            print "ok" > events; close(events)
        }
    }' < /dev/null &
    ln_page_pid=$!
    ln_move=0
    ln_escape=$(printf '\033')
    while :; do
        ln_page_size
        printf '%s %s %s\n' "$ln_height" "$ln_width" "$ln_move" > "$ln_work/page-events"
        # Acknowledge before the next request so a fast writer cannot reopen
        # the old pipe and lose an event while the renderer is closing it.
        IFS= read -r ln_ack < "$ln_work/page-events" || break
        ln_read_key || break
        ln_move=0
        case $ln_key in
            q) break ;;
            ''|' '|"$ln_cr") ln_move=2 ;;
            "$ln_escape")
                # A short timeout prevents a lone or partial Escape from hanging.
                stty min 0 time 1 || break
                ln_sequence=
                if ln_read_key; then
                    case $ln_key in
                        '['|O)
                            ln_sequence=$ln_key
                            ln_left=16
                            while [ "$ln_left" -gt 0 ] && ln_read_key; do
                                ln_sequence=$ln_sequence$ln_key
                                case $ln_key in [A-Za-z~]) break ;; esac
                                ln_left=$((ln_left - 1))
                            done ;;
                    esac
                fi
                stty min 1 time 0 || break
                case $ln_sequence in
                    '[A'|OA) ln_move=-1 ;;
                    '[B'|OB) ln_move=1 ;;
                    '[5~') ln_move=-2 ;;
                    '[6~') ln_move=2 ;;
                esac ;;
        esac
    done
    ln_page_restore
}

ln_commit_edit() {
    if cmp -s "$ln_work/candidate" "$ln_work/$ln_current"; then
        rm -f "$ln_work/candidate"; ln_say 'Unchanged.'; return
    fi
    ln_next=$((ln_current + 1))
    mv -f "$ln_work/candidate" "$ln_work/$ln_next" || { ln_error 'Cannot record change; buffer retained.'; return; }
    ln_remove=$((ln_next + 1))
    while [ "$ln_remove" -le "$ln_last" ]; do
        rm -f "$ln_work/$ln_remove"
        ln_remove=$((ln_remove + 1))
    done
    ln_current=$ln_next; ln_last=$ln_next
    ln_count=$(ln_engine count) || return
    ln_say "Changed. $ln_count lines."
}

ln_disk_matches() {
    [ -f "$1" ] && [ ! -L "$1" ] || return 1
    ln_now_meta=$(ln_metadata "$1") || return 1
    [ "$ln_now_meta" = "$ln_saved_meta" ] && cmp -s "$1" "$ln_work/saved"
}

ln_save() {
    ln_target=$(ln_path "$1") || { ln_error 'Cannot resolve destination or parent directory.'; return; }
    ln_present=no
    if [ -e "$ln_target" ] || [ -L "$ln_target" ]; then
        if [ "$ln_target" != "$ln_file" ] || [ "$ln_existing" != yes ]; then
            ln_error 'Destination exists. Choose a new filename.'; return
        fi
        if [ -L "$ln_target" ]; then
            ln_error 'Symbolic link: use write FILE for a new path.'; return
        fi
        ln_disk_matches "$ln_target" || { ln_error 'File changed on disk; use write FILE for a new path.'; return; }
        [ -w "$ln_target" ] || { ln_error 'File is not writable.'; return; }
        set -- $ln_now_meta
        [ "$3" -eq 1 ] || { ln_error 'Multiple hard links: use write FILE for a new path.'; return; }
        ln_present=yes
    elif [ "$ln_target" = "$ln_file" ] && [ "$ln_existing" = yes ]; then
        ln_error 'File was removed on disk; use write FILE for a new path.'; return
    fi
    cp "$ln_work/$ln_current" "$ln_work/saved.next" || { ln_error 'Cannot prepare saved-state record.'; return; }
    ln_save_dir=${ln_target%/*}
    ln_stage=$(mktemp "$ln_save_dir/.liner-save.XXXXXXXX") || { ln_error 'Cannot create save file.'; return; }
    if [ "$ln_present" = yes ] && ! cp -p "$ln_target" "$ln_stage"; then
        ln_error 'Cannot preserve file attributes; write cancelled.'
    elif ! cat "$ln_work/$ln_current" > "$ln_stage"; then
        ln_error 'Write failed; original and editing buffer retained.'
    elif ! cmp -s "$ln_work/$ln_current" "$ln_stage"; then
        ln_error 'Saved bytes could not be verified; write cancelled.'
    elif [ "$ln_present" = yes ] && ! ln_disk_matches "$ln_target"; then
        ln_error 'File changed during save; write cancelled.'
    else
        ln_written=no
        if [ "$ln_present" = yes ]; then
            if mv -f "$ln_stage" "$ln_target"; then ln_written=yes; fi
        elif ln "$ln_stage" "$ln_target"; then
            ln_written=yes
        fi
        if [ "$ln_written" = yes ] && [ -f "$ln_target" ] && [ ! -L "$ln_target" ] &&
            cmp -s "$ln_target" "$ln_work/$ln_current"; then
            rm -f "$ln_stage"; ln_stage=
            ln_file=$ln_target; ln_existing=yes
            mv -f "$ln_work/saved.next" "$ln_work/saved" || {
                ln_error 'Written, but saved-state update failed. Reopen before another write.'; return;
            }
            ln_saved_meta=$(ln_metadata "$ln_file") || {
                ln_error 'Written, but attributes could not be read. Reopen before another write.'; return;
            }
            ln_say 'Written.'; return
        fi
        ln_error 'Write failed; editing buffer retained.'
    fi
    rm -f "$ln_stage"; ln_stage=
    rm -f "$ln_work/saved.next"
}

ln_count=$(ln_engine count) || exit 1
ln_say "liner 0.3 | $ln_count lines | Type help for commands."
while :; do
    if [ -t 0 ]; then
        if ln_dirty; then printf 'liner*> '; else printf 'liner> '; fi
    fi
    IFS= read -r ln_line || {
        if ln_dirty; then ln_error 'Input ended with unsaved changes.'; exit 1; fi
        exit 0
    }
    ln_line=${ln_line#"${ln_line%%[! 	]*}"}
    ln_command=${ln_line%%[ 	]*}
    ln_args=${ln_line#"$ln_command"}
    ln_args=${ln_args#"${ln_args%%[! 	]*}"}
    case $ln_command in
        '') continue ;;
        show|page)
            set -- $ln_args
            if [ $# -gt 2 ]; then ln_error 'Usage: show/page [FIRST [LAST]]'
            elif [ "$ln_command" = page ]; then ln_page "${1-}" "${2-}"
            else ln_engine show '' "${1-}" "${2-}"
            fi ;;
        change|insert|delete)
            set -- $ln_args
            if [ $# -eq 0 ] || [ $# -gt 2 ] || { [ "$ln_command" != delete ] && [ $# -ne 1 ]; }; then
                ln_error 'Use change LINE, insert LINE, or delete FIRST [LAST].'; continue
            fi
            ln_first=$1; ln_final=${2-$1}
            ln_engine check "$ln_command" "$ln_first" "$ln_final" || continue
            if [ "$ln_command" != delete ]; then
                if [ "$ln_command" = change ]; then ln_engine show '' "$ln_first" "$ln_first"; fi
                if [ -t 0 ]; then printf 'Text> '; fi
                IFS= read -r ln_text || { ln_error 'Input ended; change cancelled.'; exit 1; }
                printf '%s\n' "$ln_text" > "$ln_work/input" || { ln_error 'Cannot store new text.'; continue; }
            fi
            if ln_engine edit "$ln_command" "$ln_first" "$ln_final" > "$ln_work/candidate"; then
                ln_commit_edit
            else
                rm -f "$ln_work/candidate"
            fi ;;
        write)
            if [ -n "$ln_args" ]; then ln_save "$ln_args"
            elif [ -n "$ln_file" ]; then ln_save "$ln_file"
            else ln_error 'Use write FILE to name this file.'
            fi ;;
        undo|redo|help|quit|quit!)
            if [ -n "$ln_args" ]; then ln_error 'This command takes no argument.'; continue; fi
            case $ln_command in
                undo)
                    if [ "$ln_current" -gt 0 ]; then ln_current=$((ln_current - 1)); ln_say 'Undone.'
                    else ln_say 'Nothing to undo.'; fi ;;
                redo)
                    if [ "$ln_current" -lt "$ln_last" ]; then ln_current=$((ln_current + 1)); ln_say 'Redone.'
                    else ln_say 'Nothing to redo.'; fi ;;
                help) ln_help ;;
                quit)
                    if ln_dirty; then ln_error 'Unsaved changes. Use write, or quit! to discard.'
                    else ln_discard=yes; exit 0; fi ;;
                quit!) ln_discard=yes; exit 0 ;;
            esac ;;
        *) ln_error 'Unknown command. Type help.' ;;
    esac
done
