#!/usr/bin/env bash
# =============================================================================
# Revert the test cell-divert setup back to normal routing.
# Run this after the test window 17:00-18:30 SAST today.
# =============================================================================
set -e

DB_USER="asterisk"
DB_PASS="0penV70penV7"
DB_NAME="asterisk"

echo "Reverting test cell-divert setup..."

# 1. Restore the inbound route to point at the previous TC #3
mysql -u"$DB_USER" -p"$DB_PASS" "$DB_NAME" << 'SQL'
UPDATE inbound_routes SET destination_type = 'time_condition', destination_value = '3' WHERE id = 3;

-- Restore the trunks-in dialplan to original
DELETE FROM extensions WHERE context = 'trunks-in' AND exten = '_041450XXXX';
INSERT INTO extensions (context, exten, priority, app, appdata, created_at, updated_at) VALUES
('trunks-in', '_041450XXXX', 1, 'NoOp', 'INBOUND DID: ${EXTEN}',           NOW(), NOW()),
('trunks-in', '_041450XXXX', 2, 'Set',  '__DID=${EXTEN}',                  NOW(), NOW()),
('trunks-in', '_041450XXXX', 3, 'Goto', 'from-internal,*8555,1',           NOW(), NOW());

-- Restore the from-inbound dialplan to original
DELETE FROM extensions WHERE context = 'from-inbound' AND exten = '_0414501359';
INSERT INTO extensions (context, exten, priority, app, appdata, created_at, updated_at) VALUES
('from-inbound', '_0414501359', 1, 'NoOp', 'DIRECT ROUTE TO *8555', NOW(), NOW()),
('from-inbound', '_0414501359', 2, 'Goto', 'from-internal,*8555,1', NOW(), NOW());
SQL

# 2. Optionally remove the test TC entirely
read -p "Also delete the test Time Condition #5 and Time Group? [y/N] " yn
if [[ "$yn" =~ ^[Yy]$ ]]; then
    mysql -u"$DB_USER" -p"$DB_PASS" "$DB_NAME" -e "
        DELETE FROM extensions WHERE context = 'time-condition-5';
        DELETE FROM extensions WHERE context = 'from-internal' AND exten IN ('*TC100');
        DELETE FROM time_conditions WHERE id = 5;
        DELETE FROM time_rules WHERE time_group_id IN (SELECT id FROM time_groups WHERE name LIKE 'Test Cell Divert%');
        DELETE FROM time_groups WHERE name LIKE 'Test Cell Divert%';
    "
    echo "Test TC and group removed."

    # Also regenerate the include file
    cd /var/www/html
    php artisan timeconditions:sync
fi

# 3. Reload Asterisk
asterisk -rx "dialplan reload" 2>&1
echo "Done. Asterisk dialplan reloaded."
