#!/bin/sh

DIR=$(cd "$(dirname "$(readlink -f "$0")")" && pwd)
ROOT="$(realpath "$DIR/../../")"
CLEANCSS="$ROOT"/node_modules/clean-css-cli/bin/cleancss
. "$DIR/build_common.sh"

build_scss() {
    entry_name="$1"
    theme="$2"

    input="$INDIR/$entry_name@$theme.scss"
    output="$OUTDIR/$entry_name"
    [ "$theme" = "dark" ] && output="${output}_dark"
    output="${output}.css"

    sassc -t compressed "$input" "$output"
}

cleancss() {
    entry_name="$1"
    theme="$2"

    file="$OUTDIR/$entry_name"
    [ "$theme" = "dark" ] && file="${file}_dark"
    file="${file}.css"

    $CLEANCSS -O2 "all:on;mergeSemantically:on;restructureRules:on" "$file" > "$file.tmp"
    rm "$file"
    mv "$file.tmp" "$file"
}

create_dark_patch() {
    entry_name="$1"
    light_file="$OUTDIR/$entry_name.css"
    dark_file="$OUTDIR/${entry_name}_dark.css"

    "$DIR"/gen_css_diff.js "$light_file" "$dark_file" > "$dark_file.diff"
    rm "$dark_file"
    mv "$dark_file.diff" "$dark_file"
}

THEMES="light dark"

input_args "$@"
check_args

[ -x "$CLEANCSS" ] || die "cleancss is not found"

for theme in $THEMES; do
	while IFS= read -r target; do
		build_scss "$target" "$theme"
	done < "$INDIR/targets.txt"
done

while IFS= read -r target; do
	create_dark_patch "$target"
	for theme in $THEMES; do cleancss "$target" "$theme"; done
done < "$INDIR/targets.txt"
