#!/bin/sh
[ -n "${IPKG_INSTROOT}" ] && exit 0
if [ -s /etc/config/tachyon ] && [ ! -s /etc/tachyon/backup-pre-2.0/tachyon.uci ]; then
    mkdir -p /etc/tachyon/backup-pre-2.0 2>/dev/null || true
    cp -af /etc/config/tachyon /etc/tachyon/backup-pre-2.0/tachyon.uci 2>/dev/null || true
    chmod 600 /etc/tachyon/backup-pre-2.0/tachyon.uci 2>/dev/null || true
fi
_is_v1=0
if [ -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
elif [ -x /usr/bin/tachyon ] && head -c 2 /usr/bin/tachyon 2>/dev/null | grep -q '^#!'; then
    _is_v1=1
fi
if [ "$_is_v1" -eq 1 ]; then
    __anc=" "
    __p=$$
    while [ -n "$__p" ] && [ "$__p" -gt 1 ] 2>/dev/null; do
        __anc="$__anc$__p "
        __p=$(awk '{ sub(/.*\) /, ""); print $2 }' "/proc/$__p/stat" 2>/dev/null)
    done
    for __pdir in /proc/[0-9]*; do
        __pid="${__pdir##*/}"
        case "$__anc" in *" $__pid "*) continue;; esac
        if [ -r "$__pdir/cmdline" ]; then
            __cmd="$(tr '\0' ' ' < "$__pdir/cmdline" 2>/dev/null)"
            case "$__cmd" in
                *99-tachyon-wan*|*"flock 1000"*|*"/etc/init.d/tachyon"*)
                    kill -9 "$__pid" >/dev/null 2>&1 || true
                    continue
                    ;;
            esac
        fi
        if [ -e "$__pdir/fd/1000" ]; then
            case "$(readlink "$__pdir/fd/1000" 2>/dev/null)" in
                *procd_tachyon*) kill -9 "$__pid" >/dev/null 2>&1 || true ;;
            esac
        fi
    done
    _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
    if [ -x /usr/bin/tachyon ]; then
        $_to /usr/bin/tachyon stop >/dev/null 2>&1 || true
    fi
    if [ -x /etc/init.d/tachyon ]; then
        $_to /etc/init.d/tachyon stop >/dev/null 2>&1 || true
    fi
    if [ -x /etc/init.d/tachyon-core ]; then
        $_to /etc/init.d/tachyon-core stop >/dev/null 2>&1 || true
    fi
    : > /tmp/tachyon-upgrading-from-v1 2>/dev/null || true
fi
exit 0
