pipeline {
    agent any

    parameters {
        choice(name: 'USER_NAME', choices: ['lucas', 'interstices'], description: 'Quelle instance déployer ?')
    }

    environment {
        SSH_TARGET = "57.129.77.192"
        SSH_PORT   = "34567"
        SSH_USER   = "lucas"

        GITEA_REPO_PATH = "lucas/vaultwarden"
        GITEA_API_URL = "https://gitea.lucasroyer.fr/api/v1"
        BASE_DIR = "/home/lucas/services/vaultwarden/${params.USER_NAME}"
    }

    stages {
        stage('Check git...') {
            steps {
                checkout scm
            }
        }
        stage('Deploy') {
            steps {
                withCredentials([
                    sshUserPrivateKey(credentialsId: 'jenkins-ssh-key', keyFileVariable: 'SSH_KEY'),
                    file(credentialsId: "vaultwarden-app-env-${params.USER_NAME}", variable: 'SECRET_ENV')
                ]) {
                    script {
                        echo "Deploying Vaultwarden for ${params.USER_NAME}..."

                        // SSH commands
                        def commonSsh = "ssh -4 -p ${env.SSH_PORT} -i ${SSH_KEY} -o StrictHostKeyChecking=no ${env.SSH_USER}@${env.SSH_TARGET}"
                        def commonScp = "scp -4 -P ${env.SSH_PORT} -i ${SSH_KEY} -o StrictHostKeyChecking=no"
                        
                        // Prepare folder
                        sh "${commonSsh} 'mkdir -p ${env.BASE_DIR}/vw-data'"
                        
                        // Send files
                        sh "${commonScp} docker-compose.yml ${env.SSH_USER}@${env.SSH_TARGET}:${env.BASE_DIR}/docker-compose.yml"
                        sh "${commonScp} ${SECRET_ENV} ${env.SSH_USER}@${env.SSH_TARGET}:${env.BASE_DIR}/app.env"
                        
                        // Run
                        sh """
                            ${commonSsh} "cd ${env.BASE_DIR} && docker compose -p vw-${params.USER_NAME} up -d --force-recreate --remove-orphans"
                        """
                        }
                    }
                }
            }
        }
    }

    post {
        always {
            script {
                echo "Send Gitea check..."
                // Get and store SHA
                def commitSha = sh(script: 'git rev-parse HEAD', returnStdout: true).trim()
                
                // Convert from Jenkins to Gitea API
                def buildState = (currentBuild.currentResult == 'SUCCESS') ? 'success' : 'failure'
                def buildDesc  = (currentBuild.currentResult == 'SUCCESS') ? 'Build successful' : 'Build failed'

                // Send it to Gitea API with secret 'gitea-token'
                withCredentials([string(credentialsId: 'gitea-token', variable: 'GITEA_TOKEN')]) {
                    // Use \$TOKEN to avoid jenkins to print token in logs
                    sh """
                        curl -f -X POST "${GITEA_API_URL}/repos/${GITEA_REPO_PATH}/statuses/${commitSha}" \
                             -H "Authorization: token \$GITEA_TOKEN" \
                             -H "Content-Type: application/json" \
                             -d '{"state": "${buildState}", "target_url": "${env.BUILD_URL}", "description": "${buildDesc}", "context": "jenkins-ci"}'
                    """
                }
            }
            echo "Clean unused image..."
            sh "docker image prune -f"
        }
        success { echo "Success !" }
        failure { echo "Failed." }
    }
}