#cloud-config
# ──────────────────────────────────────────────────────────────
# Quark's Holo-Grid Ledger — App server cloud-init
# Provisions: Docker, deploy user, volume mount, app directory
# Stack: Caddy · Tongo Core · Web Terminal · Valkey
# ──────────────────────────────────────────────────────────────

package_update: true
package_upgrade: true

packages:
  - ca-certificates
  - curl
  - gnupg
  - lsb-release

# ── Install Docker & prepare the application environment ────
runcmd:
  # Add Docker GPG key
  - install -m 0755 -d /etc/apt/keyrings
  - curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
  - chmod a+r /etc/apt/keyrings/docker.asc

  # Add Docker apt repository
  - |
    echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" \
      > /etc/apt/sources.list.d/docker.list

  - apt-get update -y
  - apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

  # Enable and start Docker
  - systemctl enable docker
  - systemctl start docker

  # Create deploy user with docker group access
  - useradd -m -s /bin/bash -G docker deploy
  - mkdir -p /home/deploy/.ssh
  - echo "${ssh_public_key}" > /home/deploy/.ssh/authorized_keys
  - chmod 700 /home/deploy/.ssh
  - chmod 600 /home/deploy/.ssh/authorized_keys
  - chown -R deploy:deploy /home/deploy/.ssh

  # Harden SSH — disable root login
  - sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config
  - systemctl restart sshd

  # Create application directory
  - mkdir -p /opt/hologrid
  - chown deploy:deploy /opt/hologrid

  # Mount the Hetzner persistent volume at /mnt/data
  # The volume is pre-formatted as ext4 by Hetzner
  - mkdir -p /mnt/data
  - |
    VOLUME_DEV="/dev/disk/by-id/scsi-0HC_Volume_${volume_id}"
    # Wait briefly for the device to appear
    for i in $(seq 1 10); do [ -e "$VOLUME_DEV" ] && break; sleep 2; done
    mount -o defaults "$VOLUME_DEV" /mnt/data
  - |
    echo "/dev/disk/by-id/scsi-0HC_Volume_${volume_id} /mnt/data ext4 defaults 0 2" >> /etc/fstab
  - chown deploy:deploy /mnt/data

# ── Placeholder for the application stack ────────────────────
# The production docker-compose.prod.yml will be deployed to
# /opt/hologrid/ by the Forgejo Actions CI/CD pipeline.
# It will include:
#   - Caddy (reverse proxy + automatic TLS for ${domain})
#   - Tongo Core (Go backend)
#   - Web Terminal (Node.js SSR frontend)
#   - Valkey (cache, data dir mounted from /mnt/data)
