import { Storage , File } from '@google-cloud/storage' ; import { SecretManagerServiceClient } from '@google-cloud/secret-manager' ; import fs from 'fs' ; import config from './config' ; import { decrypt } from './decrypt-dump' ; const bucket = config . get ( 'gcloudBackupBucket' ) ; let storage ; async function listFiles ( ) { console . log ( 'Listing files...' ) ; const [ files ] = await storage . bucket ( bucket ) . getFiles ( ) ; console . log ( 'Files:' ) ; files . forEach ( ( file ) => { console . log ( file . name ) ; } ) ; return files ; } async function init ( ) { const secretClient = new SecretManagerServiceClient ( ) ; const secretResourceId = config . get ( 'gcloudBackupKeyResourceId' ) ; const [ secret ] = await secretClient . accessSecretVersion ( { name : secretResourceId , } ) ; if ( ! secret . payload ?. data ) { throw new Error ( 'Postman backup service account key secret not found!' ) ; } const serviceAccountKey = JSON . parse ( secret . payload ?. data ?. toString ( ) ) ; storage = new Storage ( { credentials : { client_email : serviceAccountKey . client_email , private_key : serviceAccountKey . private_key , } , } ) ; } async function downloadFile ( srcFilename ) { const [ dumpVersion , dumpFilename ] = srcFilename . split ( '/' ) ; fs . writeFileSync ( 'dump-version.txt' , dumpVersion ) ; const options = { destination : dumpFilename , } ; console . log ( 'Downloading file' , srcFilename ) ; await storage . bucket ( bucket ) . file ( srcFilename ) . download ( options ) ; console . log ( `gs://${ bucket }/${ srcFilename } downloaded.` ) ; } async function getLatestBackup ( files ) { await Promise . all ( files . slice ( - 3 ) . map ( ( file ) => downloadFile ( file . name ) ) ) ; } async function run ( ) { try { await init ( ) ; const files = await listFiles ( ) ; await getLatestBackup ( files ) ; await decrypt ( ) ; } catch ( error ) { console . log ( error ) ; } } run ( ) ;