#!/bin/bash

# Make idmgr account, if not already present
# This should be a system account (no passwd timeout), w. no passwd,
# but having a home directory.
if [ ! -d /home/idmgr ] ; then
   /usr/sbin/useradd -s /sbin/nologin -r -m \
       -c "idmgr Registration service" idmgr &>/dev/null || :
fi

# Make directory in /library for user accounts, if not already done
mkdir -p /library/users

# Make sure the xousers group exists
getent group xousers > /dev/null 2>&1 || groupadd xousers

#  Create the identity database, if there is no pre-existing one
#  and set the current rev number
if [ ! -r /home/idmgr/identity.db ] ; then
   # creates a v2 format file
   /usr/libexec/idmgr/create_registration
fi

if [ ! -r /home/idmgr/storage_format_version ] || \
   [ `cat /home/idmgr/storage_format_version` == 0 ] ; then
   # Existing users might not be in the xousers group. Fix that.
   /usr/libexec/idmgr/update_users_0_to_1.py
   echo 1 > /home/idmgr/storage_format_version
fi

if [ ! -r /home/idmgr/storage_format_version ] || \
   [ `cat /home/idmgr/storage_format_version` == 1 ] ; then
   # Add database columns for UUID and modification date.
   /usr/libexec/idmgr/update_users_1_to_2.py && \
   echo 2 > /home/idmgr/storage_format_version
fi

if [ ! -r /home/idmgr/storage_format_version ] || \
   [ `cat /home/idmgr/storage_format_version` == 2 ] ; then
   # Add database column for group
   /usr/libexec/idmgr/update_users_2_to_3.py && \
   echo 3 > /home/idmgr/storage_format_version
fi

# Make readable by apache and others
chmod ugo+rx /home/idmgr

/sbin/chkconfig --add idmgr
/sbin/service idmgr condrestart

