name: Preview Deploy

on:
  push:
    branches: [ "main" ]
  workflow_dispatch: {}

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Build (optional)
        shell: bash
        run: |
          set -e
          DIST_DIR="."
          if [ -f package.json ]; then
            npm ci
            npm run build
            if [ -d dist ]; then DIST_DIR="dist"; fi
            if [ -d build ]; then DIST_DIR="build"; fi
          fi
          echo "DIST_DIR=$DIST_DIR" >> $GITHUB_ENV

      - name: Install rsync + ssh
        shell: bash
        run: |
          apt-get update
          apt-get install -y rsync openssh-client

      - name: Configure SSH key
        shell: bash
        run: |
          set -e
          mkdir -p ~/.ssh
          echo "${{ secrets.DEPLOY_KEY }}" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          ssh-keyscan -p "${{ secrets.DEPLOY_PORT }}" -H "${{ secrets.DEPLOY_HOST }}" >> ~/.ssh/known_hosts

      - name: Deploy to preview folder
        shell: bash
        run: |
          set -e

          # Repo-Name robust bestimmen:
          REPO_FULL="${GITHUB_REPOSITORY:-${GITEA_REPOSITORY:-}}"
          REPO_NAME="${REPO_FULL##*/}"
          if [ -z "$REPO_NAME" ]; then
            echo "ERROR: Could not determine repository name"
            exit 1
          fi

          TARGET="${{ secrets.PREVIEW_BASEDIR }}/${REPO_NAME}/"

          echo "Deploying to: $TARGET"
          ssh -p "${{ secrets.DEPLOY_PORT }}" "${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}" "mkdir -p '$TARGET'"
          rsync -az --delete -e "ssh -p ${{ secrets.DEPLOY_PORT }}" "${DIST_DIR}/" "${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}:${TARGET}"

          echo "Preview URL: https://preview.foryumedia.de/${REPO_NAME}/"