name: discord bot

on:
  push:
    branches: [main]
    paths: ["bot/**", ".github/workflows/bot.yml", ".github/requirements/bot.*"]
  pull_request:
    paths: ["bot/**", ".github/workflows/bot.yml", ".github/requirements/bot.*"]
  workflow_dispatch:   # redeploy by hand, e.g. after changing the token

permissions:
  contents: read

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
      - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7
        with:
          python-version: "3.12"
          cache: pip
          cache-dependency-path: .github/requirements/bot.txt
      # the runtime versions of bot/requirements.lock – what the server installs – plus pytest
      - run: pip install --require-hashes -r .github/requirements/bot.txt
      - run: python -m pytest -q tests
        working-directory: bot

  deploy:
    needs: test
    if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    concurrency: deploy-bot   # never two deploys at the same time
    env:
      HOST: 100.64.0.2   # develop in the tailnet (own Headscale VPN), no longer the public DEPLOY_HOST
      # install.sh sets up a user, a venv and a systemd unit, so it needs root: either log in as root, or set the
      # secret DEPLOY_USER to a user that may run sudo without a password (for servers with root login off).
      # A secret, not a variable: this repository is public and the login name should not show up in the logs.
      USER_AT_HOST: ${{ secrets.DEPLOY_USER || 'root' }}@100.64.0.2
      SUDO: ${{ (secrets.DEPLOY_USER && secrets.DEPLOY_USER != 'root') && 'sudo -n' || '' }}
    steps:
      - name: Check the secrets
        id: secrets
        env:
          KEY: ${{ secrets.DEPLOY_SSH_KEY }}
          KNOWN: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
          TOKEN: ${{ secrets.DISCORD_TOKEN }}
          TELEGRAM: ${{ secrets.TELEGRAM_TOKEN }}
        run: |
          missing=""
          [ -n "$HOST" ] || missing="$missing DEPLOY_HOST"
          [ -n "$KEY" ] || missing="$missing DEPLOY_SSH_KEY"
          [ -n "$KNOWN" ] || missing="$missing DEPLOY_KNOWN_HOSTS"
          [ -n "$TOKEN$TELEGRAM" ] || missing="$missing DISCORD_TOKEN or TELEGRAM_TOKEN"
          if [ -n "$missing" ]; then
            echo "::notice::Not deploying, secrets missing:$missing (see bot/README.md)"
            echo "ready=false" >> "$GITHUB_OUTPUT"
          else
            echo "ready=true" >> "$GITHUB_OUTPUT"
          fi

      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
        if: steps.secrets.outputs.ready == 'true'

      # The server is reached through the own Headscale VPN, not public SSH. TS_AUTHKEY: reusable, ephemeral
      # pre-auth key with tag:ci, which may only reach port 22 on tag:server.
      - name: Connect to the VPN
        if: steps.secrets.outputs.ready == 'true'
        timeout-minutes: 5
        uses: tailscale/github-action@064b10558093f38325e838ddea35486bdc6b1d5c # v4.4.0
        with:
          authkey: ${{ secrets.TS_AUTHKEY }}
          args: --login-server=https://vpn.aquaris.dev --accept-dns=false
          hostname: gh-proxy-scraper-${{ github.run_id }}
          timeout: 1m
          retry: 3
          ping: 100.64.0.2

      - name: Set up SSH
        if: steps.secrets.outputs.ready == 'true'
        env:
          KEY: ${{ secrets.DEPLOY_SSH_KEY }}
          KNOWN: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
        run: |
          install -d -m 700 ~/.ssh
          printf '%s\n' "$KEY" > ~/.ssh/id_ed25519 && chmod 600 ~/.ssh/id_ed25519
          # pinned host key: a server that suddenly presents a different key gets no token
          printf '%s\n' "$KNOWN" > ~/.ssh/known_hosts
          echo "$HOST ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMWSKndJ3ho1aMrf3M09+OLTG8HSYlul21LqvsyDAsv2" >> ~/.ssh/known_hosts

      # every deploy goes into a fresh release directory; install.sh gives it its own venv and switches
      # /opt/proxybot/current to it only when it imports and starts (bot/README.md: "Rolling back")
      - name: Copy the bot
        if: steps.secrets.outputs.ready == 'true'
        run: |
          # UTC time first: install.sh prunes the oldest by name. A new name each time, so mkdir (not -p) fails
          # instead of unpacking over an existing release
          release="$(date -u +%Y%m%dT%H%M%SZ)-${GITHUB_SHA::12}"
          echo "RELEASE=/opt/proxybot/releases/$release" >> "$GITHUB_ENV"
          tar -C bot --exclude tests --exclude '__pycache__' -czf - . | ssh -o BatchMode=yes "$USER_AT_HOST" \
            "$SUDO sh -c 'set -e; mkdir -p /opt/proxybot/releases; mkdir /opt/proxybot/releases/$release;
             tar -xzf - --no-same-owner -C /opt/proxybot/releases/$release'"

      - name: Write the tokens
        if: steps.secrets.outputs.ready == 'true'
        env:
          TOKEN: ${{ secrets.DISCORD_TOKEN }}
          TELEGRAM: ${{ secrets.TELEGRAM_TOKEN }}
        run: |
          printf 'DISCORD_TOKEN=%s\nTELEGRAM_TOKEN=%s\n' "$TOKEN" "$TELEGRAM" \
            | ssh -o BatchMode=yes "$USER_AT_HOST" "$SUDO sh -c 'umask 077; cat > /etc/proxybot.env'"

      - name: Install and restart
        if: steps.secrets.outputs.ready == 'true'
        run: ssh -o BatchMode=yes "$USER_AT_HOST" "$SUDO sh $RELEASE/deploy/install.sh $RELEASE"
