#!/bin/sh
# Self-update script for Radius. Triggered from the Settings page by user id 1.
# Designed to be invoked via: sudo /var/www/radius-circle/deploy.sh
# Written in POSIX sh so it runs under dash, bash, or sh.
# All output is streamed to stdout/stderr and captured by the controller.

PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$PROJECT_DIR" || { echo "ERROR: cannot cd to $PROJECT_DIR"; exit 1; }

echo "==> Project directory: $PROJECT_DIR"
echo "==> Starting update at: $(date '+%Y-%m-%d %H:%M:%S')"
echo

run() {
    echo "==> $*"
    "$@"
    local code=$?
    if [ $code -ne 0 ]; then
        echo "FAILED ($code): $*"
        exit $code
    fi
    echo
}

# Make git trust this directory regardless of which user runs the script
git config --global --add safe.directory "$PROJECT_DIR" >/dev/null 2>&1 || true

# Set origin with embedded GitHub credentials so pulls never prompt.
# WARNING: this token is stored in plaintext in this file. Anyone with access
# to this repository can use it. Keep the repo private and rotate the token
# periodically (GitHub -> Settings -> Developer settings -> Personal access tokens).
GIT_USER="ahsans1997"
GIT_TOKEN="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"
GIT_HOST="github.com"
GIT_REPO="YetFixLtd/radius-circle"
echo "==> Setting origin to https://${GIT_USER}:****@${GIT_HOST}/${GIT_REPO}.git"
git remote set-url origin "https://${GIT_USER}:${GIT_TOKEN}@${GIT_HOST}/${GIT_REPO}.git" >/dev/null 2>&1
echo

run git reset --hard
run git checkout master
run git reset --hard
run git pull

run php artisan migrate --force
run php artisan fix:common
run php artisan db:seed --class=PermissionsSeeder --force
run php artisan db:seed --class=GlobalSettingSeeder --force
run php artisan db:seed --class=SmsSettingSeeder --force
run php artisan db:seed --class=PaymentIssueTypeSeeder 
run php artisan backup:clean --disable-notifications

run chown -R www-data:www-data storage
run chmod -R 777 storage
run chown -R www-data:www-data bootstrap
run chmod -R 777 bootstrap

run php artisan optimize:clear
run php artisan optimize

echo "==> Update completed successfully at: $(date '+%Y-%m-%d %H:%M:%S')"
exit 0
