#!/bin/sh

target_cmd="qterminal"
[ $# -ge 1 ] && target_cmd="$1"

conf_dir="$HOME/.config/lxqt"
conf_path="$conf_dir/session.conf"
env_section="[Environment]"

if [ ! -d "$conf_dir" ]; then
    exec "$target_cmd" "$@"
fi

if [ ! -f "$conf_path" ]; then
    exec "$target_cmd" "$@"
fi

temp_file=$(mktemp) || {
    exec "$target_cmd" "$@"
}
trap 'rm -f "$temp_file"' EXIT

awk -v section="$env_section" '
    BEGIN {FS="="}
    /^$/ || /^#/ {next}
    $0 == section {in_section=1; next}
    /^\[/ {in_section=0}
    in_section && NF >= 2 {
        key = $1
        sub(/^[ \t]+|[ \t]+$/, "", key)
        value = substr($0, index($0, "=")+1)
        sub(/^[ \t]+|[ \t]+$/, "", value)
        if (key ~ /^[a-zA-Z_][a-zA-Z0-9_]*$/) {
            print key "=" value
        }
    }
' "$conf_path" > "$temp_file"

while IFS= read -r line; do
    case "$line" in
        \#*)
            continue
            ;;
        *)
            key=${line%%=*}
            value=${line#*=}
            if [ -n "$key" ] && [ -n "$value" ]; then
                eval "export $key=\"$value\""
            fi
            ;;
    esac
done < "$temp_file"

exec "$target_cmd" "$@"
