#! /bin/sh

set -e

#
# Variables defined during the oar installation process
#
PREFIX="%%PREFIX%%"
BINDIR="%%BINDIR%%"
CGIDIR="%%CGIDIR%%"
DOCDIR="%%DOCDIR%%"
EXAMPLEDIR="%%EXAMPLEDIR%%"
ETCDIR="%%ETCDIR%%"
OARCONFDIR="%%OARCONFDIR%%"
OARDIR="%%OARDIR%%"
SHAREDIR="%%SHAREDIR%%"
PERLLIBDIR="%%PERLLIBDIR%%"
RUNDIR="%%RUNDIR%%"
LOGDIR="%%LOGDIR%%"
MANDIR="%%MANDIR%%"
SBINDIR="%%SBINDIR%%"
VARLIBDIR="%%VARLIBDIR%%"
OARHOMEDIR="%%OARHOMEDIR%%"
ROOTUSER="%%ROOTUSER%%"
ROOTGROUP="%%ROOTGROUP%%"
OARDO_DEFAULTUSER="%%OARDO_DEFAULTUSER%%"
OARDO_DEFAULTGROUP="%%OARDO_DEFAULTGROUP%%"
OARUSER="%%OARUSER%%"
OAROWNER="%%OAROWNER%%"
OAROWNERGROUP="%%OAROWNERGROUP%%"
WWWUSER="%%WWWUSER%%"
APACHECONFDIR="%%APACHECONFDIR%%"
WWWROOTDIR="%%WWWROOTDIR%%"
WWWDIR="%%WWWDIR%%"
XAUTHCMDPATH="%%XAUTHCMDPATH%%"
OARSHCMD="%%OARSHCMD%%"
INITDIR="%%INITDIR%%"
DEFAULTDIR="%%DEFAULTDIR%%"
SETUP_TYPE="%%SETUP_TYPE%%"
TARGET_DIST="%%TARGET_DIST%%"
OARDOPATH="%%OARDOPATH%%"

#
# shared functions for oar setup files.
#

install_conffile() {

    
    case "${SETUP_TYPE}" in
        "deb")
            install_deb_conffile $*
            ;;
        "rpm")
            install_rpm_conffile $*
            ;;
        "tgz"|*)
            install_if_not_exist $*
            ;;
    esac

}


install_deb_conffile() {
    local src dst rights owner tmpfile package
    src=$1
    dst=$2
    rights=$3
    owner=$4

    # PACKAGE need to be defined in the postinst before calling *-setup.
    package=$PACKAGE

    ucf --debconf-ok --three-way $src $dst
    ucfr $package $dst

    if [ -n "$rights" ]; then
        chmod $rights $dst
    fi
    if [ -n "$owner" ]; then
        chown $owner $dst
    fi
    
    if [ -f "$tmpfile" ]; then
        rm -f "$tmpfile"
    fi
}

install_rpm_conffile() {
    # I've not found ucf or equivalent to install config file during postinst
    # in the rpm world. So the config file are nstalled manually in the spec
    # file.

    local src dst rights owner tmpfile
    src=$1
    dst=$2
    rights=$3
    owner=$4
    
    if [ -n "$rights" ]; then
        chmod $rights $dst
    fi
    if [ -n "$owner" ]; then
        chown $owner $dst
    fi
}

install_if_not_exist() {
    local src dst rights owner
    src=$1
    dst=$2
    rights=$3
    owner=$4

        
    # Decompress the file, if compressed
    tmpfile=
    if [ ! -f "$src" ] && [ -f "${src}.gz" ]; then
        tmpfile=$(tempfile)
        zcat ${src}.gz > $tmpfile
        src=$tmpfile
    fi

    if [ -f "$dst" ]; then 
        :
    else 
        install $src $dst
        if [ -n "$rights" ]; then
            chmod $rights $dst
        fi
        if [ -n "$owner" ]; then
            chown $owner $dst
        fi
    fi
    
    if [ -f "$tmpfile" ]; then
        rm -f "$tmpfile"
    fi
}

set_rights() {
  file=$1
  perms=$2
  owner=$3
  group=$4

  [ -n "$owner" ] && chown $owner $file
  [ -n "$group" ] && chgrp $group $file
  [ -n "$perms" ] && chmod $perms $file
}

