#!/bin/bash

service="pult_server"
home=$PWD

export PATH="/sbin:/usr/sbin:/bin:/usr/bin:$PATH"

if [ "$(id -u)" -eq 0 ]; then
    SUDO=""
else
    if hash sudo 2>/dev/null; then
        SUDO="sudo"
    else
        echo "sudo command not found" >&2
        exit 1
    fi
fi


if [ -f /etc/selinux/config ] ; then
  printf ">>> Disable SELINUX ... "
  sed -i "s/SELINUX=enforcing/SELINUX=disabled/" /etc/selinux/config
fi

if hash chkconfig 2>/dev/null; then

  file=/etc/init.d/$service

  if [ -f $file ] ; then
    chkconfig --del $service
    rm -f $file
  fi

cat >$file <<EOL
#!/bin/bash
### BEGIN INIT INFO
# Provides: $service
# Required-Start: \$local_fs \$network \$remote_fs
# Required-Stop: \$local_fs \$network \$remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Pult.online services
### END INIT INFO

cd ${home}

case "\$1" in
    boot)
        ./start
        ;;
    start)
        ./start
        ;;
    stop)
        ./stop
        ;;
    restart)
        ./restart
        ;;
    status)
        ./status
        ;;
    *)
    echo $"Usage: service $service {start|stop|restart|status}"
    exit 2
    ;;
esac
EOL

  $SUDO chmod +x $file
  chmod +x $file
  chkconfig --add $service
  usage="Usage: service $service {start|stop|restart|status}"


else
  if hash update-rc.d 2>/dev/null; then

    file=/etc/init.d/$service

    if [ -f $file ] ; then
      $SUDO update-rc.d -f $service remove
      $SUDO rm $file
    fi

cat >$file <<EOL
#!/bin/bash
### BEGIN INIT INFO
# Provides:          $service
# Required-Start:    \$local_fs \$network
# Required-Stop:     \$local_fs \$network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Pult.online services
### END INIT INFO

cd ${home}

case "\$1" in
    boot)
        ./start
        ;;
    start)
        ./start
        ;;
    stop)
        ./stop
        ;;
    restart)
        ./restart
        ;;
    status)
        ./status
        ;;
    *)
        echo $"Usage: service $service {start|stop|restart|status}"
        exit 2
        ;;
esac

exit 0
EOL

    $SUDO chmod +x $file
    chmod +x $file
    $SUDO update-rc.d $service defaults

    usage="Usage: service $service {start|stop|restart|status}"

  else

    file=/etc/init.d/$service

    if [ -f $file ] ; then
      rm -f $file
    fi

cat >$file <<EOL
#!/bin/sh /etc/rc.common

START=99

boot() {
        sleep 10
        cd ${home}
        ./start
}

start() {
        cd ${home}
        ./start
}

restart() {
        cd ${home}
        ./restart
}

stop() {
        cd ${home}
        ./stop
}

status() {
        cd ${home}
        ./status
}
EOL

    chmod +x $file
    $file enable

    usage="Usage: /etc/init.d/$service {start|stop|restart|status}"

  fi
fi

if [[ $? -ne 0 ]]; then
  exit 1
fi
