#!/bin/bash

cd /home/otwarchive/otwarchive || exit 1

FILE="/tmp/otwarchive_$(date +%Y-%m-%d).sql"

#sudo docker compose exec -T db \
 # mysqldump -uroot  \
  #--databases otwarchive_production \
  #--skip-comments \
  #| gzip > "$FILE"
#sudo docker compose exec db mysqldump -uroot -p$MYSQL_ROOT_PASSWORD --databases otwarchive_production --skip-comments > ~/otwa/otwarchive_$(date +%Y-%m-%d_%H-%M-%S).sql.gz
#
#touch ~/otwabck/otwarchive_$(date +%Y-%m-%d_%H-%M-%S).sql
#touch "/tmp/otwarchive_$(date +%Y-%m-%d).sql"
sudo docker compose exec -T db sh -c \
  'mysqldump -uroot -p"$MYSQL_ROOT_PASSWORD" --databases otwarchive_production --skip-comments' \
  | gzip > "/tmp/otwarchive_$(date +%Y-%m-%d).sql"

if [ ${PIPESTATUS[0]} -ne 0 ]; then
    echo "MySQL dump failed"
    rm -f "$FILE"
    exit 1
fi

aws --endpoint-url https://t3.storage.dev \
  s3 cp "$FILE" \
  "s3://sunsetti/mysql/otwarchive/$(basename "$FILE")"

if [ $? -ne 0 ]; then
    echo "S3 upload failed"
    rm -f "$FILE"
    exit 1
fi

rm -f "$FILE"

echo "Backup completed successfully"
