#!/bin/bash

# -e  Exit immediately if a command exits with a non-zero status.
# -u  Treat unset variables as an error when substituting.
set -eu

START=`date +%s`
BACKUP_DATE=`date +%Y%m%d`
BACKUP_LOGS_FILENAME=${BACKUP_DATE}_${URL}_logs.tar
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )" # https://stackoverflow.com/a/246128/6429616

logs_backup() {
  echo "📥 Sauvegarde les logs"
  mkdir -p backups
  ssh $DOCKER_CONTEXT mkdir -p backups/${URL}
  docker --context $DOCKER_CONTEXT run -t --rm -v $HOME/backups/${URL}:/backup -v ${NAME}-log:/logs alpine:3.12.3 ash -c "cd /logs && tar cvf /backup/${BACKUP_LOGS_FILENAME} ."
  ssh $DOCKER_CONTEXT "sudo chown kosssi:docker $HOME/backups/${URL}/${BACKUP_LOGS_FILENAME}"
  scp $DOCKER_CONTEXT:$HOME/backups/${URL}/${BACKUP_LOGS_FILENAME} backups
}

logs_restore() {
  echo "📤 Restaure les logs"
  ssh $DOCKER_CONTEXT mkdir -p backups/${URL}
  scp backups/${BACKUP_LOGS_FILENAME} $DOCKER_CONTEXT:$HOME/backups/${URL}/
  docker --context $DOCKER_CONTEXT run -t --rm -v $HOME/backups/${URL}:/backup -v ${NAME}-log:/logs alpine:3.12.3 ash -c "cd /logs && tar xvf /backup/${BACKUP_LOGS_FILENAME} --strip 1"
}

stats() {
  echo "🌠 Mise à jour de GoAccess"
  docker --context $DOCKER_CONTEXT exec -it ${STATS_CONTAINER} ash /bin/stats.sh generate
}

install() {
  echo "📦 Installation des dépendances 📦"
  echo "----------------------------------"
  echo
  echo "- Récupération du theme"
  git submodule update --init
  echo "- Installation des dépendances node du theme"
  cd themes/hugo-theme-lowtech && npm i
}

dev() {
  echo "🚧 Lancement du serveur pour le développement"
  hugo server -DF
}

dev_prod() {
  echo "🚧 Lancement du serveur pour le développement sans les brouillons"
  hugo server
}

prod() {
  echo
  echo "🚀 Déploiement du site en mode production 🚀"
  echo
  rm -rf public
  hugo --minify --environment production
  node themes/hugo-theme-lowtech/scripts/typo
  #DATE=`date +\"%Y0101\"` && find public -exec touch -d $DATE {} +
  COMPOSE_DOCKER_CLI_BUILD=0 docker-compose --context $DOCKER_CONTEXT -f docker-compose.prod.yml up -d --build --force-recreate
}

staging() {
  echo
  echo "🚀 Déploiement du site en mode staging 🚀"
  echo
  rm -rf public
  hugo --minify -DF --environment staging
  node themes/hugo-theme-lowtech/scripts/typo
  #DATE=`date +\"%Y0101\"` && find public -exec touch -d $DATE {} +
  COMPOSE_DOCKER_CLI_BUILD=0 docker-compose --context $DOCKER_CONTEXT -f docker-compose.staging.yml up -d --build --force-recreate
}

favicons() {
  echo
  if [ -f "static/logo.png" ]; then
    echo "🔍 Génération des favicons à partir d'une image 512px"
    echo
    convert static/logo.png -background transparent -resize 48x48 -colors 16 \( -clone 0 -resize 16x16 -extent 16x16 \) \( -clone 0 -resize 32x32 -extent 32x32 \) \( -clone 0 -resize 48x48 -extent 48x48 \) -delete 0 static/favicon.ico
  elif [ -f "static/logo.svg" ]; then
    echo "🔍 Génération des favicons à partir d'une image SVG"
    echo
    convert static/logo.svg -background transparent -resize 48x48 -colors 16 \( -clone 0 -resize 16x16 -extent 16x16 \) \( -clone 0 -resize 32x32 -extent 32x32 \) \( -clone 0 -resize 48x48 -extent 48x48 \) -delete 0 static/favicon.ico
  else
    echo "🚧 Il faut un fichier 'logo.svg' ou 'logo.png' dans le dossier static"
  fi
  echo
  echo "Aide :"
  echo "- liste des emoji : https://www.unicode.org/emoji/charts/full-emoji-list.html"
  echo "- les emoji de twitter : https://github.com/twitter/twemoji"
  echo "- Pour créer un base64 : \`echo \"data:image/svg+xml;base64,\$(cat static/logo.svg | base64 | tr -d '\r\n')\"\`"
}

optimizer() {
  echo
  echo "🖼️ Optimisation des images"
  echo
  # $SCRIPT_DIR/../node_modules/.bin/imagemin $PWD/static -o $PWD/static
  find ./static ./content -type f \( -iname \*.jpg \) | xargs -I % bash -c '$0/../node_modules/.bin/imagemin % --plugin.webp.quality=95 > $(dirname %)/$(basename % | sed "s/\(.*\)\..*/\1/").webp' $SCRIPT_DIR
}

optimizer_git_image() {
  first_commit_hash=$(git rev-list --max-parents=0 HEAD)

  # https://stackoverflow.com/a/48999882/6429616
  # install git alias amend-to with auto stash
  check_git_command=`git config --global --list | grep amend-to | wc -c`
  if [ "$check_git_command" -ne 187 ]; then
    git config --global alias.amend-to '!f() { SHA=`git rev-parse "$1"`; git stash -k && git commit --fixup "$SHA" && GIT_SEQUENCE_EDITOR=true git rebase --interactive --autosquash "$SHA^" && git stash pop; }; f'
  fi

  for file in $(git diff --name-only --diff-filter=M --ignore-submodules); do
    last_file_update_commit_hash=`git log -n 1 --pretty=format:%H -- $file`
    current_size=`cat $file | wc -c`
    old_size=`git cat-file -p $last_file_update_commit_hash:$file | wc -c`

    if [ "$first_commit_hash" == "$last_file_update_commit_hash" ]; then
      echo "💩 file '$file' is on first commit..."
    elif [ "$current_size" -lt "$old_size" ]; then
      git add $file
      git amend-to $last_file_update_commit_hash
    else
      echo "😳 file '$file' is bigger than original file..."
    fi
  done
}

help_generic() {
  echo
  echo "💡 Aide 💡"
  echo "----------"
  echo
  echo "Commandes :"
  echo "- ./run install            📦 Installation des dépendances"
  echo "- ./run dev                🚧 Lancement du serveur pour le développement"
  echo "- ./run dev_prod           🚧 Lancement du serveur pour le développement sans les brouillons"
  echo "- ./run prod               🚀 Déploiement du site en mode production"
  echo "- ./run staging            🚀 Déploiement du site en mode staging"
  echo "- ./run logs_backup        📥 Sauvegarde les logs"
  echo "- ./run logs_restore       📤 Restaure les logs"
  echo "- ./run stats              🌠 Mise à jour de GoAccess"
  echo "- ./run favicons           🔍 Génération des favicons à partir d'une image 512px ou un SVG"
  echo "- ./run optimizer          🖼️ Optimisation des images"
}

end() {
  END=`date +%s`
  echo
  echo "✨ Done in $((END-START))s"
  echo
}