image: maven:3.9-eclipse-temurin-17

definitions:
  steps:
    - step: &build-jar
        name: Build JAR
        script:
          - chmod +x ./mvnw
          - ./mvnw install:install-file -Dfile=lib/fonts.jar -DgroupId=net -DartifactId=custom-fonts-extension -Dversion=1 -Dpackaging=jar
          - ./mvnw clean package -DskipTests
        artifacts:
          - target/ReporteJasperSpringBoot-1-0.0.1-SNAPSHOT.jar
    
    - step: &deploy-to-server
        name: Deploy to Server
        deployment: production
        script:
          # Instalar dependencias SSH
          - apt-get update && apt-get install -y openssh-client
          # Configurar SSH known_hosts
          - mkdir -p ~/.ssh
          - ssh-keyscan -H $SSH_HOST >> ~/.ssh/known_hosts
          # Crear directorio en el servidor si no existe
          - ssh -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no $SSH_USER@$SSH_HOST "mkdir -p $DEPLOY_PATH"
          # Subir carpeta reports con todos los reportes compilados
          - scp -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no -r reports $SSH_USER@$SSH_HOST:$DEPLOY_PATH/
          # Subir JAR al servidor
          - scp -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no target/ReporteJasperSpringBoot-1-0.0.1-SNAPSHOT.jar $SSH_USER@$SSH_HOST:$DEPLOY_PATH/
          # Reiniciar servicio systemd PRODUCCION (si falla, el pipeline falla)
          - ssh -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no $SSH_USER@$SSH_HOST "systemctl restart $SERVICE_NAME || { echo 'Service production not found, failing pipeline'; exit 1; }"
          # Reiniciar servicio systemd DEVELOPMENT (si falla, el pipeline falla)
          - ssh -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no $SSH_USER@$SSH_HOST "systemctl restart $SERVICE_NAME_DEVELOPMENT || { echo 'Service development not found, failing pipeline'; exit 1; }"

pipelines:
  custom:
    build-jar:
      - step: *build-jar
    
    build-and-deploy:
      - step: *build-jar
      - step: *deploy-to-server

