#!/bin/sh

# File: refdb-init - performs post-install setup of RefDB
# Markus Hoenicka <mhoenicka@users.sourceforge.net> 2006-06-01

# refdb programs which get called
MYREFDBCTL=<prefix>/bin/<program_prefix>refdbctl<program_suffix>
MYREFDBD=<prefix>/bin/<program_prefix>refdbd<program_suffix>
MYREFDBA=<prefix>/bin/<program_prefix>refdba<program_suffix>

# User asked to confirm action
#   params: nil
#   return: user choice [y/n]
confirm () {
	while [ 1 ] ; do
		read confirm_input
		[ `echo ${confirm_input} | grep "y\|Y\|n\|N"` ] && break
		printf "\a"
	done
	[ "${confirm_input}" = "Y" ] && confirm_input="y"
	[ "${confirm_input}" = "N" ] && confirm_input="n"
	echo ${confirm_input}
}

# Report status and exit
#   params: message "succeeded"|"failed"
#   return: nil
endScript () {
	echo ; echo "$1"
	echo ; echo "refdbd-init.sh $2."
	echo "`basename $0` is finished."
	if [ "$2" = "succeeded" ] ; then
		exit 0
	else
		exit 1
	fi
}

# check whether a file is present and readable or writable
#   params: path "read|write|execute"
#   return: true if present and read/write/executable, false if not
checkFile () {
    if [ "$2" = "read" ]; then
	ls -al $1 2> /dev/null | grep -E "^.r........" > /dev/null
    elif [ "$2" = "write" ]; then
	ls -al $1 2> /dev/null | grep -E "^..w......." > /dev/null
    else
	ls -al $1 2> /dev/null | grep -E "^...x......" > /dev/null
    fi
}

# check whether the RefDB daemon is up and running
#   params: none
#   returns: true if refdbd runs, false if not
checkRefdbd () {
    ps ax|grep -E "[r]efdbd |refdbd$"
}

# find out how to connect to the database engine
#   params: engine
#   return: nil
readHostInfo () {
# ask for the hostname
    echo ""
    echo "==="
    echo "You may need to specify a hostname and a port to connect to your"
    echo "database engine, e.g. if the server runs on a remote box or if"
    echo "you cannot connect through a local socket. These are the same"
    echo "settings that you would use to connect with your database client."
    echo "Enter the hostname of the database server or its IP address."
    echo "If you do not need to use an explicit hostname or IP address,"
    echo "just press [RETURN]."

    read dbserver_hostname

    if [ ! "$dbserver_hostname" ]; then
	refdbdrc_hostname="localhost"
    else
	dbserver_hostname_switch=" -h $dbserver_hostname "
	refdbd_hostname_switch=" -i $dbserver_hostname "
	refdbdrc_hostname="$dbserver_hostname"
    fi

# ask for the port
    echo ""
    echo "==="
    echo "Specify the port on which the database engine listens. To use the"
    echo "builtin defaults, just press [RETURN]."

    read dbserver_port
	
    if [ ! "$dbserver_port" ]; then
	if [ "$1" = "mysql" ]; then
	    refdbdrc_port="3306"
	elif [ "$1" = "pgsql" ]; then
	    refdbdrc_port="5432"
	else
	    refdbdrc_port="0"
	fi
    else
	if [ "$1" = "mysql" ]; then
	    dbserver_port_switch=" -P $dbserver_port "
	elif [ "$1" = "pgsql" ]; then
	    dbserver_port_switch=" -p $dbserver_port "
	fi
	refdbd_port_switch=" -b $dbserver_port "
	refdbdrc_port="$dbserver_port"
    fi

}

### main ###
echo ""
echo ""
echo "This script will help you to set up a fresh RefDB installation."
echo ""
echo "WARNING: It is not yet designed to upgrade an existing installation."
echo "In this case you'll have to backup your data before running this script"
echo "and to restore them after performing this installation."
echo ""
echo "I'll first ask a couple of questions and try to collect some information"
echo "from your system. If all checks are ok, you'll be asked for confirmation"
echo "before any changes are committed. Up to that point you can terminate this"
echo "script anytime by pressing Ctrl-c"
echo ""

# check whether we are running as root
if [ ! "$(id -g)" = "0" ]; then
    echo "Setting up RefDB requires root permissions for some actions."
    echo "Your group ID suggests you're not logged in as root right now."
    echo "Shall I proceed anyway [y/n]?"
    input=$(confirm)
    [ "${input}" = "n" ] && endScript "I'm stopping here at your request" "failed"
fi

# check whether refdbd is still running
if checkRefdbd; then
    echo ""
    echo "==="
    echo "refdbd may currently be running on your system. Upgrading"
    echo "RefDB while the application server is running may screw up things."
    echo "Stop the application server now by means of the refdbctl(1) script"
    echo "or, if nothing else helps, by sending the appropriate process in the"
    echo "list above the TERM signal."
    echo "Shall I proceed with the installation [y/n]?"
    input=$(confirm)
    [ "${input}" = "n" ] && endScript "I'm stopping here at your request" "failed"
fi

# check the application server control script
echo ""
echo "==="
echo "Checking for the status of the application server control script."
echo "You need to have the permissions to run this script in order to set up"
echo "RefDB with all the bells and whistles. If this test fails, you are most"
echo "likely not running as root."
if ls "$MYREFDBCTL" > /dev/null 2>&1 ; then
    checkFile "$MYREFDBCTL" "execute" \
	|| endScript "$MYREFDBCTL is not executable" "failed"
    echo "$MYREFDBCTL seems to be executable."
else
    endScript "$MYREFDBCTL is not where it is supposed to be" "failed"
fi
   
echo ""
echo "==="
echo "Please select the database engine you want to use."
echo "Available are: mysql pgsql sqlite sqlite3"
echo ""

while [ 1 ] ; do
    read engine_name

    [ "${engine_name}" = "mysql" ] \
    || [ "${engine_name}" = "pgsql" ] \
    || [ "${engine_name}" = "sqlite" ] \
    || [ "${engine_name}" = "sqlite3" ] \
    && break
    printf "Please try again:\a\n"
done


if [ "${engine_name}" = "mysql" ]; then
    echo ""
    echo "==="
    echo "What is the version of the MySQL database engine that you want"
    echo "to connect to?"
    echo "If the version is 4.0 or earlier, type 'pre'"
    echo "If the version is 4.1 or later, type 'post'"

    while [ 1 ] ; do
	read version_name

	[ "${version_name}" = "pre" ] \
	    || [ "${version_name}" = "post" ] \
	    && break
	printf "Please try again:\a\n"
    done
fi

###########################################################################
## check our prerequisites

if [ "${engine_name}" = "mysql" ]; then
# check the config example file
    checkFile "<sysconfdir>/refdbdrc.mysql.example" "read" \
	|| endScript "<sysconfdir>/refdbdrc.mysql.example is not readable or missing" "failed"

# ask for the admin name and password
    echo ""
    echo "==="
    echo "Please enter your database administrator name"
    read dbadmin_name

    echo "Please enter your database administrator password"
    stty -echo
    read dbadmin_password
    stty echo

    readHostInfo "mysql"

elif [ "${engine_name}" = "pgsql" ]; then
    checkFile "<sysconfdir>/refdbdrc.pgsql.example" "read" \
	|| endScript "<sysconfdir>/refdbdrc.pgsql.example is not readable or missing" "failed"
    echo ""
    echo "==="
    echo "PostgreSQL is secure. So secure that it requires you to lean over backwards"
    echo "in order to set up RefDB. On many systems, PostgreSQL may only be"
    echo "administrated from a special Unix account which is often called pgsql or"
    echo "postgres (check your local PostgreSQL docs or peek into /etc/passwd)."
    echo "I may have to use this account in order to set up the RefDB main database."
    echo "You will now be asked to provide the name of the Unix account used for database"
    echo "administration, and additionally the database username required to connect"
    echo "to PostgreSQL from that account. You may later have to provide the"
    echo "passwords too."
    echo ""
    echo "Please enter the name of the Unix account used for database administration:"
    read postgres_name
    if [ ! "${postgres_name}" ]; then
	postgres_name=$USER
    fi
    echo "Please enter the database superuser name:"
    read dbadmin_name
    if [ ! "${dbadmin_name}" ]; then
	dbadmin_name=$postgres_name
    fi
    echo "Please enter your database superuser password"
    read dbadmin_password

    readHostInfo "pgsql"

elif [ "${engine_name}" = "sqlite" ]; then
    checkFile "<sysconfdir>/refdbdrc.sqlite.example" "read" \
	|| endScript "<sysconfdir>/refdbdrc.sqlite.example is not readable or missing" "failed"
    # provide dummy name and password to get a valid refdba config file
    dbadmin_name=root
    dbadmin_password=root
elif [ "${engine_name}" = "sqlite3" ]; then
    checkFile "<sysconfdir>/refdbdrc.sqlite3.example" "read" \
	|| endScript "<sysconfdir>/refdbdrc.sqlite3.example is not readable or missing" "failed"
    # provide dummy name and password to get a valid refdba config file
    dbadmin_name=root
    dbadmin_password=root
fi

# check whether the config file is writable
if ls "<sysconfdir>/refdbdrc" > /dev/null 2>&1 ; then
    if checkFile "<sysconfdir>/refdbdrc" "write" ; then
	echo ""
	echo "==="
	echo "refdbdrc is the main configuration file of the application server refdbd"
	echo "The file exists and is writable. It may contain your modifications"
	echo "of a previous installation. I can replace the file and keep a backup"
	echo "of your current version. Shall I modify refdbdrc [y/n]?"
	replace_refdbdrc=$(confirm)
	[ "${replace_refdbdrc}" = "n" ] && endScript "I'm not allowed to change refdbdrc" "failed"
    else
	endScript "refdbdrc is not writable" "failed"
    fi
fi

# ask for the name of a reference database
echo ""
echo "==="
echo "Please enter the name of a reference database. Reference databases"
echo "hold the bibliographic data, and you need to set up at least one."
echo "Database names can use up to 16 lowercase characters or numbers"
echo "(a-z, 0-9), but do not use the reserved name \"refdb\"."
echo "If you don't want to set up one now, just press [RETURN]."

while [ 1 ]; do
    read referencedb_name

    if [ ! "$referencedb_name" ]; then
	break
    else
# check whether reference database exists
	if [ "${engine_name}" = "mysql" ]; then
	    input="z"
	    pass="--password=${dbadmin_password}"
	    mysql $dbserver_hostname_switch $dbserver_port_switch -u $dbadmin_name $pass -e "SHOW DATABASES LIKE '$referencedb_name'" | grep '$referencedb_name' > /dev/null \
		&& echo "Reference database exists and I'm not going to fiddle with it. Do you want to pick a different name [y/n]?" && input=$(confirm)
	    [ "${input}" = "z" ] && break
	    [ "${input}" = "n" ] && referencedb_name="" && break
	elif [ "${engine_name}" = "pgsql" ]; then
	    echo "When asked for a password, provide the database administrator password"
	    input="z"
	    psql $dbserver_hostname_switch $dbserver_port_switch -U $dbadmin_name -W -c "SELECT datname FROM pg_database WHERE datname LIKE '$referencedb_name'" template1  | grep '$referencedb_name' > /dev/null \
		&& echo "Reference database exists and I'm not going to fiddle with it. Do you want to pick a different name [y/n]?" && input=$(confirm)
	    [ "${input}" = "z" ] && break
	    [ "${input}" = "n" ] && referencedb_name="" && break
	elif [ "${engine_name}" = "sqlite" ] || [ "${engine_name}" = "sqlite3" ]; then
	    input="z"
	    echo ""
	    ls <db_path>/$referencedb_name 2>/dev/null \
		&& echo "Reference database exists and I'm not going to fiddle with it. Do you want to pick a different name [y/n]?" && input=$(confirm)
	    [ "${input}" = "z" ] && break
	    [ "${input}" = "n" ] && referencedb_name="" && break
	fi
    fi
    echo "Enter the name of a reference database:"
done

if [ ! "$referencedb_name" ]; then
    echo "Skip creation of a reference database at your request."
else
    echo "$referencedb_name is marked for creation as a reference database."
    if [ "${engine_name}" = "mysql" ] || [ "${engine_name}" = "pgsql" ]; then
	echo ""
	echo "==="
	echo "You should not use the database administrator account to do your regular"
	echo "work with RefDB. It is strongly recommended to grant access to the reference"
	echo "database from a regular database user account. If the account does not"
	echo "exist yet, it will created as needed. Just press [RETURN] if you"
	echo "don't want to set up or use a database user right now."
	echo "Please enter the name of a database user account:"
	read referencedb_user

	if [ "${referencedb_user}" ]; then
	    echo "If the database user account is new, you should protect it with"
	    echo "a password. If the user account already exists, please just press"
	    echo "[RETURN] now."
	    echo "Please enter a database user password:"
	    read referencedb_password
	fi
    fi
fi

# ask whether a refdba config file should be created
echo ""
echo "==="
echo "In order to administrate your RefDB installation, you should set up"
echo "the administrative client refdba. I can now create a customized configuration"
echo "file in the current login account using the database account you provided."
echo "Should I create a config file in $HOME [y/n]?"
create_refdbarc=$(confirm)
if [ "${create_refdbarc}" = "n" ]; then
    echo "Skip creating refdba config file at your request"
else
    if ls "$HOME/.refdbarc" > /dev/null 2>&1 ; then
	if checkFile "$HOME/.refdbarc" "write" ; then
	    echo ""
	    echo "==="
	    echo "The file exists and is writable. It may contain your modifications"
	    echo "of a previous installation. I can replace the file and keep a backup"
	    echo "of your current version. Should I modify .refdbarc [y/n]?"
	    create_refdbarc=$(confirm)
	    [ "${create_refdbarc}" = "n" ] && endScript "I'm not allowed to change refdbdrc" "failed"
	else
	    endScript ".refdbarc is not writable" "failed"
	fi
    fi
fi


###########################################################################
## ask user to confirm

echo ""
echo "==="
echo "I've finished collecting all required information, and the checks look ok."
echo "If you don't want to touch your existing installation, answer with 'n'."
echo "Shall I proceed and set up RefDB [y/n]?"
input=$(confirm)
[ "$input" = "n" ] && endScript "Bailing out at your request."

###########################################################################
## do the setup

# backup an existing config file
if [ "${replace_refdbdrc}" = "y" ]; then
# appending the date to the name of the refdbdrc backup avoids driving users
# nuts by overwriting the original backup if users have to run the script
# repeatedly. Using the given date output format helps to sort the backups.
    date=$(date "+%Y%m%d%H%M.%S")
    cp <sysconfdir>/refdbdrc <sysconfdir>/refdbdrc.$date \
	|| endScript "Could not backup existing refdbd configuration file" "failed"
    echo "Saved existing refdbd configuration file as"
    echo "<sysconfdir>/refdbdrc.$date"
fi

# create the refdbd config file. Use \t in the sed expressions to pick
# the real values, not the strings in the description
if [ "${engine_name}" = "mysql" ]; then
    sed "s%<refdblib>%<pkgdatadir>%" < <sysconfdir>/refdbdrc.mysql.example | \
	sed "s/\tlocalhost/\t${refdbdrc_hostname}/" | \
	sed "s/\t3306/\t${refdbdrc_port}/"><sysconfdir>/refdbdrc \
	|| endScript "Could not create refdbd config file" "failed"
elif [ "${engine_name}" = "pgsql" ]; then
    sed "s%<refdblib>%<pkgdatadir>%" < refdbdrc.example | \
	sed "s/\tlocalhost/\t${refdbdrc_hostname}/" | \
	sed "s/\t5432/\t${refdbdrc_port}/" ><sysconfdir>/refdbdrc \
	|| endScript "Could not create refdbd config file" "failed"
elif [ "${engine_name}" = "sqlite" ]; then
    cp <sysconfdir>/refdbdrc.sqlite.example <sysconfdir>/refdbdrc \
	|| endScript "Could not create refdbd config file" "failed"
elif [ "${engine_name}" = "sqlite3" ]; then
    cp <sysconfdir>/refdbdrc.sqlite3.example <sysconfdir>/refdbdrc \
	|| endScript "Could not create refdbd config file" "failed"
fi

# create the refdba config file
if [ "${create_refdbarc}" = "y" ]; then
    if [ "${engine_name}" = "sqlite" ] || [ "${engine_name}" = "sqlite3" ]; then
	sed "s/#username.*/username  ${dbadmin_name}/" < <sysconfdir>/refdbarc.example | \
	    sed 's/passwd.*/passwd/' > $HOME/.refdbarc
    else
	sed "s/#username.*/username  ${dbadmin_name}/" < <sysconfdir>/refdbarc.example | \
	    sed "s/passwd.*/passwd ${dbadmin_password}/" > $HOME/.refdbarc
    fi
fi

# create the main database
if [ "${engine_name}" = "pgsql" ]; then
    su $postgres_name -c "$MYREFDBD -a -e 0 -l 6 -u $dbadmin_name -w $dbadmin_password"	|| endScript "Check for PostgreSQL authentication problems" "failed"
else
    $MYREFDBD -a -e 0 -l 6 $refdbd_hostname_switch $refdbd_port_switch -u $dbadmin_name -w $dbadmin_password || endScript "Failed to install or upgrade main database" "failed"
fi

# try to start refdbd
echo "The basic installation was successful. All further steps require that"
echo "refdbd is running. I will now attempt to start the application server"
$MYREFDBCTL start || endScript "Could not start refdbd" "failed"

# wait until the server responds
echo ""
echo "==="
echo "I'll try to talk to the application server. I'll keep pinging until I"
echo "succeed or until you lose patience and press Ctrl-c to terminate"
while [ 1 ]; do
    sleep 2
    $MYREFDBA -c stdout -C viewstat && break
done

# load the styles
echo ""
echo "==="
echo "Load the bibliography and citation styles"
for style in $(grep -l "<CITESTYLE" <pkgdatadir>/styles/*.xml); do
    echo "Loading $style"
    $MYREFDBA -c stdout -C addstyle $style
done

# create a reference database
if [ "${referencedb_name}" ]; then
    echo ""
    echo "==="
    echo "Create ${referencedb_name} as reference database"
    $MYREFDBA -c stdout -C createdb ${referencedb_name}
fi

# add a database user
if [ "${referencedb_user}" ]; then
    echo ""
    echo "==="
    echo "Grant ${referencedb_user} access to the reference database ${referencedb_name}"
    if [ "${referencedb_password}" ]; then
	$MYREFDBA -c stdout -C adduser -d ${referencedb_name} -W ${referencedb_password} ${referencedb_user}
    else
	$MYREFDBA -c stdout -C adduser -d ${referencedb_name} ${referencedb_user}
    fi
fi

# tell admin to tell users to create client config files
echo ""
echo "==="
echo "So far, so good. There's a few more things that you should do as the"
echo "RefDB admin:"
echo "(1) Add <pkgdatadir>/refdb.cat to your SGML master catalog or instruct"
echo "your users to include this catalog into their SGML_CATALOG_FILES"
echo "environment variable"
echo "(2) Educate users to configure their clients by providing the appropriate"
echo "configuration files in their home directories."
echo "(3) Install the refdb start script so that refdbd is started as a daemon"
echo "at system startup."
echo "Please see the RefDB handbook for further details."
echo ""
echo "I've left the RefDB daemon running so you can test your new setup"
echo "immediately. If you want to stop refdbd now, please run the following"
echo "command:"
echo ""
echo "refdbctl stop"
echo ""

exit 0;
