#!/bin/bash
# Copyright (C) 2004 Networks Associates Technology Inc. All rights reserved.
# from environment (supplied by av-update):
#  datver - currently installed DAT version

shopt -s extglob	# fancy globbing
shopt -s dotglob	# globbing * includes .*
dat_dir=${1}

dat_base="${dat_dir%/*}/dat.d"
dat_dnew="$dat_base/${2}"

while [[ -d $dat_dnew ]]; do dat_dnew="$dat_dnew_"; done

# make new dat directory and install new files in it
mkdir -p "$dat_dnew" && mv -f dat/* $dat_dnew || 
{
    rm -rf "$dat_dnew"
    exit 1
}

# ensure current dat directory is reached by soft link
if [[ ! -L "$dat_dir" && -d "$dat_dir" ]]; then
	# looks like we've got the original RPM directory in place
	dat_save="$dat_dir.orig"
	if [[ -d "$dat_save" ]]; then
	    # we've already got the original saved
	    dat_save="$dat_base/V$datver.${2#*.}"
	fi
	# rename and soft link current dat directory
	mv -f "$dat_dir" "$dat_save" &&
	    ln -s "${dat_save#"${dat_dir%/*}/"}" "$dat_dir"
fi

# make new soft link
ln -s "${dat_dnew#"${dat_dir%/*}/"}" "$dat_dir.$$"
# make sure new and current files won't be deleted in a hurry
find "$dat_dir/." "$dat_dir.$$/." -exec touch -a -c {} \; 2>/dev/null

# Delete the old backup directories
if [ -d "$dat_dir" ]; then
    # loop through the directories found in dat.d
    for d in $dat_base/*; do
	# if the current directory matches the dat link then
	# ignore it (we need this one)
	[[ $d -ef $dat_dir ]] && continue
	[[ $d -ef $dat_dir.$$ ]] && continue
	# otherwise, kill any processes currently using the files we
	# are about to blow away
	/sbin/fuser -k $d/*
	# and remove the directory
	rm -rf $d
    done
fi

# now at last we rename the link that installs the new dats
[[ ! -d "$dat_dir" ]] || rm -rf "$dat_dir" && mv -f "$dat_dir.$$" "$dat_dir"
