// Build the NTP V2 image (API + web app), push it to the Docker registry, then have the production
// server pull that image and restart the container. Dockerfile: deploy/qa/Dockerfile (WEB_MODE=build:prod).
//
// Jenkins prerequisites
//   - Agent with Docker and ssh/scp (label below), user allowed to run docker.
//   - Credentials:
//       docker-registry  Username with password  (push access to the registry)
//       prod-ssh         SSH username with private key (user on the production server, able to run docker)
//   - On the production server: Docker + compose plugin, folder DEPLOY_DIR containing a filled-in .env
//     (copy of deploy/prod/.env.example). The pipeline copies docker-compose.yml there on every deploy.
pipeline {
    agent { label 'docker' }

    parameters {
        string(name: 'REGISTRY',    defaultValue: 'registry.nafith.net',   description: 'Docker registry host[:port]')
        string(name: 'IMAGE_REPO',  defaultValue: 'ntpv2',                 description: 'Repository/name inside the registry')
        string(name: 'PROD_HOST',   defaultValue: 'prod-server.nafith.net', description: 'Production server host or IP')
        string(name: 'DEPLOY_DIR',  defaultValue: '/opt/ntpv2',            description: 'Folder on the production server holding .env')
        booleanParam(name: 'DEPLOY', defaultValue: true, description: 'Deploy to production after pushing the image')
    }

    options {
        timestamps()
        disableConcurrentBuilds()
        buildDiscarder(logRotator(numToKeepStr: '20'))
        timeout(time: 45, unit: 'MINUTES')
    }

    environment {
        IMAGE = "${params.REGISTRY}/${params.IMAGE_REPO}"
        TAG   = "${env.BUILD_NUMBER}"
    }

    stages {
        stage('Checkout') {
            steps { checkout scm }
        }

        stage('Build image') {
            // Compiles the .NET API and the React app inside the Dockerfile (no SDKs needed on the agent).
            steps {
                sh '''
                    docker build \
                      -f deploy/qa/Dockerfile \
                      --build-arg WEB_MODE=build:prod \
                      -t "$IMAGE:$TAG" -t "$IMAGE:latest" .
                '''
            }
        }

        stage('Push image') {
            steps {
                withCredentials([usernamePassword(credentialsId: 'docker-registry', usernameVariable: 'REG_USER', passwordVariable: 'REG_PASS')]) {
                    sh '''
                        echo "$REG_PASS" | docker login "$REGISTRY" -u "$REG_USER" --password-stdin
                        docker push "$IMAGE:$TAG"
                        docker push "$IMAGE:latest"
                        docker logout "$REGISTRY"
                    '''
                }
            }
        }

        stage('Deploy to production') {
            when { expression { params.DEPLOY } }
            steps {
                // Manual gate; remove if every successful build should go straight to production.
                input message: "Deploy ${env.IMAGE}:${env.TAG} to ${params.PROD_HOST}?", ok: 'Deploy'
                withCredentials([
                    sshUserPrivateKey(credentialsId: 'prod-ssh', keyFileVariable: 'SSH_KEY', usernameVariable: 'SSH_USER'),
                    usernamePassword(credentialsId: 'docker-registry', usernameVariable: 'REG_USER', passwordVariable: 'REG_PASS')
                ]) {
                    sh '''
                        SSH_OPTS="-i $SSH_KEY -o StrictHostKeyChecking=accept-new"
                        TARGET="$SSH_USER@$PROD_HOST"

                        scp $SSH_OPTS deploy/prod/docker-compose.yml "$TARGET:$DEPLOY_DIR/docker-compose.yml"

                        # registry password goes over stdin so it never appears in a command line or the build log
                        echo "$REG_PASS" | ssh $SSH_OPTS "$TARGET" \
                          "docker login '$REGISTRY' -u '$REG_USER' --password-stdin \
                           && cd '$DEPLOY_DIR' \
                           && export NTP_IMAGE='$IMAGE:$TAG' \
                           && docker compose pull \
                           && docker compose up -d --no-build \
                           && docker image prune -f \
                           && docker logout '$REGISTRY'"
                    '''
                }
            }
        }

        stage('Smoke test') {
            when { expression { params.DEPLOY } }
            steps {
                withCredentials([sshUserPrivateKey(credentialsId: 'prod-ssh', keyFileVariable: 'SSH_KEY', usernameVariable: 'SSH_USER')]) {
                    // The container only listens on 127.0.0.1:8081 on the server, so check from there.
                    sh '''
                        ssh -i "$SSH_KEY" -o StrictHostKeyChecking=accept-new "$SSH_USER@$PROD_HOST" \
                          'for i in $(seq 1 15); do
                             code=$(curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:8081/) && [ "$code" -lt 500 ] && [ "$code" != 000 ] && exit 0
                             sleep 4
                           done
                           docker logs --tail 50 ntpv2-prod; exit 1'
                    '''
                }
            }
        }
    }

    post {
        success { echo "Deployed ${env.IMAGE}:${env.TAG}" }
        failure { echo 'Pipeline failed - see the stage log above.' }
        always  { sh 'docker image prune -f || true' }
    }
}
