#!/bin/sh
#
# filerotate: Rotates a file by adding an index to its name and moving
# the existing files to the next index.
#
# Ivan Vilata i Balaguer <ivan at selidor dot net>, 2000-2002.
#
# Do what you want with this, but acknowledgement is welcome.
# Of course there is NO WARRANTY of any kind.


progname=$(basename $0)

if [ "$1" = '--help' ]; then
    cat << EOF
Usage: $progname FILE BACKUPS
   or: $progname --help
Rotates a FILE by adding an index to its name and moving the existing files
to the next index.  The specified number of BACKUPS are kept.
EOF
    exit 0
fi

if [ $# -ne 2 ]; then
    echo "Usage: $progname FILE BACKUPS  or  $progname --help" > /dev/stderr
    exit 1
fi


FILE="$1"
BACKUPS=$2

last=$(($BACKUPS - 1))
if [ -e "$FILE.$last" ]; then
    rm -f "$FILE.$last"
fi

curr=$last
while [ $curr -gt 0 ]; do
    prev=$(($curr - 1))
    if [ -e "$FILE.$prev" ]; then
	mv "$FILE.$prev" "$FILE.$curr"
    fi
    curr=$prev
done

if [ -e "$FILE" ]; then
    mv "$FILE" "$FILE.0"
fi
