#! /bin/sh
# #############################################################################

       NAME_="insertext"
       HTML_="put text into file"
    PURPOSE_="insert text file into another file at line n"
   SYNOPSIS_="$NAME_ [-hl] <n> <text_file_to_insert> <file> [<file>..]"
   REQUIRES_="standard GNU commands"
    VERSION_="1.1"
       DATE_="2001-06-23; last update: 2005-03-30"
     AUTHOR_="Dawid Michalczyk <dm@eonworks.com>"
        URL_="www.comp.eonworks.com"
   CATEGORY_="text"
   PLATFORM_="Linux"
      SHELL_="bash"
 DISTRIBUTE_="yes"

# #############################################################################
# This program is distributed under the terms of the GNU General Public License

usage() {

echo >&2 "$NAME_ $VERSION_ - $PURPOSE_
Usage: $SYNOPSIS_
Requires: $REQUIRES_
Options:
     <n>, an integer referring to line number at which to insert the text file
     <text_file_to_insert>, the text file to insert
     <file>, the text file to insert into
     -h, usage and options (this help)
     -l, see this script"
    exit 1
}

# tmp files setup
tmp_1=/tmp/tmp.${RANDOM}$$
tmp_2=/tmp/tmp.${RANDOM}$$

# signal trapping and tmp file removal
trap 'rm -f $tmp_1 $tmp_2 >/dev/null 2>&1' 0
trap "exit 1" 1 2 3 15

# enabling extended globbing
shopt -s extglob

# option handling
case "$1" in
    -h) usage ;;
    -l) more $0; exit 1 ;;
    +([0-9])) # arg1 must be an integer

        n=$1
        [[ $# < 3 ]] && { echo >&2 missing argument; exit 1; }
        [ -e $2 ] || { echo >&2 file $2 does not exist; exit 1; }
        insert=$2
        shift 2

        for a in $@; do

            if [ -f $a ]; then

            # in case we want to insert at line 1
            if [[ $n == 1 ]];then

                touch $tmp_1
                sed -n ''$n',$p' $a > $tmp_2
                cat $tmp_1 $insert $tmp_2 > $a
                continue

            fi

            ((n--)) # back up one line
            sed -n '1,'$n'p' $a > $tmp_1
            ((n++)) # back to original n
            sed -n ''$n',$p' $a > $tmp_2
            cat $tmp_1 $insert $tmp_2 > $a

        else

            echo $a does not exist or is not a file

        fi

    done ;;


    *) echo invalid argument, type $NAME_ -h for help; exit 1 ;;

esac
