import * as chalk from 'chalk' ; import { concat , fromEvent , defer } from 'rxjs' ; import { takeWhile , mergeMap } from 'rxjs/operators' ; import { OutputType , stdout , spawnShell } from '@machinelabs/core' ; import { factory } from './execute' ; import * as fs from 'fs' ; import * as pty from 'node-pty' ; import { isRootDir } from './is-root-dir' ; import { failWith } from './fail-with' ; import { processify } from './processify' ; export function deployServer ( project , serverName , zone , env ) { if ( ! isRootDir ( ) ) { failWith ( 'Command needs to be run from root dir' ) ; } return concat ( stdout ( chalk . green ( 'Deploying server' ) ) , spawnShell ( `(cd ./server && npm run node_modules && npm run build -- --env=${ env })` ) , processify ( ( ) => { if ( ! fs . existsSync ( './server/dist' ) ) { console . log ( chalk . red ( 'Dist does not exist. Aborting' ) ) ; process . exit ( 1 ) ; } } ) , stdout ( chalk . green ( 'Zipping files for better performance' ) ) , spawnShell ( `tar -h -zcf machinelabs-server.tar.gz ./server` ) , stdout ( chalk . green ( 'Transferring files to server' ) ) , copyServer ( serverName , project , zone ) , stdout ( chalk . green ( 'Unzipping and restarting services' ) ) , spawnShell ( `gcloud compute --project "${ project }" ssh --zone "${ zone }" "root@${ serverName }" --command "cd /var && tar -zxf machinelabs-server.tar.gz && rm -rf machinelabs-server && mv server machinelabs-server && pm2 restart all"` ) , stdout ( chalk . green ( 'Cleaning up' ) ) , spawnShell ( `rm -rf ./machinelabs-server.tar.gz` ) , stdout ( chalk . green ( 'Server successfully deployed' ) ) ) ; } const copyServer = ( serverName , project , zone ) => { const endOfProcessIndicator = 'a1c80580-1505-4555-814c-301b1c5fff98' ; return defer ( ( ) => { const term = pty . spawn ( `/bin/bash` , [ '-c' , `gcloud compute copy-files ./machinelabs-server.tar.gz root@${ serverName }:/var/machinelabs-server.tar.gz --project "${ project }" --zone "${ zone }"; echo ${ endOfProcessIndicator }` ] , { name : 'xterm-color' , cols : 80 , rows : 30 , cwd : process . cwd ( ) , env : process . env } ) ; return fromEvent ( term , 'data' ) . pipe ( takeWhile ( ( data ) => ! data . trim ( ) . endsWith ( endOfProcessIndicator ) ) , mergeMap ( ( data ) => stdout ( data ) ) ) ; } ) ; } ;