stages:
  - build
  - deploy

variables:
  # Das ist der Name deines Images in der GitLab Registry
  IMAGE_NAME: $CI_REGISTRY_IMAGE:latest

build_image:
  stage: build
  image: docker:24.0.5
  services:
    - docker:24.0.5-dind
  before_script:
    # Login in die GitLab-eigene Registry
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
  script:
    # Bauen und Hochladen des Images
    - docker build -t $IMAGE_NAME .
    - docker push $IMAGE_NAME

deploy_to_k3s:
  stage: deploy
  image: alpine:latest
  before_script:
    # SSH-Client installieren und Key vorbereiten
    - apk add --no-cache openssh-client
    - mkdir -p ~/.ssh
    # Wir nutzen die Variable SSH_PRIVATE_KEY, die wir in GitLab hinterlegt haben
    - if [ -z "$SSH_PRIVATE_KEY" ]; then echo "FEHLER - Variable SSH_PRIVATE_KEY ist leer!"; exit 1; fi
    - cp "$SSH_PRIVATE_KEY" ~/.ssh/id_ed25519
    - chmod 600 ~/.ssh/id_ed25519
    # Verhindert die Abfrage "Are you sure you want to continue connecting"
    - echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
  script:
    # Den Server anweisen, das Deployment neu zu starten
    - ssh $SERVER_USER@$SERVER_IP "kubectl rollout restart deployment/klausfriese-web"
  only:
    - main
