# .gitlab-ci.yaml

# Define the default image to be used for all jobs.
# This image should have bash and rsync/ssh client available.
image: alpine/git:latest

# Define stages for the pipeline.
# 'deploy' is the main stage responsible for deployment.
stages:
  - deploy

# Define the 'deploy_website' job.
deploy_website:
  stage: deploy
  tags:
    - jmp-site
  # Only run this job when changes are pushed to the 'main' branch.
  only:
    - main

  # Define variables required for SSH connection and deployment path.
  variables:
    # Replace with your actual SSH user for the target server.
    SSH_USER: "root"
    # Replace with the IP address or hostname of your target server.
    # If the GitLab Runner is on the same machine as /var/www/jmpgames.it,
    # you can use 'localhost' or '127.0.0.1'.
    SSH_HOST: "localhost"
    # The absolute path on the target server where the website files will be deployed.
    DEPLOY_PATH: "/var/www/jmpgames.it"
    # The local path within the GitLab Runner's working directory where your website files are located.
    # Assuming your website files are in the root of your repository.
    WEBSITE_SOURCE_PATH: "./"

  # Before the script runs, ensure SSH key is added and permissions are set.
  before_script:
    # Ensure the .ssh directory exists with correct permissions.
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh

    # Add the private SSH key. SSH_PRIVATE_KEY should be a CI/CD variable
    # configured in GitLab with your deployment key.
    # Make sure this variable is "masked" and "protected".
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_rsa
    - chmod 600 ~/.ssh/id_rsa

    # Add your server's host key to known_hosts to avoid host key checking prompts.
    # This is crucial for non-interactive scripts.
    # Replace with your server's actual public host key.
    # You can get it by running `ssh-keyscan your_server_ip_or_hostname` on your local machine.
    - ssh-keyscan "$SSH_HOST" >> ~/.ssh/known_hosts
    - chmod 644 ~/.ssh/known_hosts

  # The main script to execute for deployment.
  script:
    # Use rsync to synchronize files from the GitLab Runner to the target server.
    # -a: archive mode (preserves permissions, ownership, timestamps, recursive)
    # -v: verbose output
    # -z: compress file data during the transfer
    # --delete: delete extraneous files from dest dirs (DANGER: USE WITH CAUTION!)
    #           Only use if you want to ensure the target directory exactly mirrors the source.
    #           Otherwise, remove this flag.
    - rsync -avz --delete $WEBSITE_SOURCE_PATH $SSH_USER@$SSH_HOST:$DEPLOY_PATH

  # Define what happens if the job succeeds or fails.
  after_script:
    # Optional: Clean up the SSH key from the runner's environment for security.
    - rm -f ~/.ssh/id_rsa
