#!/bin/sh

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

# 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
		echo -ne "\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$"
}

### main ###
echo ""
echo ""
echo "This script will help you to set up a fresh RefDB installation."
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 "/usr/bin/refdbctl" > /dev/null 2>&1 ; then
    checkFile "/usr/bin/refdbctl" "execute" \
	|| endScript "/usr/bin/refdbctl is not executable" "failed"
    echo "refdbctl seems to be executable."
else
    endScript "refdbctl 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
    echo -e "Please try again:\a"
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
	echo -e "Please try again:\a"
    done
fi

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

if [ "${engine_name}" = "mysql" ]; then
# check the config example file
    checkFile "/etc/refdb/refdbdrc.mysql.example" "read" \
	|| endScript "/etc/refdb/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"
    read dbadmin_password

elif [ "${engine_name}" = "pgsql" ]; then
    checkFile "/etc/refdb/refdbdrc.pgsql.example" "read" \
	|| endScript "/etc/refdb/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

elif [ "${engine_name}" = "sqlite" ]; then
    checkFile "/etc/refdb/refdbdrc.sqlite.example" "read" \
	|| endScript "/etc/refdb/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 "/etc/refdb/refdbdrc.sqlite3.example" "read" \
	|| endScript "/etc/refdb/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 "/etc/refdb/refdbdrc" > /dev/null 2>&1 ; then
    if checkFile "/etc/refdb/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 -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 -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 /var/lib/refdb/db/$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 /etc/refdb/refdbdrc /etc/refdb/refdbdrc.$date \
	|| endScript "Could not backup existing refdbd configuration file" "failed"
    echo "Saved existing refdbd configuration file as"
    echo "/etc/refdb/refdbdrc.$date"
fi

# create the refdbd config file
if [ "${engine_name}" = "mysql" ]; then
    cp /etc/refdb/refdbdrc.mysql.example /etc/refdb/refdbdrc \
	|| endScript "Could not create refdbd config file" "failed"
elif [ "${engine_name}" = "pgsql" ]; then
    cp /etc/refdb/refdbdrc.pgsql.example /etc/refdb/refdbdrc \
	|| endScript "Could not create refdbd config file" "failed"
elif [ "${engine_name}" = "sqlite" ]; then
    cp /etc/refdb/refdbdrc.sqlite.example /etc/refdb/refdbdrc \
	|| endScript "Could not create refdbd config file" "failed"
elif [ "${engine_name}" = "sqlite3" ]; then
    cp /etc/refdb/refdbdrc.sqlite3.example /etc/refdb/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}/" < /etc/refdb/refdbarc.example | \
	    sed 's/passwd.*/passwd/' > $HOME/.refdbarc
    else
	sed "s/#username.*/username  ${dbadmin_name}/" < /etc/refdb/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 "/usr/bin/refdbd -a -e 0 -l 6 -u $dbadmin_name -w $dbadmin_password"	|| endScript "Check for PostgreSQL authentication problems" "failed"
else
    /usr/bin/refdbd -a -e 0 -l 6 -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"
/usr/bin/refdbctl 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
    /usr/bin/refdba -c stdout -C viewstat && break
done

# load the styles
echo ""
echo "==="
echo "Load the bibliography and citation styles"
for style in $(grep -l CITESTYLE /usr/share/refdb/styles/*.xml); do
    echo "Loading $style"
    /usr/bin/refdba -c stdout -C addstyle $style
done

# create a reference database
if [ "${referencedb_name}" ]; then
    echo ""
    echo "==="
    echo "Create ${referencedb_name} as reference database"
    /usr/bin/refdba -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
	/usr/bin/refdba -c stdout -C adduser -d ${referencedb_name} -W ${referencedb_password} ${referencedb_user}
    else
	/usr/bin/refdba -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 /usr/share/refdb/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;
