name: Build and Deploy Container

on:
  push:
    branches:
      - main
      - develop

env: # global: unkritische, strukturgebende Variablen
  TARGET_HOST: host.containers.internal
  TARGET_USER: traefik
  APP_DIR: /home/traefik/valtrix-website
  CONTAINER_NAME: valtrix-website
  QUADLET_FILE: ./deploy/valtrix-website.container

jobs:
  build_and_deploy:
    runs-on: ubuntu-latest
    env: # Job-spezifisch: Secrets und sensible Werte
      SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
      SSH_KNOWN_HOSTS: ${{ secrets.SSH_KNOWN_HOSTS }}

    steps:
      - name: Pre-clean Git global config (avoid https→ssh rewrite)
        shell: bash
        run: |
          set -euo pipefail
          echo "Cleaning up global git config"
          git config --global --unset-all core.sshCommand || true
          for key in $(git config --global --get-regexp '^url\\..*\\.insteadof$' 2>/dev/null | awk '{print $1}'); do
            if echo "$key" | grep -qi 'gitea\\.smb-corp\\.de'; then
              git config --global --unset-all "$key" || true
            fi
          done

      - name: Setup SSH for git/scp
        shell: bash
        run: |
          install -m 700 -d ~/.ssh
          printf "%s\n" "$SSH_PRIVATE_KEY" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          printf "%s\n" "$SSH_KNOWN_HOSTS" > ~/.ssh/known_hosts || true
          chmod 644 ~/.ssh/known_hosts
          # Ensure host keys exist
          (ssh-keygen -F "$TARGET_HOST" >/dev/null || ssh-keyscan -H "$TARGET_HOST" >> ~/.ssh/known_hosts) || true
          (ssh-keygen -F gitea.smb-corp.de >/dev/null || ssh-keyscan -H gitea.smb-corp.de >> ~/.ssh/known_hosts) || true

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

      - name: Copy repository to target host (atomic replace)
        shell: bash
        run: |
          set -euo pipefail
          TMP_DIR="$APP_DIR.tmp.$(date +%s)"
          ssh -i ~/.ssh/id_ed25519 $TARGET_USER@$TARGET_HOST "mkdir -p '$TMP_DIR'"
          scp -r -i ~/.ssh/id_ed25519 ./* $TARGET_USER@$TARGET_HOST:$TMP_DIR/
          ssh -i ~/.ssh/id_ed25519 $TARGET_USER@$TARGET_HOST "
            set -euo pipefail;
            if [ -d '$APP_DIR' ]; then rm -rf '$APP_DIR'; fi;
            mv '$TMP_DIR' '$APP_DIR'
          "

      - name: Build container on target host
        shell: bash
        run: |
          ssh -i ~/.ssh/id_ed25519 $TARGET_USER@$TARGET_HOST "
            set -euo pipefail
            export APP_DIR='$APP_DIR' CONTAINER_NAME='$CONTAINER_NAME'
            cd \"\$APP_DIR\"
            echo 'Building container: '\$CONTAINER_NAME 'in' \$APP_DIR
            podman build -t \$CONTAINER_NAME:latest .
          "

      - name: Backup existing Quadlet file
        shell: bash
        run: |
          ssh -i ~/.ssh/id_ed25519 $TARGET_USER@$TARGET_HOST "
            set -euo pipefail
            export CONTAINER_NAME='$CONTAINER_NAME'
            QFILE=~/.config/containers/systemd/\$CONTAINER_NAME.container
            test -f \"\$QFILE\" && cp \"\$QFILE\" \"\$QFILE.bak\" || true
          "

      - name: Replace Quadlet file and restart service
        shell: bash
        run: |
          scp -i ~/.ssh/id_ed25519 "$QUADLET_FILE" $TARGET_USER@$TARGET_HOST:~/.config/containers/systemd/
          ssh -i ~/.ssh/id_ed25519 $TARGET_USER@$TARGET_HOST "
            set -euo pipefail
            export CONTAINER_NAME='$CONTAINER_NAME'
            systemctl --user daemon-reload
            systemctl --user restart \$CONTAINER_NAME.service
            echo 'Service restarted: '\$CONTAINER_NAME
          "

      - name: Verify deployment
        shell: bash
        run: |
          ssh -i ~/.ssh/id_ed25519 $TARGET_USER@$TARGET_HOST "
            set -euo pipefail
            export CONTAINER_NAME='$CONTAINER_NAME'
            echo 'Running containers:'
            podman ps --filter \"name=\$CONTAINER_NAME\" --format \"table {{.Names}}\t{{.Image}}\t{{.Status}}\"
            echo '--- Last 20 log lines ---'
            podman logs \$CONTAINER_NAME --tail 20 || echo 'No logs available'
          "