#!/bin/bash

PIDFILE="/tmp/webgif.pid"
PORT=8000
DIR="/usr/share/webgif"
HOST="0.0.0.0"

start() {
  if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
    echo "WebGIF is already running."
    exit 0
  fi

  echo "Starting WebGIF on http://localhost:$PORT"
  cd "$DIR" || exit 1

  python3 -m http.server "$PORT" --bind "$HOST" > /dev/null 2>&1 &
  echo $! > "$PIDFILE"
}

stop() {
  if [ ! -f "$PIDFILE" ]; then
    echo "WebGIF is not running."
    exit 0
  fi

  if kill "$(cat "$PIDFILE")" 2>/dev/null; then
    rm -f "$PIDFILE"
    echo "WebGIF stopped."
  else
    echo "Failed to stop WebGIF (process may not exist)."
    rm -f "$PIDFILE"
  fi
}

status() {
  if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
    echo "WebGIF is running (PID $(cat "$PIDFILE"))."
  else
    echo "WebGIF is not running."
  fi
}

case "$1" in
  start) start ;;
  stop) stop ;;
  status) status ;;
  *)
    echo "Usage: webgif {start|stop|status}"
    ;;
esac
