name: setup-deploy-ssh
description: |
  配置 deploy SSH —— 把 private key 写到 ~/.ssh/deploy_key（mode 600），
  把指定 host 列表 ssh-keyscan 到 ~/.ssh/known_hosts，并把统一的 ssh 选项串
  暴露到 $GITEA_ENV，调用方用 `ssh $DEPLOY_SSH_OPTS user@host` 直接拼。

  暴露的环境变量（同 job 内后续 step 可见）：
    DEPLOY_SSH_KEY_PATH    private key 路径，如 /home/runner/.ssh/deploy_key
    DEPLOY_SSH_HOSTKEY_ALGOS  HostKeyAlgorithms 串
    DEPLOY_SSH_OPTS        完整 ssh 选项串：-i <path> -o StrictHostKeyChecking=accept-new -o HostKeyAlgorithms=...

  HostKeyAlgorithms 串的存在原因：runner 默认 prefer sk-* FIDO 类型 host key，跟目标 sshd
  不匹配时 negotiate 失败 → ssh client 卡 CLOSE_WAIT。详见 #273 评论 5。

inputs:
  ssh_key:
    description: 'Private SSH key (PEM content)'
    required: true
  hosts:
    description: 'Space-separated host list (用于 ssh-keyscan)'
    required: true

runs:
  using: composite
  steps:
    - name: Write key + scan host fingerprints + export ssh opts
      shell: bash
      env:
        DEPLOY_SSH_KEY: ${{ inputs.ssh_key }}
        DEPLOY_HOSTS: ${{ inputs.hosts }}
      run: |
        mkdir -p ~/.ssh
        DEPLOY_KEY_PATH="$HOME/.ssh/deploy_key"
        echo "$DEPLOY_SSH_KEY" > "$DEPLOY_KEY_PATH"
        chmod 600 "$DEPLOY_KEY_PATH"
        # ssh-keyscan -H 接受多个 host 一次性扫，输出哈希形式的 host key
        # -t rsa,ecdsa,ed25519 排除 sk-* FIDO 硬件 key（部分 runner 默认装的 FIDO 类型跟
        # 目标 sshd 不匹配会让 negotiate 失败、ssh client 卡死 CLOSE_WAIT，详见 #273 评论 5）
        # 2>/dev/null 屏蔽 keyscan 输出到 stderr 的 banner 行
        ssh-keyscan -H -t rsa,ecdsa,ed25519 $DEPLOY_HOSTS >> ~/.ssh/known_hosts 2>/dev/null

        HOSTKEY_ALGOS="ssh-ed25519,ecdsa-sha2-nistp256,rsa-sha2-512,rsa-sha2-256,ssh-rsa"
        SSH_OPTS="-i ${DEPLOY_KEY_PATH} -o StrictHostKeyChecking=accept-new -o HostKeyAlgorithms=${HOSTKEY_ALGOS}"

        # 用 GITEA_ENV / GITHUB_ENV 把变量暴露给后续 step（兼容两者）
        ENV_FILE="${GITEA_ENV:-${GITHUB_ENV:-}}"
        if [[ -n "$ENV_FILE" ]]; then
          {
            echo "DEPLOY_SSH_KEY_PATH=${DEPLOY_KEY_PATH}"
            echo "DEPLOY_SSH_HOSTKEY_ALGOS=${HOSTKEY_ALGOS}"
            echo "DEPLOY_SSH_OPTS=${SSH_OPTS}"
          } >> "$ENV_FILE"
        else
          echo "warn: GITEA_ENV / GITHUB_ENV 都没设，DEPLOY_SSH_OPTS 不会暴露给后续 step" >&2
        fi
