const path = require('path')

let appLoc = path.join(..._program.split('services')[0].split('/'))
let licenceKey = ''
let activationKey = ''

let writeError = 0

if (_WEBIN_FILEREF1) {
    const fileText = _WEBIN_FILEREF1.toString()
    const split = fileText.split('\n')[1].split(',')
    activationKey = split[0]
    licenceKey = split[1]
}

const sessionStoragePath = path.resolve(__dirname, '..', '..', 'drive', 'files', appLoc, 'mock-storage')

if (!fs.existsSync(sessionStoragePath)){
    fs.mkdirSync(sessionStoragePath);
}

const licenceStore = path.resolve(sessionStoragePath, 'licence.json')

const json = {
    licenceKey: licenceKey,
    activationKey: activationKey
}

try {
    fs.writeFileSync(licenceStore, JSON.stringify(json))
} catch (err) {
    writeError = 1
}

if (writeError) {
    _webout = `{ "return": [{ "MSG": "Error writing licence file" }] }`
} else {
    _webout = `{ "return": [{ "MSG": "SUCCESS" }] }`
}