Skip to content

Instantly share code, notes, and snippets.

@RamonGilabert
Last active April 12, 2016 16:28
Show Gist options
  • Save RamonGilabert/e15e91de0b5937e145bba4cca342c637 to your computer and use it in GitHub Desktop.
Save RamonGilabert/e15e91de0b5937e145bba4cca342c637 to your computer and use it in GitHub Desktop.
#!/bin/sh
USER="pi"
APP_DIR="/home/pi/Desktop/Lights-Berry"
NODE_APP="app.js"
CONFIG_DIR="$APP_DIR"
PID_DIR="$APP_DIR/pid"
PID_FILE="$PID_DIR/app.pid"
LOG_DIR="$APP_DIR/log"
LOG_FILE="$LOG_DIR/app.log"
NODE_EXEC=$(which node)
APP_NAME="Lights"
USAGE="Usage: $0 { start | stop | restart }"
###############
# REDHAT chkconfig header
# chkconfig: - 58 74
# description: Lights is the script for starting Lights on boot.
### BEGIN INIT INFO
# Provides: node
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: start and stop node.
# Description: Node process for an app.
### END INIT INFO
###############
pid_file_exists() {
[ -f "$PID_FILE" ]
}
get_pid() {
echo "$(cat "$PID_FILE")"
}
remove_pid_file() {
echo "Removing pid file"
rm -f "$PID_FILE"
}
is_running() {
PID=$(get_pid)
! [ -z "$(ps aux | awk '{print $2}' | grep "^$PID$")" ]
}
start_it() {
echo "Starting $APP_NAME..."
echo "cd $APP_DIR && (NODE_CONFIG_DIR=$CONFIG_DIR $NODE_EXEC $APP_DIR/$NODE_APP 1>$LOG_FILE 2>&1 & echo \$! > $PID_FILE)" | sudo -i -u $USER
echo "$APP_NAME started with pid $(get_pid)"
}
stop_process() {
PID=$(get_pid)
echo "Killing process $PID"
kill -9 $PID
}
start_app() {
if pid_file_exists
then
if is_running
then
PID=$(get_pid)
echo "$APP_NAME already running with pid $PID"
exit 1
else
echo "$APP_NAME stopped, but pid file exists"
remove_pid_file
start_it
fi
else
start_it
fi
}
stop_app() {
if pid_file_exists
then
if is_running
then
echo "Stopping $APP_NAME..."
stop_process
remove_pid_file
echo "$APP_NAME stopped"
else
echo "$APP_NAME already stopped, but pid file exists"
remove_pid_file
fi
else
echo "$APP_NAME already stopped, pid file does not exist"
exit 1
fi
}
case "$1" in
start)
start_app
;;
stop)
stop_app
;;
restart)
stop_app
start_app
;;
*)
echo $USAGE
exit 1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment