#! /bin/sh

set -o pipefail
set -e
set -u


if tty && ! which firebase; then
   f="$(mktemp)"
   wget https://firebase.tools -O - > "$f"
   export upgrade=true
   sudo bash "$f"
fi
which firebase

outdir=$(mktemp -d)
cleanup() {
   rm -rf "$outdir"
}
trap cleanup EXIT

rm -rf $outdir
mkdir -p $outdir/public
cp ./open-resume.com.d/resume.html.2 $outdir/public/index.html
cp ./open-resume.com.d/resume.pdf $outdir/public/BreeLaPointeResume.pdf
cp -r ./open-resume.com.d/fonts $outdir/public/

(
   if ! which woff2_compress; then
      sudo apt -y install woff2
   fi
   set -ueo pipefail
   for f in "$outdir"/public/fonts/*.ttf; do
      echo ttf to woff2 for "$f"
      if [ -f "$f" ]; then
         woff2_compress "$f"
         rm "$f"
      fi
      basename_f="${f##*/}"
      find "$outdir/public" -type f | grep -v public.fonts | while read -r f2; do
         sed -i "s#$basename_f#${basename_f%.ttf}.woff2#g" "$f2"
      done
      echo asserting no $basename_f
      ! grep -R "$basename_f" "$outdir/public"
      echo asserting ${basename_f%.ttf}.woff2
      grep -R "${basename_f%.ttf}.woff2" "$outdir/public"
   done
   du -sh "$outdir/public/fonts/"*
)

cp -r ./firebase.json ./.firebaserc ./.firebase $outdir/
sed -i "s#deploy/public#public#" $outdir/firebase.json
cd $outdir

(
   set -ueo pipefail
   if [ -n "$GITLAB_PAT" ]; then
      export HOME="$(mktemp -d)"
      git clone https://gitlab%40breel.dev:"$GITLAB_PAT"@gitlab.com/breel/resume.git gitlab-resume.d
      git config --global user.name "gitlab@breel.dev"
      git config --global user.email "gitlab@breel.dev"
      rm -rf ./gitlab-resume.d/*
      cp -r ./public/* ./gitlab-resume.d/
      cd ./gitlab-resume.d/
      git add -A :/
      git commit -m "$(date -u +%Y-%m-%dT%H:%M:%S)"
      git push origin main
   fi
) || true

(
   set -ueo pipefail
   echo firebase uses squeaky2x3@gmail.com
   ! tty || firebase login
   echo firebase init
   args=()
   log_args=()
   if ! tty; then
      args+=("--token" "$FIREBASE_CI_TOKEN")
      log_args+=("--token" "${FIREBASE_CI_TOKEN:0:1}")
      test "${FIREBASE_CI_TOKEN:0:1}" != "$"
   fi
   echo firebase deploy "${log_args[@]}"
   firebase deploy "${args[@]}"
)
