#!/bin/sh

# A routine to change the user that runs interbase Firebird


#------------------------------------------------------------------------
# Prompt for response, store result in Answer

Answer=""

AskQuestion() {
    Test=$1
    DefaultAns=$2
    echo -n "${1}"
    Answer="$DefaultAns"
    read Answer
}



#------------------------------------------------------------------------
# Check for a previous install 


checkInstallUser() {

    if [ "`whoami`" != "root" ];
      then
        ehco ""
        echo "--- Warning ----------------------------------------------"
        echo ""
        echo "    You need to be 'root' user to do this change"
        echo ""
        exit
    fi
}


#------------------------------------------------------------------------
#  check if it is running


checkIfServerRunning() {

# Check is server is being actively used.

    checkString=`ps -efww| egrep "(fbserver|fbguard)" |grep -v grep`

    if [ ! -z "$checkString" ] 
      then
        echo "An instance of the Firebird/InterBase Super server seems to be running." 
        echo "Please quit all interbase applications and then proceed"
        exit 1 
    fi

    checkString=`ps -efww| egrep "(fb_inet_server|gds_pipe)" |grep -v grep`

    if [ ! -z "$checkString" ] 
      then
        echo "An instance of the Firebird/InterBase server seems to be running." 
        echo "Please quit all interbase applications and then proceed." 
        exit 1 
    fi



# Stop lock manager if it is the only thing running.

    for i in `ps -efww | grep "fb_lock_mgr" | grep -v "grep" | awk '{print $2}' `
     do
        kill $i
     done

}

#------------------------------------------------------------------------
#  Add new user and group


addFirebirdUser() {

    testStr=`grep firebird /etc/group`

    if [ -z "$testStr" ]
      then
        groupadd firebird
    fi

    testStr=`grep firebird /etc/passwd`
    if [ -z "$testStr" ]
      then
        useradd -M -d $IBRootDir -s /bin/bash \
            -c "Firebird Database Administrator" -g firebird firebird 

        # >/dev/null 2>&1 
    fi
}




#------------------------------------------------------------------------
#  Delete new user and group


deleteFirebirdUser() {

    userdel firebird
 #   groupdel firebird

}



#------------------------------------------------------------------------
# add a service line in the (usually) /etc/services or /etc/inetd.conf file
# Here there are three cases, not found         => add service line,
#                             found & different => ask user to check
#                             found & same      => do nothing
#                             

replaceLineInFile() {
    FileName=$1
    newLine=$2
    oldLine=$3

    if [ -z "$oldLine" ] 
      then
        echo "$newLine" >> $FileName

    elif [ "$oldLine" != "$newLine"  ]
      then
# We really expect this to be the case.

        cat $FileName | grep -v "$oldLine" > ${FileName}.tmp
        mv ${FileName}.tmp $FileName
        echo "$newLine" >> $FileName
        echo "Updated."

    fi
}


#------------------------------------------------------------------------
#  changeXinetdServiceUser
#  Change the run user of the xinetd service

changeXinetdServiceUser() {

    InitFile=/etc/xinetd.d/firebird
    if [ -f $InitFile ] 
      then
        ex -s $InitFile <<EOF
/	user	/s/=.*$/= $RunUser/g
w
q
EOF
    fi
}

#------------------------------------------------------------------------
#  Update inetd service entry
#  This just adds/replaces the service entry line

updateInetdEntry() {

    FileName=/etc/inetd.conf
    newLine="gds_db  stream  tcp     nowait.30000      $RunUser $IBBin/fb_inet_server fb_inet_server # InterBase Database Remote Server"
    oldLine=`grep "^gds_db" $FileName`

    replaceLineInFile "$FileName" "$newLine" "$oldLine"
}

#------------------------------------------------------------------------
#  Update xinetd service entry

updateXinetdEntry() {

    cp $IBRootDir/misc/firebird.xinetd /etc/xinetd.d/firebird
    changeXinetdServiceUser
}


#------------------------------------------------------------------------
#  Update inetd service entry 
#  Check to see if we have xinetd installed or plain inetd.  Install differs
#  for each of them.

updateInetdServiceEntry() {

    if [ -d /etc/xinetd.d ] 
      then
        updateXinetdEntry
    else
        updateInetdEntry
    fi

}


#------------------------------------------------------------------------
#  fixFilePermissions
#  Change the permissions to restrict access to server programs to 
#  firebird group only.  This is MUCH better from a saftey point of 
#  view than installing as root user, even if it requires a little 
#  more work.


fixFilePermissions() {

    # Turn other access off.
    chmod -R o= $IBRootDir


    # Now fix up the mess.

    # fix up directories 
    for i in `find $IBRootDir -print`
    do
        FileName=$i
        if [ -d $FileName ]
        then
            chmod o=rx $FileName
        fi
    done


    cd $IBBin


    # set up the defaults for bin
    for i in `ls`
      do
         chmod ug=rx,o=  $i
    done

    # User can run these programs, they need to talk to server though.
    # and they cannot actually create a database.
     

    chmod a=rx isql 
    chmod a=rx qli
    
    # SUID is still needed for group direct access.  General users
    # cannot run though.
    for i in fb_lock_mgr gds_drop fb_inet_server
    do
        chmod ug=rx,o= $i
        chmod ug+s $i
    done


    cd $IBRootDir

    # Fix lock files
    for i in isc_init1 isc_lock1 isc_event1 
      do
        FileName=$i.`hostname`
        chmod ug=rw,o= $FileName
      done


    chmod ug=rw,o= firebird.log

	chmod a=r aliases.conf
	chmod a=r firebird.conf
    chmod a=r firebird.msg
    chmod ug=rw,o= help/help.fdb
    chmod ug=rw,o= security.fdb


    # Set a default of read all files in examples

    cd examples

    for i in `ls`
      do
         chmod a=r  $i
    done

    # make examples db's writable by group
    chmod ug=rw,o= *.fdb

}


#------------------------------------------------------------------------
#  resetXinitdServer
#  Check for both inetd and xinetd, only one will be running but script
#  will work.

resetInetdServer() {

    if [ -f /var/run/inetd.pid ]
      then
        kill -HUP `cat /var/run/inetd.pid`
    fi

    if [ -f /var/run/xinetd.pid ]
      then
        kill -HUP `cat /var/run/xinetd.pid`
    fi
}



#= Main Program ============================================================

IBRootDir=@prefix@
IBBin=$IBRootDir/bin




RunUser=firebird
RunGroup=firebird

# Well if you really insist, here it is ;-) - Mark.
#RunUser=interbase
#RunGroup=interbase


# If you want to root user (server run restructed to group root)
# RunUser=root
# RunGroup=root


checkInstallUser

checkIfServerRunning


echo ""
echo "Change Firebird install for $IBRootDir to uid=$RunUser gid=$RunGroup"
echo "(User or group options can be changed by editing this script)"
echo ""
AskQuestion "Press return to continue - or ^C to abort"


if [ $RunUser = "firebird" ]
  then
#    deleteFirebirdUser
    addFirebirdUser
fi



# Update the /etc/inetd.conf or xinetd entry
echo "Updating /etc/services file"
updateInetdServiceEntry


# Update ownership and SUID bits for programs.
echo "Updating $IBRootDir"


chown -R $RunUser.$RunGroup $IBRootDir

fixFilePermissions

# Get inetd to reread new init files.
resetInetdServer


cd $IBRootDir

touch firebird.log
chmod ug=rw,o= firebird.log


# make examples writable by group
chmod ug=rw,o= examples/*.fdb

echo "Completed."
