#!/bin/sh

. /usr/share/dirsrv/data/DSSharedLib

libpath_add "/usr/lib64/dirsrv/"
libpath_add ""
libpath_add "/usr/lib64"
libpath_add ""

export LD_LIBRARY_PATH
SHLIB_PATH=$LD_LIBRARY_PATH
export SHLIB_PATH

usage()
{
    echo "Usage: db2bak [archivedir] [-Z serverID] [-q] [-V] [-v] [-h]"
    echo "Options:"
    echo "        archivedir   - Directory where the backup should be stored"
    echo "        -Z serverID  - Server instance identifier"
    echo "        -q           - Quiet mode - suppresses output"
    echo "        -V           - Verbose output"
    echo "        -v           - Display version"
    echo "        -h           - Display usage"  
}

if [ $# -gt 4 ]
then
    usage
    exit 1
fi
if [ "$#" -gt 0 ]
then
    if [[ $1 != -* ]]
    then
        bak_dir=$1
        shift
    fi
fi

while getopts "hqVd:Z:vi:a:SD" flag
do
    case $flag in
        h) usage
           exit 0;;
        q) args=$args" -q";;
        V) args=$args" -V";;
        v) args=$args" -v";;
        S) args=$args" -S";;
        D) args=$args" -D \"$OPTARG\"";;
        i) args=$args" -i \"$OPTARG\"";;
        a) $bakdir=$OPTARG;;
        d) args=$args" -d \"$OPTARG\"";;
        Z) servid=$OPTARG;;
        ?) usage
           exit 1;;
    esac
done

shift $(($OPTIND - 1))
if [ $1 ]
then
    echo "ERROR - Unknown option: $1"
    usage
    exit 1
fi

instance=$(get_slapd_instance "/etc/dirsrv" $servid)
if [ $? -eq 1 ]
then
    usage
    echo "You must supply a valid server instance identifier.  Use -Z to specify instance name"
    echo "Available instances: $instance"
    exit 1
fi

CONFIG_DIR="/etc/dirsrv/slapd-$instance"

if [ -z "$bak_dir" ]
then
    bak_dir=/var/lib/dirsrv/slapd-$instance/bak/$instance-`date +%Y_%m_%d_%H_%M_%S`
fi

echo "Back up directory: $bak_dir"
eval /usr/sbin/ns-slapd db2archive -D $CONFIG_DIR -a $bak_dir $args
