#cloud-config
# A public Kaspa node: kaspad in Docker on Ubuntu 24.04. From https://kasnodes.com/run/cloud
# Progress: /var/log/kaspad-setup.log
package_update: true
packages:
  - docker.io
  - docker-compose-v2
  - ufw

write_files:
  - path: /opt/kaspad/docker-compose.yml
    content: |
      services:
        kaspad:
          image: kaspanet/rusty-kaspad:latest
          container_name: kaspad
          restart: unless-stopped
          ports:
            - "16111:16111"            # P2P, for other nodes
            - "127.0.0.1:16110:16110"  # RPC, from this server only
          volumes:
            - kaspad-data:/app/data
          env_file:
            - claim.env
          command:
            - kaspad
            - --yes
            - --nologfiles
            - --disable-upnp
            - --utxoindex
            - --rpclisten=0.0.0.0:16110
          logging:
            options:
              max-size: "50m"
              max-file: "3"
      volumes:
        kaspad-data:
  - path: /opt/kaspad/claim.env
    content: |
      # To claim this node on KasNodes, put your code after the = and remove the #, then run
      # cd /opt/kaspad && docker compose up -d
      # KASPAD_USER_AGENT_COMMENTS=
  - path: /opt/kaspad/setup.sh
    permissions: "0755"
    content: |
      #!/bin/bash
      set -euo pipefail
      exec >>/var/log/kaspad-setup.log 2>&1
      echo "Setup started $(date -u)"
      # The chain needs about 640 GB: use an attached volume (mounted under /mnt) when there is one.
      data=""
      for _ in $(seq 60); do
        data=$(findmnt -rn -o TARGET | grep -m1 '^/mnt/' || true)
        [ -n "$data" ] && break
        udevadm trigger || true
        sleep 5
      done
      if [ -n "$data" ]; then
        echo "Keeping the chain on the volume at $data"
        systemctl stop docker docker.socket
        mkdir -p "$data/docker"
        printf '{"data-root": "%s/docker"}\n' "$data" > /etc/docker/daemon.json
      else
        echo "No volume under /mnt after 5 minutes: keeping the chain on the server's own disk"
      fi
      systemctl enable --now docker
      ufw allow OpenSSH
      ufw allow 16111/tcp
      ufw --force enable
      timedatectl set-ntp true || true
      cd /opt/kaspad
      docker compose up -d
      echo "kaspad is running. Follow it with: cd /opt/kaspad && docker compose logs -f kaspad"

runcmd:
  - [bash, /opt/kaspad/setup.sh]
