#cloud-config
package_update: true
package_upgrade: true

packages:
  - docker.io
  - docker-compose

users:
  - name: minecraft
    no_create_home: true
    ssh-authorized-keys:
      - "YOUR_SSH_HERE"

write_files:
  - path: /opt/minecraft/docker-compose.yml
    content: |
      version: '3'
      services:
        minecraft:
          image: itzg/minecraft-server
          restart: unless-stopped
          ports:
            - '25565:25565'
          environment:
            EULA: 'TRUE'
            MEMORY: '2G'
          volumes:
            - '/opt/minecraft/data:/data'
    owner: "minecraft:minecraft"
    permissions: "0644"
    defer: true

  - path: /etc/systemd/system/minecraft.service
    content: |
      [Unit]
      Description=Minecraft Server
      After=network.target docker.service
      
      [Service]
      User=minecraft
      WorkingDirectory=/opt/minecraft
      ExecStart=/usr/bin/docker-compose up
      ExecStop=/usr/bin/docker-compose down
      Restart=always
      
      [Install]
      WantedBy=multi-user.target
    owner: "root:root"
    permissions: "0644"

runcmd:
  - mkdir -p /opt/minecraft/data
  - chown -R minecraft:minecraft /opt/Minecraft
  - usermod -aG docker minecraft
  - systemctl daemon-reload
  - systemctl enable minecraft
  - systemctl start minecraft

power_state:
  mode: reboot