#!/bin/groovy
/* groovylint-disable CompileStatic, DuplicateStringLiteral, LineLength */
pipeline {
    agent {
        docker {
            alwaysPull true
            image 'alpine:3.14'
            label 'Wrangler1'
            args '-u root'
        }
    }

    stages {
        stage('Prepare Environment') {
            steps {
                sh '#!/bin/sh \n' +
                   'id; apk add docker openrc git'
            }
        }
        stage('Obtain Source') {
            steps {
                git branch: 'main', url: 'https://git.adamoutler.com/aoutler/aidgaf-server.git'
            }
        }
        stage('Build in docker') {
            steps {
                // Get some code from a Git repository
                sh '#!/bin/sh \n' +
                   'docker build -t aidgaf .'
            }
        }
        stage('setup credentials') {
            steps {
                withCredentials([ sshUserPrivateKey(credentialsId: 'dockeruserOn192.168.1.115', keyFileVariable: 'sshkey', usernameVariable: 'user')]) {
                    sh '#!/bin/sh \n' +
                        'set +e; docker logs aidgaf-server; docker stop aidgaf-server||echo machine stopped; docker rm aidgaf-server||echo machine does not exist; set -e'
                }
            }
        }
        stage('export docker container') {
            steps {
                sh '#!/bin/sh \n' +
                   'set +e; docker stop aidgaf-server||echo machine stopped; docker rm aidgaf-server||echo machine does not exist; set -e'
                withCredentials([
                    string(credentialsId: 'OpenAI-API-Token', variable: 'OPEN_AI_TOKEN'),
                    string(credentialsId: 'PapaHashingSecret', variable: 'PAPA_HASH'),
                    string(credentialsId: 'PapaAsyncUrl', variable: 'ASYNC_URL'),
                    sshUserPrivateKey(credentialsId: 'dockeruserOn192.168.1.115', keyFileVariable: 'sshkey')]) {
                    sh '#!/bin/sh \n' +
                        'mkdir -p ~/.ssh; cp "$sshkey" ~/.ssh/id_rsa'
                    sh '#!/bin/sh \n' +
                        /* groovylint-disable-next-line GStringExpressionWithinString */
                        'docker run --name=aidgaf-server -eSERVERPORT=8087 -eHOSTNAME=0.0.0.0 -eHASHKEY="${PAPA_HASH}" -eAPIKEY="${OPEN_AI_TOKEN}" -eASYNC_METHOD="PATCH" -eASYNC_URL="${ASYNC_URL}" -p8087:8087 -d --restart=always  aidgaf'
                }
            }
        }
    }
}