name: main

on:
  push:
    branches: ["main"]
    paths-ignore: # 忽略的文件
      - "README.md"
      - "LICENSE"
      - "CHANGELOG.md"

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: home
  IMAGE_NAME_FULL: ghcr.io/nbtca/home

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Use Latest Corepack
        run: |
          echo "Before: corepack version => $(corepack --version || echo 'not installed')"
          npm install -g corepack@latest
          echo "After : corepack version => $(corepack --version)"
          corepack enable
          corepack prepare pnpm@latest --activate
          echo "pnpm version => $(pnpm --version || echo 'pnpm not installed')"

      - uses: docker/build-push-action@v6
        with:
          context: .
          file: ./Dockerfile
          no-cache: true
          platforms: linux/amd64
          tags: |
            ${{ env.IMAGE_NAME_FULL }}

  build-and-push:
    runs-on: ubuntu-latest
    needs: build
    steps:
      - uses: actions/checkout@v4

      - name: Use Latest Corepack
        run: |
          echo "Before: corepack version => $(corepack --version || echo 'not installed')"
          npm install -g corepack@latest
          echo "After : corepack version => $(corepack --version)"
          corepack enable
          corepack prepare pnpm@latest --activate
          echo "pnpm version => $(pnpm --version || echo 'pnpm not installed')"

      - name: Login
        uses: docker/login-action@v2
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and Push
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ./Dockerfile
          no-cache: true
          push: true
          platforms: linux/amd64
          tags: |
            ${{ env.IMAGE_NAME_FULL }}:${{ github.ref_name }}

      - name: Deploy
        uses: appleboy/ssh-action@v1.0.0
        env:
          BRANCH_NAME: ${{ github.ref_name }}
        with:
          host: ${{ secrets.REMOTE_HOST }}
          username: ${{ secrets.REMOTE_USER }}
          key: ${{ secrets.ACCESS_TOKEN }}
          envs: BRANCH_NAME
          script: |
            cd ${{secrets.REMOTE_PATH}}
            docker compose up --force-recreate -d --pull=always
