#!/bin/bash usage() { echo "Usage: $0 start|stop" exit 1 } start_server() { if [ -f "$PID_FILE" ]; then echo "Already running!" exit 1 fi cd "$WEBROOT_DIR" if command -v python3 > /dev/null; then nohup python3 -m http.server --bind "$BIND_ADDR" --cgi "$BIND_PORT" > "$OUT_FILE" 2>&1 & elif command -v python2 > /dev/null; then nohup python2 -m CGIHTTPServer "$BIND_PORT" > "$OUT_FILE" 2>&1 & else echo "Require python2 or python3!" exit 1 fi echo "$!" > "$PID_FILE" echo "Started." exit } stop_server() { if [ ! -f ./server.pid ]; then echo "Not running." exit fi local PID="$(cat "$PID_FILE")" if ! kill -0 "$PID" 2> /dev/null; then echo "Not running." rm -f "$PID_FILE" exit fi kill "$PID" echo "Stopped." rm -f "$PID_FILE" exit } cd "$(dirname "$0")" BASE_DIR="$(pwd)" BIND_ADDR=0.0.0.0 BIND_PORT=8000 WEBROOT_DIR="${BASE_DIR}/webroot" PID_FILE="${BASE_DIR}/server.pid" OUT_FILE="${BASE_DIR}/server.out" export LOG_DIR="/usr/local/myapp/logs" case "$1" in start) start_server ;; stop) stop_server ;; *) usage ;; esac