# This defines the name of the workflow as it will appear in the "Actions" tab of the Gitea repository.
name: Production deployment

on:
  push:
    branches:
      - master

env:
  SSH_SERVER: "192.168.1.37"
  DOCKER_IMAGE_NAME: "jdrbot"

jobs:
  build:
    name: Build
    runs-on: ubuntu-latest

    steps:
      - name: Check out repo's default branch
        uses: actions/checkout@v3
      - name: Install Docker
        run: curl -fsSL https://get.docker.com | sh
      - name: Docker build
        run: |
          echo ${{ secrets.DOCKER_TOKEN }} | docker login gitea.skydust.fr -u ${{ secrets.DOCKER_USER }} --password-stdin
          docker build . -t gitea.skydust.fr/${{ secrets.DOCKER_USER }}/${{ env.DOCKER_IMAGE_NAME }}
          docker tag gitea.skydust.fr/${{ secrets.DOCKER_USER }}/${{ env.DOCKER_IMAGE_NAME }} gitea.skydust.fr/${{ secrets.DOCKER_USER }}/${{ env.DOCKER_IMAGE_NAME }}:latest
      - name: Docker push
        run: docker push gitea.skydust.fr/${{ secrets.DOCKER_USER }}/${{ env.DOCKER_IMAGE_NAME }}:latest

  deploy:
    name: Deploying
    runs-on: ubuntu-latest
    needs: build

    steps:
      - name: Check out repo's default branch
        uses: actions/checkout@v3
      - name: Setup the ssh key
        run: |
          mkdir ~/.ssh
          echo "${{ secrets.SSH_KEY }}" > ~/.ssh/ssh_key
          ssh-keyscan -t rsa ${{ env.SSH_SERVER }} >> ~/.ssh/known_hosts
          chmod 700 -R ~/.ssh
      - name: Deploying
        run: |
          ssh -i ~/.ssh/ssh_key ${{ secrets.SSH_USER }}@${{ env.SSH_SERVER }} << EOF
            echo ${{ secrets.DOCKER_TOKEN }} | docker login gitea.skydust.fr -u ${{ secrets.DOCKER_USER }} --password-stdin
            PREVIOUS_IMAGE=\$(docker inspect ${{ env.DOCKER_IMAGE_NAME }} --format "{{.Image}}")
            docker stop ${{ env.DOCKER_IMAGE_NAME }} || true
            docker rm ${{ env.DOCKER_IMAGE_NAME }} || true
            docker image rm \${PREVIOUS_IMAGE} || true
            docker pull gitea.skydust.fr/${{ secrets.DOCKER_USER }}/${{ env.DOCKER_IMAGE_NAME }}:latest
            docker run --restart=always -v /opt/JdrBot/Songs:/app/Songs -d --name="${{ env.DOCKER_IMAGE_NAME }}" gitea.skydust.fr/${{ secrets.DOCKER_USER }}/${{ env.DOCKER_IMAGE_NAME }}:latest
          EOF