Tuesday, December 7, 2010

syncscripts

Here's my script to manage systemwide scripts. The scripts and their destination files are held in the syncscripts.lst file. Scripts can be added. The script has be run from the folder where are all of the other scripts are developed. It checks the if the destination file exists, and copies it if it doesn't. If it does exist, it compares the md5sum of script with that of the destination file; if they differ, it copies the script to the destination file. The remove function has not yet been written.

#!/bin/bash

# pre-defined script variables
silent=1
verbose=1
addscript=1
remscript=1
scriptlist=syncscripts.lst

# display script usage
disphelp() {
    echo "Usage: $(basename $0) [OPTION] [SCRIPT]"
    echo
    echo "OPTIONS:"
    echo " -s          silent"
    echo " -v          verbose"
    echo " -a SCRIPT      add script"
    echo " -r SCRIPT      remove script"
    echo " -h         display this message"
}

###########################################################
args=`getopt svar $*`

set -- $args
for i; do
    case "$1" in
        -s) silent=0        ; shift    ;;
        -v) verbose=0     ; shift ;;
        -a) addscript=0 ; shift ;;
        -r) remscript=0 ; shift ;;
        -h) disphelp        ; exit 0 ;;
        --) shift                ; break ;;
    esac
done

# check for existence of syncscripts.lst, create an empty one if
#+one does not already exist
if [[ ! -f $scriptlist ]]; then
    [[ $silent = 1 ]] && echo "syncscripts.lst not found, creating a blank file"
    touch $scriptlist
fi

# add script to scriptlist
if [[ $addscript = 0 ]]; then
    # check to make sure script exists, the add script and destination
    #+to file.
    if [[ -f $1 ]]; then
        [[ $silent = 1 ]] && echo "$1 $2" >> $scriptlist
        exit 0
    fi
    [[ $silent = 1 ]] && echo "failed to add $1, no such file"
    exit 1
fi

# remove script from scriptlist
if [[ $remscript = 0 ]]; then
    [[ $silent = 1 ]] && echo "the remove function has not yet been written, nothing was removed"
    exit 0
fi

# step through lines of syncscripts.lst, every two lines contain an
#+entry the first line is the script, the second the path to move it to
while read line; do
    script=`echo $line | awk '{print $1}'`
    dest=`echo $line | awk '{print $2}'`

    # if destination path does not exist, copy without checking md5sums
    if [[ -z $dest ]]; then
        [[ $silent = 1 ]] && echo "$dest does not exist, copying $script to $dest"
        cp $script $dest
        continue
    fi
    # get the md5sum of the script and its destination, if no
    #+changes have been made, it doesn't need to be copied.
    scriptsum=`md5sum $script | awk '{print $1}'`
    destsum=`md5sum $dest | awk '{print $1}'`
    if [[ $scriptsum != $destsum ]]; then
        [[ $silent = 1 ]] && echo "detected changes in $script, copying to $dest"
        cp $script $dest
    fi
done <$scriptlist


exit 0

No comments:

Post a Comment