#!/bin/bash
# Gitea Act Runner 자동 설치 — Synology NAS (armv7l / x86_64 / arm64)

GITEA_URL="http://192.168.123.100:8418"
REG_TOKEN="Kj6L43zdWKZdTtqFswN0PYFWRHkdUChxG8yIfr8L"
RUNNER_NAME="synology-runner"
RUNNER_DIR="/volume1/gitea/act_runner"
ACT_RUNNER_VERSION="0.2.11"

echo "=== Gitea Act Runner Setup ==="

# 1. 아키텍처 감지
ARCH=$(uname -m)
case "$ARCH" in
  x86_64)  BINARY="act_runner-${ACT_RUNNER_VERSION}-linux-amd64" ;;
  aarch64) BINARY="act_runner-${ACT_RUNNER_VERSION}-linux-arm64" ;;
  armv7l)  BINARY="act_runner-${ACT_RUNNER_VERSION}-linux-arm-7" ;;
  *)       echo "ERROR: 지원하지 않는 아키텍처: $ARCH"; exit 1 ;;
esac
echo "[1] 아키텍처: $ARCH -> $BINARY"

# 2. 설치 디렉토리 생성
mkdir -p "$RUNNER_DIR/workspace"
echo "[2] 디렉토리: $RUNNER_DIR"

# 3. 바이너리 다운로드
DOWNLOAD_URL="https://gitea.com/gitea/act_runner/releases/download/v${ACT_RUNNER_VERSION}/${BINARY}"
echo "[3] 다운로드: $DOWNLOAD_URL"
curl -L --progress-bar "$DOWNLOAD_URL" -o "$RUNNER_DIR/act_runner"
chmod +x "$RUNNER_DIR/act_runner"
echo "[3] 완료: $("$RUNNER_DIR/act_runner" --version 2>&1 | head -1)"

# 4. config.yaml 생성
cat > "$RUNNER_DIR/config.yaml" <<YAML
runner:
  name: ${RUNNER_NAME}
  labels:
    - "self-hosted:host"
    - "linux:host"

container:
  network: host
  docker_host: "-"

host:
  workdir_parent: ${RUNNER_DIR}/workspace
YAML
echo "[4] config.yaml 생성"

# 5. Runner 등록
echo "[5] Runner 등록..."
"$RUNNER_DIR/act_runner" register \
  --no-interactive \
  --instance "$GITEA_URL" \
  --token "$REG_TOKEN" \
  --name "$RUNNER_NAME" \
  --labels "self-hosted,linux" \
  --config "$RUNNER_DIR/config.yaml"
echo "[5] 등록 완료"

# 6. 부팅 시작 스크립트
cat > "$RUNNER_DIR/start.sh" <<'SH'
#!/bin/bash
RUNNER_DIR="/volume1/gitea/act_runner"
PID_FILE="$RUNNER_DIR/runner.pid"
LOG="$RUNNER_DIR/runner.log"
if [ -f "$PID_FILE" ] && kill -0 $(cat "$PID_FILE") 2>/dev/null; then
  echo "already running pid=$(cat $PID_FILE)"
  exit 0
fi
nohup "$RUNNER_DIR/act_runner" daemon --config "$RUNNER_DIR/config.yaml" >> "$LOG" 2>&1 &
echo $! > "$PID_FILE"
echo "started pid=$!"
SH
chmod +x "$RUNNER_DIR/start.sh"
echo "[6] start.sh 생성"

# 7. 즉시 시작
echo "[7] Runner 시작..."
"$RUNNER_DIR/start.sh"
sleep 3
echo "[7] PID: $(cat $RUNNER_DIR/runner.pid 2>/dev/null || echo 'N/A')"

echo ""
echo "=== 설치 완료 ==="
echo "DSM 작업 스케줄러 → 부팅 트리거 → 명령: bash ${RUNNER_DIR}/start.sh"
echo "Gitea 확인: ${GITEA_URL}/KimJaeHyun/myfinance/settings/runners"
