#!/bin/sh
#############################################################
# Copyright (C) 2005 Parallels Inc.  All Rights Reserved.
# Setup script for autoload drivers
#############################################################

. gettext.sh

export TEXTDOMAIN="parallels"

initd="/etc/init.d/"
chkconfig="/sbin/chkconfig"
rc_name="parallels"
rc_file="/usr/lib/parallels/autostart/$rc_name"

# Get chkconfig utlity 
function get_chkconfig() {

    chkp=`which chkconfig`
    err=$?

    if test $err -eq 0; then
        chkconfig=`which chkconfig`
    else 
        chkconfig=""
    fi
}

# Get init.d directory path
function get_initd() {
    
    if test "x$chkconfig" != "x"; then
        if test -d /etc/init.d; then
            initd="/etc/init.d/"
        elif test -d /etc/rc.d/init.d; then
            initd="/etc/rc.d/init.d/"
        fi
    else
        if test -d /etc/rc5.d; then
            initd="/etc/"
        elif test -d /etc/rc.d/rc5.d; then
            initd="/etc/rc.d/"
        elif test -d /etc/init.d/rc5.d; then
            initd="/etc/init.d/"
        fi
    fi
}

# Main install proc
function do_install() {

    get_chkconfig
    get_initd

    if test "x$chkconfig" != "x"; then
        $chkconfig --del $rc_name > /dev/null &> /dev/null
        ln -sf $rc_file $initd
        $chkconfig --add $rc_name > /dev/null &> /dev/null
        $chkconfig $rc_name 35 > /dev/null &> /dev/null
    else
        # Set autostart via links ( do not forget to remove ! )
        ## start
        ln -sf $rc_file $initd/rc2.d/S90$rc_name > /dev/null 2>&1
        ln -sf $rc_file $initd/rc3.d/S90$rc_name > /dev/null 2>&1
        ln -sf $rc_file $initd/rc5.d/S90$rc_name > /dev/null 2>&1
        ## stop
        ln -sf $rc_file $initd/rc2.d/K90$rc_name > /dev/null 2>&1
        ln -sf $rc_file $initd/rc3.d/K90$rc_name > /dev/null 2>&1
        ln -sf $rc_file $initd/rc5.d/K90$rc_name > /dev/null 2>&1
    fi
}

# Main remove proc
function do_remove() {

    get_chkconfig
    get_initd

    if test "x$chkconfig" != "x"; then
        $chkconfig --del $rc_name > /dev/null &> /dev/null
        rm -f $initd/$rc_name > /dev/null 2>&1
    else
        # Set autostart via links ( do not forget to remove ! )
        rm -f   $initd/rc3.d/S90$rc_name $initd/rc5.d/S90$rc_name \
                $initd/rc3.d/K90$rc_name $initd/rc5.d/K90$rc_name > /dev/null 2>&1
    fi
    
    # On suse i've see segfault on del, try to remove manually
    if test -d $initd; then
        cd $initd
        find . -iname $rc_name | xargs rm -f > /dev/null 2>&1
    fi
}

case "$1" in
    install)
        do_install
    ;;
    remove)
        do_remove
    ;;
    *)
        eval_gettext "=> This program installs/removes Parallels Workstation init script
Usage: $0 <install/remove>
 install  : Install init script
 remove   : Remove init script"; echo
    ;;
esac

exit 0
