const fs = require('fs')
const path = require('path')
const COS = require('cos-nodejs-sdk-v5')

const root = path.join(__dirname, '..', 'dist', 'build', 'h5')
const serverEnv = path.join(__dirname, '..', '..', 'server', '.env')

if (fs.existsSync(serverEnv)) {
  require('dotenv').config({ path: serverEnv })
}

const bucket = process.env.COS_BUCKET
const region = process.env.COS_REGION || process.env.TENCENT_REGION
const secretId = process.env.TENCENT_SECRET_ID
const secretKey = process.env.TENCENT_SECRET_KEY
const prefix = process.env.ADMIN_COS_PREFIX || 'admin/'

if (!bucket || !region || !secretId || !secretKey) {
  console.error('COS_BUCKET, COS_REGION, TENCENT_SECRET_ID and TENCENT_SECRET_KEY are required')
  process.exit(1)
}

if (!fs.existsSync(root)) {
  console.error('Build output not found: ' + root)
  process.exit(1)
}

const cos = new COS({ SecretId: secretId, SecretKey: secretKey })

function walk(dir) {
  const files = []
  fs.readdirSync(dir).forEach(name => {
    const file = path.join(dir, name)
    const stat = fs.statSync(file)
    if (stat.isDirectory()) files.push.apply(files, walk(file))
    else files.push(file)
  })
  return files
}

function contentType(file) {
  if (file.endsWith('.html')) return 'text/html; charset=utf-8'
  if (file.endsWith('.js')) return 'application/javascript; charset=utf-8'
  if (file.endsWith('.css')) return 'text/css; charset=utf-8'
  if (file.endsWith('.json')) return 'application/json; charset=utf-8'
  if (file.endsWith('.svg')) return 'image/svg+xml'
  if (file.endsWith('.png')) return 'image/png'
  if (file.endsWith('.jpg') || file.endsWith('.jpeg')) return 'image/jpeg'
  return 'application/octet-stream'
}

async function upload(file) {
  const relative = path.relative(root, file).replace(/\\/g, '/')
  const key = prefix + relative
  await new Promise((resolve, reject) => {
    cos.putObject({
      Bucket: bucket,
      Region: region,
      Key: key,
      Body: fs.createReadStream(file),
      ContentType: contentType(file)
    }, err => err ? reject(err) : resolve())
  })
  console.log('uploaded ' + key)
}

async function main() {
  const files = walk(root)
  for (const file of files) {
    await upload(file)
  }
  console.log('Admin console uploaded to cos://' + bucket + '/' + prefix)
}

main().catch(err => {
  console.error(err.message || err)
  process.exit(1)
})
