#!/usr/bin/env bash

set -eu

help() {
    cat <<EOF
Usage: $0 [OPTIONS]

Options:
    -a		Update API
    -w		Update Web
    -A		Update API & Web
    -m		Apply migration in API
    -h		Show this help and exit
EOF
}

# False by default
apply_migration=0
update_api=0
update_web=0

# Check if any flag was passed
if [[ $# -eq 0 ]]; then
    help;
    exit 1
fi

while getopts ":awAmh" opt; do
	case $opt in
		a) update_api=1 ;;
		w) update_web=1 ;;
		A) update_api=1; update_web=1 ;;
		m) apply_migration=1;;
		h) help; exit 0 ;;
		\?) help; exit 1 ;;
	esac
done

if (( update_api || update_web )); then
    git pull
fi

if (( update_api )); then
    echo "Updating api"
    cd packages/api
    bun i --frozen-lockfile
    if (( apply_migration )); then
      echo "Applying migration"
      bun run db:migrate
    fi
    cd ../..
    echo "Restarting api service"
    systemctl --user restart nexus-api
elif (( apply_migration )); then
    echo "Applying migration"
    cd packages/api
    bun run db:migrate
    cd ../..
    echo "Restarting api service"
    systemctl --user restart nexus-api
fi

if (( update_web )); then
    echo "Updating web"
    cd packages/web
    bun i --frozen-lockfile
    bun run build
    cd ../..
    echo "Restarting web service"
    systemctl --user restart nexus-web
fi

echo "Update complete"