#!/usr/bin/env bash
# Absolute Raid Bot - first-time setup: Discord token, owner, server, log channel. Run: sudo arb-setup
set -euo pipefail
APP=/opt/absolute-raid-bot
[ "$(id -u)" = "0" ] || { echo "Run it with sudo: sudo arb-setup"; exit 1; }
echo "Absolute Raid Bot setup (Enter keeps the value in brackets)"
cur() { "$APP/venv/bin/python" -c "import json,sys;print(json.load(open('$APP/config.json')).get(sys.argv[1],''))" "$1" 2>/dev/null || true; }
OWNER_D="$(cur owner_id)"; GUILD_D="$(cur guild_id)"; LOG_D="$(cur log_channel_id)"
read -rsp "Discord bot token (hidden; Enter keeps the current one): " TOKEN; echo
read -rp  "Owner's Discord user ID (optional; empty = whoever pairs becomes owner) [$OWNER_D]: " OWNER; OWNER="${OWNER:-$OWNER_D}"
read -rp  "Your Discord server ID [$GUILD_D]: " GUILD; GUILD="${GUILD:-$GUILD_D}"
read -rp  "Staff log channel ID (optional) [$LOG_D]: " LOGC; LOGC="${LOGC:-$LOG_D}"
[[ -z "$OWNER" || "$OWNER" =~ ^[0-9]{15,22}$ ]] || { echo "The owner ID should be a long number (Discord: Copy User ID)."; exit 1; }
[[ -z "$GUILD" || "$GUILD" =~ ^[0-9]{15,22}$ ]] || { echo "The server ID should be a long number (Discord: Copy Server ID)."; exit 1; }
if [ -n "$TOKEN" ]; then
  umask 077
  printf 'DISCORD_TOKEN=%s\n' "$TOKEN" > /etc/absolute-raid-bot/bot.env
elif [ ! -s /etc/absolute-raid-bot/bot.env ]; then
  echo "A token is needed the first time."; exit 1
fi
chmod 600 /etc/absolute-raid-bot/bot.env
"$APP/venv/bin/python" - "$OWNER" "$GUILD" "$LOGC" <<'PY'
import json, os, sys
p = "/opt/absolute-raid-bot/config.json"
c = json.load(open(p)) if os.path.exists(p) else json.load(open("/opt/absolute-raid-bot/config.example.json"))
c.pop("token", None)
c.update({"owner_id": sys.argv[1], "guild_id": sys.argv[2], "log_channel_id": sys.argv[3], "data_dir": "data"})
json.dump(c, open(p, "w"), indent=2)
PY
chown arb:arb "$APP/config.json"; chmod 640 "$APP/config.json"
systemctl enable absolute-raid-bot >/dev/null
systemctl restart absolute-raid-bot
sleep 6
if systemctl is-active --quiet absolute-raid-bot; then
  echo; echo "The bot is running."
  if [ -s "$APP/data/pairing-code.txt" ]; then
    echo; echo "  PAIRING CODE:  $(cat "$APP/data/pairing-code.txt")"
    echo "  In your Discord server, a member with Manage Server runs:  /dkpadmin pair code:<the code>"
    echo "  Until then the bot answers nothing else. (Lost it? sudo arb-status shows it again.)"
  else
    echo "Already paired. In Discord: /dkpadmin 2fa-setup"
  fi
  echo "IMPORTANT: copy $APP/data/secret.key somewhere safe (it opens your backups):"
  echo "  sudo cat $APP/data/secret.key"
else
  echo "The bot didn't start. Last log lines:"; journalctl -u absolute-raid-bot -n 30 --no-pager
fi
