stages:
  - deploy

variables:
  # The image will be built and run locally on the VPS using this tag
  IMAGE_TAG: $CI_COMMIT_SHORT_SHA 
  
  # Container Name 
  APP_NAME: {project_domain} 
  # Traefik Network on the VPS (use the name of your Traefik network)
  TRAEFIK_NETWORK: traefik_default 
  # The domain Traefik will route
  APP_DOMAIN: {project_domain} 

  COMPOSER_CACHE_DIR: "$CI_PROJECT_DIR/.composer_cache"

deploy_to_{project_domain}:
  stage: deploy

  environment:
    name: {project_domain}/$CI_COMMIT_SHORT_SHA # Displays the unique commit ID in the Environments page
    action: start
  
  tags:
    - uthavu_tag
  
  # The 'shell' executor runs commands directly on the host OS, 
  # which already has access to the host's Docker daemon.
  image: docker:25.0.0-cli # Use a minimal image since the shell executor handles the work.

  # We can keep the cache definition, as it still helps speed up the local build
  # by reusing files copied to the CI directory before the build starts.
  cache:
    key: "$CI_COMMIT_REF_SLUG" 
    paths:
      - vendor/
      - "$COMPOSER_CACHE_DIR" 
      - composer.lock 
    policy: pull-push 
  
  script:
    - echo "Deployment started directly on VPS host via shell executor..."
    
    # 1. BUILD (Executed on the VPS host's Docker engine)
    - mkdir -p "$COMPOSER_CACHE_DIR" # Ensures cache directory exists
    
    # Build the image directly on the VPS and tag it locally
    - docker build -t $APP_NAME:$IMAGE_TAG .

    # 2. DEPLOY (Executed on the VPS host)
    # Stop and remove the old container
    - docker stop $APP_NAME || true
    - docker rm $APP_NAME || true
    
    # Run the new container, exposing it via Traefik (HTTPS)
    - docker run -d --restart always --name $APP_NAME --network $TRAEFIK_NETWORK --label "traefik.enable=true" --label "traefik.http.routers.uthavu.rule=Host(\`$APP_DOMAIN\`)" --label "traefik.http.routers.uthavu.entrypoints=websecure" --label "traefik.http.routers.uthavu.tls.certresolver=le" --label "traefik.http.services.uthavu.loadbalancer.server.port=80" $APP_NAME:$IMAGE_TAG
    - echo "Deployment complete! $APP_NAME routed via Traefik HTTPS."
    
    # 3. Cleanup old images (optional but recommended)
    - docker image prune -a -f
  
  only:
    - main