#!/usr/bin/env bash
set -euo pipefail

REPO_ROOT="/home/westfarn/Documents/django_live_sites/Company_Site"
APP_DIR="$REPO_ROOT/company_site"
VENV="$REPO_ROOT/venv"
SETTINGS="$APP_DIR/company_site/settings.py"
LOCAL_SETTINGS="$APP_DIR/company_site/local_settings.py"

if [[ $# -lt 1 || -z "${1:-}" ]]; then
  echo "Usage: $0 <checkout-directory>" >&2
  exit 1
fi

CHECKOUT="$1"

cp "$SETTINGS" /tmp/company_site_settings.py.bak
cp "$LOCAL_SETTINGS" /tmp/company_site_local_settings.py.bak 2>/dev/null || true

rsync -a --delete \
  --exclude venv/ \
  --exclude .git/ \
  --exclude 'company_site/company_site/settings.py' \
  --exclude 'company_site/company_site/local_settings.py' \
  "$CHECKOUT/" "$REPO_ROOT/"

cp /tmp/company_site_settings.py.bak "$SETTINGS"
cp /tmp/company_site_local_settings.py.bak "$LOCAL_SETTINGS" 2>/dev/null || true

source "$VENV/bin/activate"
pip install -r "$REPO_ROOT/requirements.txt"
cd "$APP_DIR"
python manage.py migrate --noinput
python manage.py collectstatic --noinput

sudo systemctl restart company
