name: update geoip-db

on:
  schedule:
    - cron: '0 0 * * *'
  workflow_dispatch:

permissions:
  contents: read

concurrency:
  group: update-geoip-db
  cancel-in-progress: false

jobs:
  refresh-db:
    runs-on: blacksmith-2vcpu-ubuntu-2404
    timeout-minutes: 10

    steps:
      - name: Checkout
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Set up SSH agent
        uses: webfactory/ssh-agent@v0.9.1
        with:
          ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY_SERVER }}

      - name: Add server to known hosts
        run: |
          set -euo pipefail
          mkdir -p ~/.ssh
          ssh-keyscan -H ${{ secrets.SERVER_IP }} >> ~/.ssh/known_hosts

      - name: Refresh MMDB on server & roll restart
        env:
          SERVER: ${{ secrets.SERVER_USER }}@${{ secrets.SERVER_IP }}
          IPINFO_TOKEN: ${{ secrets.IPINFO_TOKEN }}
        run: |
          set -euo pipefail

          ssh "${SERVER}" bash << EOSSH
            set -euo pipefail

            if ! command -v curl >/dev/null 2>&1; then
              sudo apt-get update -y
              sudo apt-get install -y curl
            fi

            if ! command -v go >/dev/null 2>&1; then
              sudo apt-get update -y
              sudo apt-get install -y golang-go
            fi

            export PATH="\$PATH:\$(go env GOPATH)/bin"
            if ! command -v mmdbverify >/dev/null 2>&1; then
              GOBIN="\$(go env GOPATH)/bin" go install github.com/maxmind/mmdbverify@latest
            fi

            TMPDIR="\$(mktemp -d)"
            trap 'rm -rf "\$TMPDIR"' EXIT

            DEST_DIR="/etc/fluxer"
            DEST_DB="\${DEST_DIR}/ipinfo_lite.mmdb"

            mkdir -p "\$DEST_DIR"

            curl -fsSL -o "\$TMPDIR/ipinfo_lite.mmdb" \
              "https://ipinfo.io/data/ipinfo_lite.mmdb?token=${IPINFO_TOKEN}"

            [ -s "\$TMPDIR/ipinfo_lite.mmdb" ]

            mmdbverify -file "\$TMPDIR/ipinfo_lite.mmdb"

            install -m 0644 "\$TMPDIR/ipinfo_lite.mmdb" "\$DEST_DB.tmp"
            mv -f "\$DEST_DB.tmp" "\$DEST_DB"

            docker service update --force fluxer-geoip_app
          EOSSH
