path_public_dir="public"
path_tmp="tmp"
path_dest="$path_tmp/startup_css_assets"
glob_css_dest="$path_dest/application*.css"
glob_css_src="$path_public_dir/assets/application*.css"
should_clean=false

should_force() {
  $1=="force"
}

has_dest_already() {
 find $glob_css_dest -quit
}

has_src_already() {
 find $glob_css_src -quit
}

compile_assets() {
  # We need to build the same test bundle that is built in CI
  RAILS_ENV=test bundle exec rake rake:assets:precompile
}

clean_assets() {
  bundle exec rake rake:assets:clobber
}

copy_assets() {
  rm -rf $path_dest
  mkdir $path_dest
  cp $glob_css_src $path_dest
}

echo "-----------------------------------------------------------"
echo "If you are run into any issues with Startup CSS generation,"
echo "please check out the feedback issue:"
echo ""
echo "https://gitlab.com/gitlab-org/gitlab/-/issues/331812"
echo "-----------------------------------------------------------"

if [ ! -e $path_public_dir ]; then
  echo "Could not find '$path_public_dir/'. This script must be run in the root directory of the gitlab project."
  exit 1
fi

if [ ! -e $path_tmp ]; then
  echo "Could not find '$path_tmp/'. This script must be run in the root directory of the gitlab project."
  exit 1
fi

if [ "$1" != "force" ] && has_dest_already; then
  echo "Already found assets for '$glob_css_dest'. Did you want to run this script with 'force' argument?"
  exit 0
fi

# If we are in CI, don't recompile things...
if [ -n "$CI" ]; then
  if ! has_src_already; then
    echo "Could not find '$glob_css_src'. Expected these artifacts to be generated by CI pipeline."
    exit 1
  fi
elif has_src_already; then
  echo "Found '$glob_css_src'. Skipping compile assets..."
else
  echo "Starting compile assets process..."
  compile_assets
  should_clean=true
fi

copy_assets

if $should_clean; then
  echo "Starting cleanup..."
  clean_assets
fi
