name: cicd

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

jobs:
  build_test_publish_deploy_test:
    runs-on: docker
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-dotnet@v4
        with:
          dotnet-version: "9.0.x"

      - name: Test
        run: dotnet test -c Release

      - name: Publish
        run: dotnet publish -c Release -o out

      - name: Install deploy tools
        run: |
          apt-get update
          apt-get install -y rsync openssh-client
          
      - name: Deploy TEST
        env:
          DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
          DEPLOY_USER: ${{ secrets.DEPLOY_USER }}
          DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
        run: |
          set -e
          mkdir -p ~/.ssh
          chmod 700 ~/.ssh
          echo "$DEPLOY_SSH_KEY" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          ssh-keyscan -H "$DEPLOY_HOST" >> ~/.ssh/known_hosts

          rsync -az --delete out/ "$DEPLOY_USER@$DEPLOY_HOST:/opt/minapp-test/app/"
          ssh "$DEPLOY_USER@$DEPLOY_HOST" "sudo systemctl restart minapp-test"

  deploy_prod_manual:
    if: ${{ github.event_name == 'workflow_dispatch' }}
    runs-on: docker
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-dotnet@v4
        with:
          dotnet-version: "8.0.x"

      - name: Publish
        run: dotnet publish -c Release -o out

      - name: Deploy PROD
        env:
          DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
          DEPLOY_USER: ${{ secrets.DEPLOY_USER }}
          DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
        run: |
          set -e
          mkdir -p ~/.ssh
          chmod 700 ~/.ssh
          echo "$DEPLOY_SSH_KEY" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          ssh-keyscan -H "$DEPLOY_HOST" >> ~/.ssh/known_hosts

          rsync -az --delete out/ "$DEPLOY_USER@$DEPLOY_HOST:/opt/minapp/app/"
          ssh "$DEPLOY_USER@$DEPLOY_HOST" "sudo systemctl restart minapp"
