#!/bin/bash

PNAME="astra"
if [ -n "$1" ] ; then
    PNAME="$1"
fi

APID_LIST=`ps -C $PNAME -o pid=`
CDIR=`pwd`

ask() {
    read -r -p "Reset password to default in $1 [y/N] " ANS
    if [ "x$ANS" = "xY" -o "x$ANS" = "xy" ] ; then
        return 0
    else
        return 1
    fi
}

resetpass_561() {
    ACFG="$1"
    cat <<EOF
config = json.load("$ACFG")
if config.settings then
    config.settings.user = "admin"
    config.settings.pass = "admin"
    json.save("$ACFG", config)
end
astra.exit()
EOF
}

resetpass_562() {
    ACFG="$1"
    cat <<EOF
config = json.load("$ACFG")
user = config.users["admin"]
if not user then
    user = { enable = true, type = 1, created = os.time() }
    config.users["admin"] = user
end
user.cipher = "3fed7a346e430ea4c2aa10250928f4de"
json.save("$ACFG", config)
astra.exit()
EOF
}

resetpass() {
    APID="$1"
    ABIN="/proc/$APID/exe"
    AVER=`$ABIN -v`

    ACFG=`cat /proc/$APID/cmdline | tr '\0' '\n' | grep -A1 '\-c' | tail -n1`
    if ! ask "$ACFG" ; then
        return 0
    fi

    case "$AVER" in
        "Astra v.5.61")
            resetpass_561 "$ACFG" | $ABIN - >/dev/null
            ;;
        "Astra v.5."*)
            resetpass_562 "$ACFG" | $ABIN - >/dev/null
            ;;
        "Astra v.6."*)
            resetpass_562 "$ACFG" | $ABIN - >/dev/null
            ;;
        *)
            echo "Unknown version: $AVER"
            ;;
    esac
}

cd /
for APID in $APID_LIST ; do
    cd /proc/$APID/cwd
    resetpass "$APID"
done
cd $CDIR
