#!/bin/sh
set -eu

APP_DIR=/opt/bayouradar-skywarn
CONFIG_DIR=/etc/bayouradar-skywarn
STATE_DIR=/var/lib/bayouradar-skywarn
RUN_DIR=/run/bayouradar-skywarn
SOURCE_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)

if [ "$(id -u)" -ne 0 ]; then
  echo "Run this installer as root." >&2
  exit 1
fi

if command -v apt-get >/dev/null 2>&1; then
  apt-get update
  DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-venv python3-pip python3-yaml ffmpeg espeak-ng
elif command -v pacman >/dev/null 2>&1; then
  pacman -Sy --noconfirm python python-pip python-yaml ffmpeg espeak
else
  echo "Unsupported package manager. Install Python 3, PyYAML, ffmpeg, and espeak/espeak-ng manually." >&2
fi

RUN_USER=root
RUN_GROUP=root
if id asterisk >/dev/null 2>&1; then
  RUN_USER=asterisk
  RUN_GROUP=$(id -gn asterisk)
fi

mkdir -p "$APP_DIR" "$CONFIG_DIR" "$STATE_DIR" "$RUN_DIR" /tmp/AUTOSKY
rm -rf "$APP_DIR/src"
cp -R "$SOURCE_DIR/src" "$SOURCE_DIR/setup.py" "$SOURCE_DIR/requirements.txt" "$SOURCE_DIR/VERSION" "$SOURCE_DIR/LICENSE" "$SOURCE_DIR/NOTICE.md" "$APP_DIR/"
mkdir -p "$APP_DIR/audio/tones" "$APP_DIR/audio/ids"

rm -rf "$APP_DIR/venv"
python3 -m venv --system-site-packages "$APP_DIR/venv"
if ! "$APP_DIR/venv/bin/python" -c 'import yaml' >/dev/null 2>&1; then
  echo "PyYAML is unavailable inside the virtual environment." >&2
  exit 1
fi
mkdir -p "$APP_DIR/bin"
cat > "$APP_DIR/bin/br-skywarn" <<'EOF'
#!/bin/sh
export PYTHONPATH=/opt/bayouradar-skywarn/src
exec /opt/bayouradar-skywarn/venv/bin/python -m bayouradar_skywarn.cli "$@"
EOF
cat > "$APP_DIR/bin/br-skywarn-service" <<'EOF'
#!/bin/sh
export PYTHONPATH=/opt/bayouradar-skywarn/src
exec /opt/bayouradar-skywarn/venv/bin/python -m bayouradar_skywarn.service "$@"
EOF
chmod 755 "$APP_DIR/bin/br-skywarn" "$APP_DIR/bin/br-skywarn-service"

if [ ! -f "$CONFIG_DIR/config.yaml" ]; then
  cp "$SOURCE_DIR/config/config.example.yaml" "$CONFIG_DIR/config.yaml"
  chmod 640 "$CONFIG_DIR/config.yaml"
fi

chown -R "$RUN_USER:$RUN_GROUP" "$APP_DIR" "$STATE_DIR" "$RUN_DIR" /tmp/AUTOSKY
chown root:"$RUN_GROUP" "$CONFIG_DIR/config.yaml"

if command -v systemctl >/dev/null 2>&1; then
  sed -e "s/__RUN_USER__/$RUN_USER/g" -e "s/__RUN_GROUP__/$RUN_GROUP/g" "$SOURCE_DIR/deploy/bayouradar-skywarn.service" > /etc/systemd/system/bayouradar-skywarn.service
  systemctl daemon-reload
  systemctl enable bayouradar-skywarn.service
  echo "Installed systemd service. Configure $CONFIG_DIR/config.yaml, then run:"
  echo "  /opt/bayouradar-skywarn/bin/br-skywarn config-check"
  echo "  systemctl restart bayouradar-skywarn"
else
  cp "$SOURCE_DIR/deploy/bayouradar-skywarn.cron" /etc/cron.d/bayouradar-skywarn
  echo "systemd not found; installed one-minute cron compatibility mode."
fi
