#!/bin/sh

# Prepares pools using BerkeleyDB for meta data for upgrade from dCache 2.5 to 2.6. Run this script
# if pools fail to start with a com.sleepycat.je.EnvironmentFailureException error after upgrade.


getCanonicalPath() # $1 = path                              
{                                                           
local link                                              
link="$1"                                               
if readlink -f . > /dev/null 2>&1; then                 
RET="$(readlink -f $link)"                          
else                                                    
RET="$(cd $(dirname $link); pwd)/$(basename $link)" 
while [ -h "$RET" ]; do                             
link="$(ls -ld $RET | sed 's/.*-> //')"         
if [ -z "${link##/*}" ]; then                   
RET="${link}"                               
else                                            
link="$(dirname $RET)/${link}"              
RET="$(cd $(dirname $link); pwd)/$(basename $link)" 
fi                                              
done                                                
fi                                                      
}                                                           

[ -f /etc/default/dcache ] && . /etc/default/dcache         
[ -f /etc/dcache.env ] && . /etc/dcache.env                 

if [ -z "$DCACHE_HOME" ]; then                              
getCanonicalPath "$0"                                     
DCACHE_HOME="${RET%/*/*}"                                 
fi                                                          
if [ ! -d "$DCACHE_HOME" ]; then                            
echo "$DCACHE_HOME is not a directory"                    
exit 2                                                    
fi                                                          

DCACHE_CLASSPATH=${DCACHE_HOME}/share/classes/*             
DCACHE_DEFAULTS=${DCACHE_HOME}/share/defaults               
DCACHE_CACHED_CONFIG=${DCACHE_HOME}/var/config/cache        
. ${DCACHE_HOME}/share/lib/loadConfig.sh

for domain in $(getProperty dcache.domains); do
    for cell in $(getProperty domain.cells "$domain"); do
        service=$(getProperty domain.service "$domain" "$cell")
        if [ "$service" = "pool" -a $(getProperty metaDataRepository "$domain" "$cell") = "org.dcache.pool.repository.meta.db.BerkeleyDBMetaDataRepository" ]; then
            path=$(getProperty path "$domain" "$cell")
            echo "Preparing $path for upgrade"
            quickJava -jar $(getProperty dcache.paths.share)/misc/je-4.1.21.jar DbPreUpgrade_4_1 -h "$path/meta"
        fi
    done
done
