#!/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

DOCKER_CONTEXT=vert
START=`date +%s`
BACKUP_DATE=`date +%Y%m%d`

logs_backup() {
  mkdir -p backups
  ssh $DOCKER_CONTEXT mkdir -p backups/histoiredunpied
  docker --context $DOCKER_CONTEXT run -t --rm -v $HOME/backups/histoiredunpied:/backup -v histoiredunpied-log-volume:/logs alpine:3.11.6 ash -c "cd /logs && tar cvf /backup/${BACKUP_DATE}_histoiredunpied_logs.tar ."
  ssh $DOCKER_CONTEXT "sudo chown kosssi:docker $HOME/backups/histoiredunpied/${BACKUP_DATE}_histoiredunpied_logs.tar"
  scp $DOCKER_CONTEXT:$HOME/backups/histoiredunpied/${BACKUP_DATE}_histoiredunpied_logs.tar backups
}

logs_restore() {
  ssh $DOCKER_CONTEXT mkdir -p backups/histoiredunpied
  scp backups/${BACKUP_DATE}_histoiredunpied_logs.tar $DOCKER_CONTEXT:$HOME/backups/histoiredunpied/
  docker --context $DOCKER_CONTEXT run -t --rm -v $HOME/backups/histoiredunpied:/backup -v histoiredunpied-log-volume:/logs alpine:3.11.6 ash -c "cd /logs && tar xvf /backup/${BACKUP_DATE}_histoiredunpied_logs.tar --strip 1"
}

logs_update() {
  docker --context $DOCKER_CONTEXT exec -it histoiredunpied-logs ash /bin/stats.sh generate
}

help() {
  echo "💡 Aide"
  echo "-------"
  echo
  echo "Commandes :"
  echo "- ./run logs backup        📥 Sauvegarde les logs"
  echo "- ./run logs restore       📤 Restore les logs"
  echo "- ./run logs update        🌠 Mise à jour de GoAccess"
  echo
}

if [ $# -ge 1 ]; then
  if [ $1 == "logs" ]; then
    if [ $# -ge 2 ]; then
      if [ $2 == "backup" ]; then
        echo "📥 Sauvegarde les logs"
        logs_backup
      elif [ $2 == "restore" ]; then
        echo "📤 Restore les logs"
        logs_restore
      elif [ $2 == "update" ]; then
        echo "🌠 Mise à jour de GoAccess"
        logs_update
      else
        help
      fi
    else
      help
    fi
  else
    help
  fi
else
  help
fi

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