#!/bin/bash
# Script para configurar o Forgejo Runner
# Execute na VPS apos o Forgejo estar rodando

set -e

FORGEJO_URL="${FORGEJO_URL:-https://git.esdrasrenan.com.br}"
RUNNER_NAME="${RUNNER_NAME:-vps-runner}"
RUNNER_DIR="/srv/forgejo-runner"
CONFIG_FILE="$RUNNER_DIR/config.yml"

echo "=== Configuracao do Forgejo Runner ==="
echo ""
echo "1. Acesse o Forgejo: $FORGEJO_URL"
echo "2. Va em: Site Administration > Actions > Runners"
echo "3. Clique em 'Create new Runner'"
echo "4. Copie o token de registro"
echo ""
read -p "Cole o token de registro aqui: " REGISTRATION_TOKEN

if [ -z "$REGISTRATION_TOKEN" ]; then
    echo "ERRO: Token nao pode ser vazio"
    exit 1
fi

# Criar diretorio do runner
mkdir -p "$RUNNER_DIR"
cd "$RUNNER_DIR"

# Baixar o runner se nao existir
if [ ! -f "./forgejo-runner" ]; then
    echo "Baixando Forgejo Runner..."
    RUNNER_VERSION="6.2.2"
    curl -L -o forgejo-runner "https://code.forgejo.org/forgejo/runner/releases/download/v${RUNNER_VERSION}/forgejo-runner-${RUNNER_VERSION}-linux-amd64"
    chmod +x forgejo-runner
fi

# Registrar o runner
echo "Registrando runner..."
./forgejo-runner register \
    --instance "$FORGEJO_URL" \
    --token "$REGISTRATION_TOKEN" \
    --name "$RUNNER_NAME" \
    --labels "ubuntu-latest:docker://node:20-bookworm,self-hosted:host,linux:host,vps:host" \
    --no-interactive

# Criar config.yml customizado
cat > "$CONFIG_FILE" << 'EOF'
log:
  level: info

runner:
  file: .runner
  capacity: 2
  timeout: 3h
  insecure: false
  fetch_timeout: 5s
  fetch_interval: 2s
  labels:
    - "ubuntu-latest:docker://node:20-bookworm"
    - "self-hosted:host"
    - "linux:host"
    - "vps:host"

cache:
  enabled: true
  dir: /tmp/forgejo-runner-cache
  host: ""
  port: 0
  external_server: ""

container:
  network: "host"
  privileged: false
  options: ""
  workdir_parent: /tmp/forgejo-runner-workdir
  valid_volumes:
    - /var/run/docker.sock
    - /home/runner/apps
    - /srv/apps
    - /tmp
  docker_host: ""
  force_pull: false

host:
  workdir_parent: /tmp/forgejo-runner-workdir
EOF

echo ""
echo "=== Runner registrado com sucesso! ==="
echo ""
echo "Para iniciar o runner como servico systemd, execute:"
echo ""
echo "sudo tee /etc/systemd/system/forgejo-runner.service << 'SYSTEMD'
[Unit]
Description=Forgejo Runner
After=docker.service network.target

[Service]
Type=simple
User=runner
WorkingDirectory=$RUNNER_DIR
ExecStart=$RUNNER_DIR/forgejo-runner daemon --config $CONFIG_FILE
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
SYSTEMD"
echo ""
echo "sudo systemctl daemon-reload"
echo "sudo systemctl enable forgejo-runner"
echo "sudo systemctl start forgejo-runner"
