name: Build and Deploy Container

env:
  TARGET_HOST: www.valtrix.systems
  TARGET_USER: traefik
  APP_DIR: /home/traefik/valtrix-website
  CONTAINER_NAME: valtrix-website
  QUADLET_FILE: valtrix-website.container
  SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
  SSH_KNOWN_HOSTS: ${{ secrets.SSH_KNOWN_HOSTS }}

on:
  push:
    branches:
      - main
      - develop

jobs:
  build_and_deploy:
    runs-on: linux
    container:
      image: ubuntu:latest
      options: --entrypoint /bin/sh
    steps:
      - name: Install tools
        run: |
          apt-get update
          apt-get install -y bash git openssh-client rsync podman-cli
      - name: Checkout repository
        run: git clone git@gitea.smb-corp.de:${{ gitea.repository }} .
      - name: Deploy via SSH
        run: |
          rsync -az --delete ./ $TARGET_USER@$TARGET_HOST:$APP_DIR/
#      - name: Checkout repository from local Gitea
#        run: |
#          git clone http://gitea:3000/${{ gitea.repository }} .
#          git checkout $GITEA_REF_NAME
#      - name: Checkout Repository
#        uses: actions/checkout@v4
#          rsync -az --delete ./ $TARGET_USER@$TARGET_HOST:$APP_DIR/

#      - name: Copy code to target host
#        run: |
#          scp -r ./ $TARGET_USER@$TARGET_HOST:$APP_DIR/

      - name: Build container on target host
        run: |
          ssh $TARGET_USER@$TARGET_HOST '
            cd $APP_DIR
            podman build -t $CONTAINER_NAME:latest .
          '

      - name: Backup Quadlet file
        run: |
          ssh $TARGET_USER@$TARGET_HOST '
            cp ~/.config/containers/systemd/$CONTAINER_NAME.container ~/.config/containers/systemd/$CONTAINER_NAME.container.bak
          '

      - name: Replace Quadlet file
        run: |
          scp ./$QUADLET_FILE $TARGET_USER@$TARGET_HOST:~/.config/containers/systemd/
          ssh $TARGET_USER@$TARGET_HOST '
            systemctl --user daemon-reload
            systemctl --user restart $CONTAINER_NAME.service
          '