#!/bin/sh

usage() {
    echo "Usage: $0 --version <version>"
    echo "Example: $0 --version 0.2.7"
    exit 1
}

VERSION=""

while [ $# -gt 0 ]; do
    case "$1" in
        --version)
            VERSION="$2"
            shift 2
            ;;
        *)
            usage
            ;;
    esac
done

if [ -z "$VERSION" ]; then
    echo "Error: --version is required"
    usage
fi

FOLDER="stonkys.com-${VERSION}"
ARCHIVE="stonkys_com-${VERSION}-source.tar.gz"

if [ ! -d "$FOLDER" ]; then
    echo "Error: directory ${FOLDER} not found"
    exit 1
fi

echo "==> Packaging ${FOLDER}"
echo "    Archive: ${ARCHIVE}"

tar czf "$ARCHIVE" \
  --exclude='*/.pytest_cache/*' \
  --exclude='uwsgi.generated.ini' \
  --exclude='db/db.bak' \
  --exclude='*/.env' \
  --exclude='*/venv/*' \
  --exclude='*/__pycache__/*' \
  --exclude='*.pyc' \
  --exclude='*/.git/*' \
  --exclude='*.swp' \
  --exclude='*.swo' \
  --exclude='*~' \
  --exclude='*/node_modules/*' \
  --exclude='*/populate.py' \
  --exclude='*.db' \
  --exclude='*.sqlite3' \
  --exclude='*.cache' \
  --exclude='*.pid' \
  --exclude='*/upload/*' \
  --exclude='*/log/*' \
  --exclude='*/charts/*' \
  --exclude='*plotly*' \
  --exclude='*uPlot*' \
  --exclude='*/misc/*' \
  --exclude='*/log/*' \
  --exclude='*/upload/*' \
  --exclude='*.swp' \
  --exclude='*/static/charts/*' \
  "$FOLDER"
if [ $? -eq 0 ]; then
    SIZE=$(ls -lh "$ARCHIVE" | awk '{print $5}')
    echo "==> Done: ${ARCHIVE} (${SIZE})"
else
    echo "Error: tar failed"
    exit 1
fi
