#!/bin/sh
[ -n "${IPKG_INSTROOT}" ] && exit 0
mkdir -p /etc/tachyon /etc/tachyon-core /usr/share/tachyon /tmp/dnsmasq.d 2>/dev/null || true

# Restore /etc/config/tachyon from preinst backup if the package manager removed it.
if [ ! -s /etc/config/tachyon ] && [ -s /etc/tachyon/backup-pre-2.0/tachyon.uci ]; then
    cp -af /etc/tachyon/backup-pre-2.0/tachyon.uci /etc/config/tachyon 2>/dev/null || true
    chmod 600 /etc/config/tachyon 2>/dev/null || true
fi

# Migrate 1.x (ucode + rpcd) -> 2.0 (Pure-Rust daemon): clean legacy hooks/services/tables,
# preserving /etc/config/tachyon for automatic store import.
_is_v1=0
if [ -f /tmp/tachyon-upgrading-from-v1 ] || [ -d /usr/lib/tachyon ] || [ -e /usr/libexec/rpcd/tachyon ] || [ -e /usr/bin/tachyon-read ] || [ -e /etc/hotplug.d/iface/99-tachyon-wan-monitor ] || [ -e /etc/init.d/tachyon-torrserver-direct ]; then
    _is_v1=1
fi
if [ "$_is_v1" -eq 1 ]; then
    _to=""
    if command -v timeout >/dev/null 2>&1; then
        if timeout 1 /bin/true >/dev/null 2>&1; then
            _to="timeout 15"
        elif timeout -t 1 /bin/true >/dev/null 2>&1; then
            _to="timeout -t 15"
        fi
    fi

    for _old_svc in /etc/init.d/tachyon-torrserver-direct /etc/init.d/tachyon-core; do
        if [ -x "$_old_svc" ]; then
            $_to "$_old_svc" stop >/dev/null 2>&1 || true
            "$_old_svc" disable >/dev/null 2>&1 || true
        fi
    done
    rm -f /etc/rc.d/*tachyon-core* /etc/rc.d/*tachyon-torrserver-direct* 2>/dev/null || true

    for p in /proc/[0-9]*; do
        [ -r "$p/cmdline" ] || continue
        case "$(tr '\0' ' ' < "$p/cmdline" 2>/dev/null)" in
            *"/usr/lib/tachyon/"*|*"/usr/bin/tachyon-core"*)
                kill -9 "${p##*/}" >/dev/null 2>&1 || true
                ;;
        esac
    done

    if command -v nft >/dev/null 2>&1; then
        nft delete table inet tachyon >/dev/null 2>&1 || true
        nft delete table inet TachyonTable >/dev/null 2>&1 || true
        nft delete table inet TachyonKillSwitch >/dev/null 2>&1 || true
        nft delete table ip tachyon >/dev/null 2>&1 || true
        nft delete table ip6 tachyon >/dev/null 2>&1 || true
    fi
    rm -f /usr/share/nftables.d/chain-pre/input/10-tachyon.nft /usr/share/nftables.d/ruleset-post/90-tachyon-kill-switch.nft 2>/dev/null || true

    if command -v ip >/dev/null 2>&1; then
        for _p in 9499 9500 9501; do
            for _fam in -4 -6; do
                while ip "$_fam" rule del pref "$_p" >/dev/null 2>&1; do :; done
            done
        done
        for _fam in -4 -6; do
            ip "$_fam" rule del fwmark 0x04000000/0x04000000 lookup 100 >/dev/null 2>&1 || true
            ip "$_fam" rule del fwmark 0x04000000 lookup 100 >/dev/null 2>&1 || true
            ip "$_fam" rule del fwmark 0x10000000/0x10000000 lookup 100 >/dev/null 2>&1 || true
            ip "$_fam" rule del fwmark 0x10000000 lookup 100 >/dev/null 2>&1 || true
        done
    fi

    if command -v uci >/dev/null 2>&1 && [ -f /etc/config/dhcp ]; then
        _dont_touch="$(uci -q get tachyon.settings.dont_touch_dhcp 2>/dev/null || echo '0')"
        if [ "$_dont_touch" != "1" ]; then
            _had_v1_dns=0
            if uci -q get dhcp.@dnsmasq[0].server 2>/dev/null | grep -q '127\.0\.0\.42'; then
                _had_v1_dns=1
            fi
            if [ -n "$(uci -q get dhcp.@dnsmasq[0].tachyon_server 2>/dev/null || true)" ] ||                [ -n "$(uci -q get dhcp.@dnsmasq[0].tachyon_noresolv 2>/dev/null || true)" ] ||                [ -n "$(uci -q get dhcp.@dnsmasq[0].tachyon_cachesize 2>/dev/null || true)" ] ||                [ -n "$(uci -q get dhcp.tachyon 2>/dev/null || true)" ]; then
                _had_v1_dns=1
            fi
            uci -q del_list dhcp.@dnsmasq[0].server="127.0.0.42" 2>/dev/null || true
            _orig_servers="$(uci -q get dhcp.@dnsmasq[0].tachyon_server 2>/dev/null || true)"
            if [ -n "$_orig_servers" ]; then
                uci -q delete dhcp.@dnsmasq[0].server 2>/dev/null || true
                for _srv in $_orig_servers; do
                    [ "$_srv" != "127.0.0.42" ] && uci -q add_list dhcp.@dnsmasq[0].server="$_srv" 2>/dev/null || true
                done
                uci -q delete dhcp.@dnsmasq[0].tachyon_server 2>/dev/null || true
            fi
            for _opt in noresolv cachesize rebind_protection localuse addn_hosts notinterface serversfile localservice; do
                _val="$(uci -q get "dhcp.@dnsmasq[0].tachyon_${_opt}" 2>/dev/null || true)"
                if [ -n "$_val" ]; then
                    if [ "$_val" = "__tachyon_unset__" ] || [ "$_val" = "__absent__" ] || [ "$_val" = "unset" ]; then
                        uci -q delete "dhcp.@dnsmasq[0].${_opt}" 2>/dev/null || true
                    else
                        uci -q set "dhcp.@dnsmasq[0].${_opt}=${_val}" 2>/dev/null || true
                    fi
                    uci -q delete "dhcp.@dnsmasq[0].tachyon_${_opt}" 2>/dev/null || true
                fi
            done
            if [ "$_had_v1_dns" -eq 1 ]; then
                if [ "$(uci -q get dhcp.@dnsmasq[0].noresolv 2>/dev/null)" = "1" ]; then
                    uci -q set dhcp.@dnsmasq[0].noresolv="0" 2>/dev/null || true
                fi
                if [ "$(uci -q get dhcp.@dnsmasq[0].cachesize 2>/dev/null)" = "0" ]; then
                    uci -q set dhcp.@dnsmasq[0].cachesize="150" 2>/dev/null || true
                fi
            fi
            uci -q delete dhcp.tachyon 2>/dev/null || true
            uci -q commit dhcp 2>/dev/null || true
            rm -f /tmp/dnsmasq.d/tachyon.conf 2>/dev/null || true
            if [ "$_had_v1_dns" -eq 1 ] && [ -x /etc/init.d/dnsmasq ]; then
                /etc/init.d/dnsmasq reload >/dev/null 2>&1 || /etc/init.d/dnsmasq restart >/dev/null 2>&1 || true
            fi
        fi
    fi

    rm -rf /usr/lib/tachyon /var/run/tachyon/section-cache /var/run/tachyon/ui-state 2>/dev/null || true
    rm -f /usr/libexec/rpcd/tachyon /usr/bin/tachyon-read /etc/hotplug.d/iface/99-tachyon-wan-monitor /etc/init.d/tachyon-torrserver-direct /www/cgi-bin/tachyon-agent /usr/lib/cgi-bin/tachyon-agent /etc/uci-defaults/50_luci-tachyon /usr/share/luci/menu.d/luci-app-tachyon.json /usr/share/rpcd/acl.d/luci-app-tachyon.json /usr/lib/lua/luci/i18n/tachyon.ru.lmo 2>/dev/null || true
    rm -f /tmp/tachyon-upgrading-from-v1 2>/dev/null || true
fi

if command -v crontab >/dev/null 2>&1; then
    _tachyon_cron_re='#[[:space:]]*tachyon-(list-update|subscription-update|component-update-check|parental-quota)([[:space:]]|$)|/usr/bin/tachyon[[:space:]]+(list_update(_if_due)?|subscription_update(_if_due)?|component_updates_if_due|component_auto_update_apply|parental_quota_tick)([[:space:]]|$)'
    _cron_cur="$(mktemp /tmp/tachyon-cron-cur.XXXXXX 2>/dev/null || echo "/tmp/tachyon-cron-cur.$$")"
    _crontmp="$(mktemp /tmp/tachyon-cron.XXXXXX 2>/dev/null || echo "/tmp/tachyon-cron.$$")"
    if [ -r /etc/crontabs/root ]; then
        cat /etc/crontabs/root > "$_cron_cur" 2>/dev/null || true
    else
        crontab -l > "$_cron_cur" 2>/dev/null || true
    fi
    if grep -q -E "$_tachyon_cron_re" "$_cron_cur" 2>/dev/null; then
        grep -v -E "$_tachyon_cron_re" "$_cron_cur" > "$_crontmp" || true
        crontab "$_crontmp" 2>/dev/null || true
        if [ -s "$_crontmp" ] && [ -x /etc/init.d/cron ]; then
            pgrep crond >/dev/null 2>&1 || /etc/init.d/cron start >/dev/null 2>&1 || true
        fi
    fi
    rm -f "$_cron_cur" "$_crontmp" 2>/dev/null || true
fi

rm -f /tmp/luci-indexcache* /usr/share/tachyon/tachyon.ru.po 2>/dev/null || true
rm -rf /tmp/luci-modulecache 2>/dev/null || true
for _js in /www/luci-static/resources/view/tachyon/*.js /www/luci-static/resources/luci.js /www/luci-static/resources/view/tachyon /www/luci-static/resources; do
    [ -e "$_js" ] && touch "$_js" 2>/dev/null || true
done
[ -x /etc/init.d/rpcd ] && /etc/init.d/rpcd reload >/dev/null 2>&1 || true

chmod 755 /usr/bin/tachyon /etc/init.d/tachyon /www/cgi-bin/tachyon-sub 2>/dev/null || true
if [ -x /etc/init.d/tachyon ]; then
    /etc/init.d/tachyon enable >/dev/null 2>&1 || true
    /etc/init.d/tachyon stop >/dev/null 2>&1 || true
    _wait_i=0
    while [ "$_wait_i" -lt 6 ]; do
        _alive=0
        for _p in /proc/[0-9]*; do
            [ -r "$_p/comm" ] || continue
            if [ "$(cat "$_p/comm" 2>/dev/null)" = "tachyon" ]; then
                _alive=1
                break
            fi
        done
        [ "$_alive" -eq 0 ] && break
        _wait_i=$((_wait_i + 1))
        sleep 1
    done
    killall -9 tachyon >/dev/null 2>&1 || true
    /etc/init.d/tachyon start >/dev/null 2>&1 || true
fi
exit 0
