#! /bin/sh

# This script is an adapted version of the pkg-install of the
# databases/postgresql7 port. (Wouldn't it be nice to have a
# target for making a user in bsd.port.mk or something similar?)

# $FreeBSD: www/py-webware/pkg-install 300897 2012-07-14 14:29:18Z beat $

PATH=/bin:/usr/sbin:${LOCALBASE}/bin:

# set these if not provided by the Makefile
WEBWARE_USER=${WEBWARE_USER:-webkit}
WEBWARE_GROUP=${WEBWARE_USER:-webkit}
WEBWARE_MASTER_DIR=${WEBWARE_MASTER_DIR:-${PKG_PREFIX}/share/webware}
WEBKIT_HOME_DIR=${WEBKIT_HOME_DIR:-${PKG_PREFIX}/www/webkit}

add_webkit_account()
{
    UID=108  # shouldn't be used for any other user!
    GID=${UID}

    if pw group show "${WEBWARE_GROUP}" 2>/dev/null; then
        echo "You already have a group \"${WEBWARE_GROUP}\", so I will use it."
    else
        if pw groupadd ${WEBWARE_GROUP} -g ${GID}; then
            echo "Added group \"${WEBWARE_GROUP}\"."
        else
            echo "Adding group \"${WEBWARE_GROUP}\" failed..."
            exit 1
        fi
    fi

    if pw user show "${WEBWARE_USER}" 2>/dev/null; then
        echo "You already have a user \"${WEBWARE_USER}\", so I will use it."
    else
        if pw useradd ${WEBWARE_USER} -u ${UID} -g ${WEBWARE_GROUP} -h - \
            -d ${WEBKIT_HOME_DIR} -c "WebKit Default User"
        then
            echo "Added user \"${WEBWARE_USER}\"."
        else
            echo "Adding user \"${WEBWARE_USER}\" failed..."
            exit 1
        fi
    fi
}

compile_python_files()
{
	(cd ${WEBWARE_MASTER_DIR} && python install.py --no-password-prompt)
}

make_webkit_home_dir()
{
    # make the default webware user home directory if it doesn't exist yet
    if ! [ -d ${WEBKIT_HOME_DIR} ] ; then
        # make application workdir for webkit user
        python ${WEBWARE_MASTER_DIR}/bin/MakeAppWorkDir.py \
               ${WEBKIT_HOME_DIR}
        chown -R root:wheel ${WEBKIT_HOME_DIR}
        echo chown -R ${WEBWARE_USER}:${WEBWARE_GROUP} \
            ${WEBKIT_HOME_DIR}/Cache ${WEBKIT_HOME_DIR}/ErrorMsgs \
            ${WEBKIT_HOME_DIR}/Logs ${WEBKIT_HOME_DIR}/Sessions
        chown -R ${WEBWARE_USER}:${WEBWARE_GROUP} \
            ${WEBKIT_HOME_DIR}/Cache ${WEBKIT_HOME_DIR}/ErrorMsgs \
            ${WEBKIT_HOME_DIR}/Logs ${WEBKIT_HOME_DIR}/Sessions
    fi
}

case $2 in
PRE-INSTALL)
    add_webkit_account
    ;;
POST-INSTALL)
    compile_python_files
    if ! [ -f ${WEBKIT_HOME_DIR}/AppServer ] ; then
        make_webkit_home_dir
    fi
    ;;
esac
