#!/usr/local/bin/node
const fs = require('fs')
const path = require('path')
let baseDir = path.resolve(process.argv[2])
var force = process.argv.indexOf('-f') > -1
console.log("force:", force)
copyAssets(baseDir)
console.log('done')
function copyAssets(srcDir) {
    fs.readdirSync(srcDir).forEach(function (ele, index) {
        if (/\(\d\)/.test(ele)) {
            return
        }
        var subPath = path.resolve(srcDir, ele)
        var info = fs.statSync(subPath)
        if (!info.isDirectory()) {
            var src = path.resolve(srcDir, ele)
            var dstDir = path.resolve(__dirname, 'images')
            var baseName = path.basename(src)
            var fileName = baseName.replace(/@\dx/g, '')
            var execRes = /@(\dx)/.exec(baseName)
            var subDir = execRes ? execRes[1] : ''
            if (subDir) {
                if (!fs.existsSync(path.resolve(dstDir, subDir))) {
                    fs.mkdirSync(path.resolve(dstDir, subDir), { recursive: true })
                }
            }
            var dst = path.resolve(dstDir, subDir, fileName)
            if (force) {
                if (fs.existsSync(dst)) {
                    fs.unlinkSync(dst)
                }
            }
            try {
                fs.copyFileSync(src, dst, fs.constants.COPYFILE_EXCL)
                console.log('\x1B[32m%s\x1B[39m', `${baseName}\t->\timages/${subDir ? (subDir + '/' + fileName) : fileName}`)
            } catch (e) {
                console.error('\x1B[90m%s\x1B[39m', `${src}\t->\t${dst}`)
            }
        }
    })
}
