/* eslint-env node */
/* eslint-disable @typescript-eslint/no-var-requires */

const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CaseSensitivePathsPlugin = require("case-sensitive-paths-webpack-plugin");
const Webpack = require("webpack");

const path = require("path");

const DEVELOPMENT = process.env.NODE_ENV === "development";

let version = process.env.DRONE_TAG;

if(!version){
	version = require('child_process')
		.execSync("git describe --abbrev=0")
		.toString();
}

version = version.replace("v", "").trim();

module.exports = {
	context: path.join(__dirname, "src"),
	resolve: {
		extensions: [".js", ".ts", ".tsx"]
	},
	entry: ["./index.tsx"],
	output: {
		path: path.join(__dirname, "dist/startpage"),
		filename: "bundle.js"
	},
	devtool: DEVELOPMENT ? "source-map" : false,
	devServer: {
		contentBase: "./dist",
		inline: true,
		host: "localhost",
		port: 8080,
		stats: "errors-only",
		liveReload: true,
		watchContentBase: true
	},
	watchOptions: {
		ignored: ['dist/**', 'node_modules/**']
	},
	module: {
		rules: [
			{
				test: /\.(ts|tsx)$/,
				exclude: /node_modules/,
				loader: "ts-loader"
			},
			{
				test: /\.s[ac]ss$/i,
				use: [
					MiniCssExtractPlugin.loader,
					"css-loader",
					"sass-loader",
				],
			},
			{
				test: /\.(png|jpg|gif|svg)$/,
				loader: "file-loader",
				options: {
					name: "assets/img/[name].[ext]?[hash]"
				}
			}
		]
	},
	plugins: [
		new HtmlWebpackPlugin({
			filename: "index.html",
			template: "index.html",
			hash: true,
			minify: !DEVELOPMENT
		}),
		new MiniCssExtractPlugin(),
		new CopyWebpackPlugin([
			{
				from: "manifest.json",
				to: "..",
				transform(content) {
					return content.toString().replace("$VERSION", version);
				}
			}
		]),
		new Webpack.DefinePlugin({
			VERSION: JSON.stringify(version),
		}),
		new CaseSensitivePathsPlugin()
	]
};
