#!/sbin/openrc-run

name="VPNCloud"
description="VPNCloud 2.4.0"
extra_started_commands="status"

CONF="${SVCNAME#*.}"
CONFIG_FILE="/etc/vpncloud/$CONF.net"
PIDFILE="/var/run/vpncloud-$CONF.pid"

depend() {
  need net
  use dns
}

checkconfig() {
  if [ "$CONF" = "$SVCNAME" ]; then
    eerror "Usage error: Create symlink first:"
    eerror "  ln -s /etc/init.d/vpncloud /etc/init.d/vpncloud.<conf-name>"
    eerror "Then start: rc-service vpncloud.<conf-name> start"
    return 1
  fi

  if [ ! -f "$CONFIG_FILE" ]; then
    eerror "Config file $CONFIG_FILE not found!"
    return 1
  fi

  mkdir -p /var/run
  chmod 755 /var/run
  return 0
}

start() {
  checkconfig || return 1
  ebegin "Starting $description (config: $CONF.net)"
  nohup /usr/local/bin/vpncloud --config "$CONFIG_FILE" > /dev/null 2>&1 &
  echo $! > "$PIDFILE"
  eend $? "Start failed!"
}

stop() {
  checkconfig || return 1
  ebegin "Stopping $description (config: $CONF.net)"
  
  if [ -f "$PIDFILE" ]; then
    local PID=$(cat "$PIDFILE")
    # 适配 BusyBox ps：用 grep 过滤 PID（替代 ps -p）
    if ps | grep -w "$PID" > /dev/null; then
      kill -INT "$PID" && sleep 2
      # 再次检查，未停止则强制终止
      if ps | grep -w "$PID" > /dev/null; then
        kill -KILL "$PID"
      fi
    fi
    rm -f "$PIDFILE"
  else
    eerror "PID file not found - service not running?"
    return 1
  fi
  
  eend $? "Stop failed!"
}

status() {
  checkconfig || return 1
  ebegin "Checking $description status (config: $CONF.net)"
  
  if [ -f "$PIDFILE" ] && ps | grep -w "$(cat "$PIDFILE")" > /dev/null; then
    eecho "Running (PID: $(cat "$PIDFILE"))"
    return 0
  else
    eecho "Not running"
    return 1
  fi
  
  eend $?
}