/* eslint-env node */

/*
This script adds fallbacks for custom properties.

Input:

    :root {
      --theme-color: red;
    }

    a {
      color: var(--theme-color);
    }

Output:

    :root {
      --theme-color: red;
    }

    a {
      color: red /* fallback * /;
      color: var(--theme-color);
    }

This script should work with:

- Node.js 4 or later.
- npm 5 or later (npm 3 might work too).
*/

const fs = require("fs");
const path = require("path");
const postcss = require("postcss");
const customProperties = require("postcss-custom-properties");

const CSS_FILE = path.join(__dirname, "../bananas/static/admin/css/bananas.css");
// const CSS_FILE = path.join(__dirname, "test.css");

const FALLBACK_COMMENT = "/* fallback */";

const input = fs.readFileSync(CSS_FILE, "utf8");

const output = postcss()
  .use(removeOldFallbacks)
  .use(customProperties({ preserve: true }))
  .use(markFallbacksWithComment)
  .process(input).css;

fs.writeFileSync(CSS_FILE, output);

function removeOldFallbacks(root) {
  root.walkDecls(decl => {
    if (decl.toString().endsWith(FALLBACK_COMMENT)) {
      decl.remove();
    }
  });
}

function markFallbacksWithComment(root) {
  root.walkDecls(decl => {
    if (decl.value.includes("var(")) {
      const prev = decl.prev();
      if (prev) {
        prev.value += ` ${FALLBACK_COMMENT}`;
      }
    }
  });
}

@@ -563,32 +563,35 @@
 s%22);%0A%0Aconst 
-CSS_FILE
+mainCssFile
  = path.join
@@ -583,32 +583,35 @@
 ile = path.join(
+%0A  
 __dirname, %22../b
@@ -604,16 +604,18 @@
 dirname,
+%0A 
  %22../ban
@@ -632,16 +632,24 @@
 c/admin/
+bananas/
 css/bana
@@ -660,14 +660,63 @@
 css%22
+%0A
 );%0A
-// 
+%0Aconst variables = extractVariables(mainCssFile);%0A%0A
 cons
@@ -725,18 +725,38 @@
 CSS_FILE
+S
  =
+ %5B%0A  mainCssFile,%0A 
  path.jo
@@ -774,18 +774,61 @@
 e, %22
-test
+../bananas/static/admin/bananas/css/banansive
 .css%22)
+%0A%5D
 ;%0A%0Ac
@@ -870,16 +870,49 @@
 k */%22;%0A%0A
+CSS_FILES.forEach(cssFile =%3E %7B%0A  
 const in
@@ -933,24 +933,23 @@
 ileSync(
-CSS_FILE
+cssFile
 , %22utf8%22
@@ -948,24 +948,26 @@
 , %22utf8%22);%0A%0A
+  
 const output
@@ -979,16 +979,18 @@
 stcss()%0A
+  
   .use(r
@@ -1008,16 +1008,18 @@
 lbacks)%0A
+  
   .use(c
@@ -1054,13 +1054,26 @@
 true
+, variables
  %7D))%0A
+  
   .u
@@ -1101,16 +1101,18 @@
 omment)%0A
+  
   .proce
@@ -1127,16 +1127,18 @@
 ).css;%0A%0A
+  
 fs.write
@@ -1146,24 +1146,23 @@
 ileSync(
-CSS_FILE
+cssFile
 , output
@@ -1163,16 +1163,375 @@
 output);
+%0A%7D);%0A%0Afunction extractVariables(file) %7B%0A  const input = fs.readFileSync(file, %22utf8%22);%0A  const root = postcss.parse(input);%0A%0A  const variables = %7B%7D;%0A%0A  root.walkRules(%22:root%22, rule =%3E %7B%0A    rule.each(decl =%3E %7B%0A      if (decl.prop && decl.prop.startsWith(%22--%22)) %7B%0A        variables%5Bdecl.prop.slice(2)%5D = decl.value;%0A      %7D%0A    %7D);%0A  %7D);%0A%0A  return variables;%0A%7D
 %0A%0Afuncti

Fix CSS build script