#!/bin/bash
export TM_USER="${TM_USER:-SuperAdmin}"
export TM_PASSWORD="${TM_PASSWORD:-$TM_SUPERADMIN_PASSWORD}"
export TM_SERVER_PORT="${TM_SERVER_PORT:-$TM_XMLRPC_PORT}"
export DEDI_USER="${DEDI_USER:-$TM_SERVER_USER}"
export DEDI_PASSWORD="${DEDI_PASSWORD:-$TM_SERVER_PASSWORD}"
overlay="$(mktemp -d)"
upperDir="$overlay/upper"
workDir="$overlay/work"
cache="/cache"
data="/data"
runDir="/opt/xaseco"
entrypoint="$cache/aseco.php"
config="$runDir/config.xml"
adminConfig="$runDir/adminops.xml"
dbConfig="$runDir/localdatabase.xml"
dediConfig="$runDir/dedimania.xml"
pluginConfig="$runDir/plugins.xml"
settingsPath="/settings"
serverPath="$settingsPath/tmserver"
pluginTag="plugin"
pluginPath="/aseco_plugins"

userPattern="^(.+?)(@([[:digit:]]+(.[[:digit:]]+){3}))?\$"

tmOptions=(
    TM_SERVER_HOST ip
    TM_SERVER_PORT port
    TM_USER login
    TM_PASSWORD password
    TM_TIMEOUT timeout
)

groups=(
    ADMINS admins
    OPERATORS operators
)

sqlOptions=(
    MYSQL_HOST mysql_server
    MYSQL_USER mysql_login
    MYSQL_PASSWORD mysql_password
    MYSQL_DATABASE mysql_database
)

dediOptions=(
    DEDI_URL url
    DEDI_NAME name
    DEDI_USER login
    DEDI_PASSWORD password
    DEDI_NATION nation
    DEDI_LOG_NEWS log_news
    DEDI_SHOW_MOTD show_welcome
)

if [ ! -f "$entrypoint" ]; then
    file="$(mktemp -u).zip"
    root="$(mktemp -d)"
    mkdir -p "$(dirname "$file")"
    curl -v --insecure https://www.gamers.org/tmn/xaseco_116.zip -o "$file"
    unzip -o "$file" -d "$root"
    cp -r "$root"/xaseco/* "$cache"
fi

script="$(
    printf "%s\n" \
        'file="$(basename "$1")";' \
        'if [[ "$file" == *".php" ]];' \
        '    then dir="includes";' \
        'else' \
        '    dir=".";' \
        'fi;' \
        'if [ ! -f "$0/$dir/$file" ]; then' \
        '    mkdir -p "$0/$dir";' \
        '    cp "$1" "$0/$dir";' \
        'fi;'
)"

find "$cache/newinstall" -type f -exec bash -c "$script" "$cache" \{\} \;

mount -t tmpfs tmpfs "$overlay"
mkdir -p "$upperDir" "$workDir"
mount -t overlay overlay -o lowerdir="$cache:$data",upperdir="$upperDir",workdir="$workDir" "$runDir"
cd "$runDir"

dos2unix "/root/parser.patch" ./includes/xmlparser.inc.php
patch -p 1 ./includes/xmlparser.inc.php "/root/parser.patch"

if [ -n "$MASTERADMIN_USER" ]; then
    loginTag="tmlogin"
    ipTag="ipaddress"
    adminPath="$settingsPath/aseco/masteradmins"
    nodesPath="$adminPath/*"
    namePath="$nodesPath[1]"
    ipPath="$nodesPath[2]"

    if [ "$(xmlstarlet select --template -v "count($nodesPath)" "$config")" -lt 1 ]; then
        xmlstarlet edit --inplace --subnode "$adminPath" --type elem -n "$loginTag" "$config"
    fi

    if [ "$(xmlstarlet select --template -v "count($nodesPath)" "$config")" -lt 2 ] ||
        [ "$(xmlstarlet select --template -v "name($ipPath)" "$config")" != "$ipTag" ]; then
        xmlstarlet edit --inplace --append "$namePath" --type elem -n "$ipTag" "$config"
    fi

    xmlstarlet edit --inplace --update "$namePath" --value "$MASTERADMIN_USER" "$config"

    if [ -z "$MASTERADMIN_IP" ]; then
        xmlstarlet edit --inplace --delete "$ipPath" "$config"
    else
        xmlstarlet edit --inplace --update "$ipPath" --value "$MASTERADMIN_IP" "$config"
    fi
fi

for i in $(seq 0 2 $((${#tmOptions[@]} - 1))); do
    var="${tmOptions[$i]}"
    option="${tmOptions[$(($i + 1))]}"
    value="${!var}"

    if [ -n "$value" ]; then
        xmlstarlet edit --inplace --update "$serverPath/$option" --value "$value" "$config"
    fi
done

for i in $(seq 0 2 $((${#groups[@]} - 1))); do
    var="${groups[$i]}"
    group="${groups[$(($i + 1))]}"
    value="${!var}"
    path="/lists/$group"

    echo "$value" | while read user; do
        name="$(echo "$user" | LC_ALL="C" perl -pe "s/$userPattern/\1/")"
        ip="$(echo "$user" | LC_ALL="C" perl -pe "s/$userPattern/\3/")"
        xmlstarlet edit --inplace --subnode "$path" --type elem -n "tmlogin" --value "$name" "$adminConfig"

        if [ -n "$ip" ]; then
            xmlstarlet edit --inplace --subnode "$path" --type elem -n "ipaddress" --value "$ip" "$adminConfig"
        fi
    done
done

for i in $(seq 0 2 $((${#sqlOptions[@]} - 1))); do
    var="${sqlOptions[$i]}"
    option="${sqlOptions[$(($i + 1))]}"
    value="${!var}"
    xmlstarlet edit --inplace --update "$settingsPath/$option" --value "$value" "$dbConfig"
done

for i in $(seq 0 2 $((${#dediOptions[@]} - 1))); do
    var="${dediOptions[$i]}"
    option="${dediOptions[$(($i + 1))]}"
    value="${!var}"

    if [ -n "$value" ]; then
        xmlstarlet edit --inplace --update "/dedimania/masterserver_account/$option" --value "$value" "$dediConfig"
    fi
done

if [ -n "$X1_EXTRA_PLUGINS" ]; then
    for plugin in $X1_EXTRA_PLUGINS; do
        xmlstarlet edit --inplace --subnode "$pluginPath" --type elem -n "$pluginTag" --value "$plugin" "$pluginConfig"
    done
fi

if [ -n "$X1_DISABLED_PLUGINS" ]; then
    for i in $(seq 1 "$(xmlstarlet select --template -v "count($pluginPath/$pluginTag)" "$pluginConfig")"); do
        for plugin in $X1_DISABLED_PLUGINS; do
            path="$pluginPath/$pluginTag[$i]"

            if [ "$(xmlstarlet select --template -v "$path/text()" "$pluginConfig")" == "$plugin" ]; then
                xmlstarlet edit --inplace --delete "$path" "$pluginConfig"
            fi
        done
    done
fi

$@