import dayjs from 'dayjs'
import { exec } from 'child_process'

import { readFileSync, writeFileSync } from 'fs'

const versionFile = './sagoo-iot/versionInfo.json'

main()

/**
 * 写入json文件
 * @param {*} version
 * @param {*} fileDirName
 */
function writeJson(version, fileDirName) {
	try {
		writeFileSync(fileDirName, JSON.stringify(version, null, 2), { flag: 'w+', encoding: 'utf-8' })
		console.log(`-> 写入 ${fileDirName} 成功`)
	} catch (err) {
		console.error(`-> 写入 ${fileDirName} 失败: `)
		console.error(err)
		throw err
	}
}

/**
 * 获取最新的版本号
 * @returns
 */
function getLatestVersion() {
	return new Promise((resolve) => {
		exec('git describe --abbrev=0 --tags', (err, version) => {
			if (err) {
				resolve({ version: '获取失败', hash: '获取失败' })
			} else {
				if (!version) return resolve({ version: '获取失败', hash: '获取失败' })
				exec('git rev-parse HEAD', (err, hash) => {
					if (err) {
						resolve({ version: version.trim(), hash: '获取失败' })
					} else {
						resolve({ version: version.trim(), hash: hash.trim() })
					}
				})
			}
		})
	})
}

// 主函数
function main() {
	getLatestVersion()
		.then(({ version, hash }) => {
			const content = readFileSync(versionFile, 'utf-8')
			const packageInfo = JSON.parse(content)

			packageInfo.version = version
			packageInfo.hash = hash
			packageInfo.updateTime = dayjs().format('YYYY-MM-DD HH:mm:ss')

			writeJson(packageInfo, versionFile)
		})
		.catch(() => {})
}
