#!/usr/bin/env bash

USER=${SUDO_USER:-$USER}
USER_HOME=$(getent passwd $USER | cut -d: -f6)
if [ -z "$XDG_CONFIG_HOME" ]; then
  XDG_CONFIG_HOME="$USER_HOME/.config"
fi
CONFIG_DIR="$XDG_CONFIG_HOME/xr_driver"
if [ ! -d "$CONFIG_DIR" ]; then
  mkdir -p $CONFIG_DIR
fi
if [ -z "$XDG_STATE_HOME" ]; then
  XDG_STATE_HOME="$USER_HOME/.local/state"
fi
LOG_FILE="$XDG_STATE_HOME/xr_driver/driver.log"

if [ -n "$1" ]
then
    config_file="$CONFIG_DIR/config.ini"
    config_value=""
    if [ "$1" == "--disable" ] || [ "$1" == "-d" ]; then
        config_key="disabled"
        config_value="true"
    elif [ "$1" == "--enable" ] || [ "$1" == "-e" ]; then
        config_key="disabled"
        config_value="false"
    elif [ "$1" == "--status" ] || [ "$1" == "-s" ]; then
        config_key="disabled"
    elif [ "$1" == "--vr-lite-invert-x-enable" ] || [ "$1" == "-invx" ]; then
        config_key="vr_lite_invert_x"
        config_value="true"
    elif [ "$1" == "--vr-lite-invert-x-disable" ] || [ "$1" == "-invxd" ]; then
        config_key="vr_lite_invert_x"
        config_value="false"
    elif [ "$1" == "--vr-lite-invert-y-enable" ] || [ "$1" == "-invy" ]; then
        config_key="vr_lite_invert_y"
        config_value="true"
    elif [ "$1" == "--vr-lite-invert-y-disable" ] || [ "$1" == "-invyd" ]; then
        config_key="vr_lite_invert_y"
        config_value="false"
    elif [ "$1" == "--mouse-sensitivity" ] || [ "$1" == "-ms" ]; then
        config_key="mouse_sensitivity"
        config_type="string"
        if [ -n "$2" ]; then
            config_value="$2"
        fi
    elif [ "$1" == "--debug" ]; then
        config_key="debug"
        config_type="string"
        if [ -n "$2" ]; then
            config_value="$2"
        fi
    elif [ "$1" == "--use-joystick" ] || [ "$1" == "-j" ]; then
        config_type="string"
        config_key="output_mode"
        config_value="joystick"
        config_key2="external_mode"
        config_value2="none"
    elif [ "$1" == "--use-mouse" ] || [ "$1" == "-m" ]; then
        config_type="string"
        config_key="output_mode"
        config_value="mouse"
        config_key2="external_mode"
        config_value2="none"
    elif [ "$1" == "--display-zoom" ] || [ "$1" == "-z" ]; then
        config_key="display_zoom"
        config_type="string"
        if [ -n "$2" ]; then
            config_value="$2"
        fi
    elif [ "$1" == "--external-mode" ] || [ "$1" == "-em" ]; then
        config_type="string"
        config_key="external_mode"
    elif [ "$1" == "--disable-external" ] || [ "$1" == "-de" ]; then
        config_type="string"
        config_key="external_mode"
        config_value="none"
    elif [ "$1" == "--virtual-display" ] || [ "$1" == "-vd" ]; then
        config_type="string"
        config_key="output_mode"
        config_value="external_only"
        config_key2="external_mode"
        config_value2="virtual_display"
    elif [ "$1" == "--breezy-desktop" ] || [ "$1" == "-bd" ]; then
        config_type="string"
        config_key="output_mode"
        config_value="external_only"
        config_key2="external_mode"
        config_value2="breezy_desktop"
    elif [ "$1" == "--sideview" ] || [ "$1" == "-sv" ]; then
        config_type="string"
        config_key="output_mode"
        config_value="external_only"
        config_key2="external_mode"
        config_value2="sideview"
    elif [ "$1" == "--sbs-mode-stretched" ] || [ "$1" == "-sbsms" ]; then
        config_type="string"
        config_key="sbs_mode_stretched"
        config_value="${2:-true}"
    elif [ "$1" == "--sbs-content-3d" ] || [ "$1" == "-sbs3d" ]; then
        config_type="string"
        config_key="sbs_content"
        config_value="${2:-true}"
    elif [ "$1" == "--sbs-display-size" ] || [ "$1" == "-sbsds" ]; then
        config_type="string"
        config_key="sbs_display_size"
        config_value="$2"
    elif [ "$1" == "--sbs-display-distance" ] || [ "$1" == "-sbsdd" ]; then
        config_type="string"
        config_key="sbs_display_distance"
        config_value="$2"
    elif [ "$1" == "--sideview-position" ] || [ "$1" == "-svp" ]; then
        config_type="string"
        config_key="sideview_position"
        config_value="$2"
    elif [ "$1" == "--sideview-display-size" ] || [ "$1" == "-svds" ]; then
        config_type="string"
        config_key="sideview_display_size"
        config_value="$2"
    elif [ "$1" == "--smooth-follow-enable" ] || [ "$1" == "-sfe" ]; then
        config_key="sideview_smooth_follow_enabled"
        config_value="true"
    elif [ "$1" == "--smooth-follow-disable" ] || [ "$1" == "-sfd" ]; then
        config_key="sideview_smooth_follow_enabled"
        config_value="false"
    elif [ "$1" == "--multi-tap-enable" ] || [ "$1" == "-mte" ]; then
        config_key="multi_tap_enabled"
        config_value="true"
    elif [ "$1" == "--multi-tap-disable" ] || [ "$1" == "-mtd" ]; then
        config_key="multi_tap_enabled"
        config_value="false"
    elif [ "$1" == "--smooth-follow-threshold" ] || [ "$1" == "-sft" ]; then
        config_key="sideview_follow_threshold"
        if [ -n "$2" ]; then
            config_value="$2"
        fi
    elif [ "$1" == "--disable-metrics" ] || [ "$1" == "-dm" ]; then
        config_key="metrics_disabled"
        config_value="true"
    elif [ "$1" == "--request-token" ] || [ "$1" == "--verify-token" ] || [ "$1" == "--refresh-license" ] || [ "$1" == "--get-hardware-id" ]; then
        config_type="string"
        config_key="hardware_id"
        config_file="/dev/shm/xr_driver_state"
    elif [ "$1" == "--view-log" ] || [ "$1" == "-l" ]; then
        less +F "$LOG_FILE"
    fi

    if [[ -n $config_key ]]; then
        if [ ! -f "$config_file" ]; then
            touch "$config_file"
        fi

        # non-empty config_value implies write/update, empty implies read (report status)
        if [[ -n $config_value ]]; then
            # Check if the key already exists in the config file
            if grep -q "^$config_key=" "$config_file"; then
                # Replace the existing key/value pair
                sed -i "s/^$config_key=.*/$config_key=$config_value/" "$config_file"
            else
                # Add the new key/value pair to the end of the file
                echo "$config_key=$config_value" >> "$config_file"
            fi
            if [[ -n $config_key2 ]]; then
                if grep -q "^$config_key2=" "$config_file"; then
                    sed -i "s/^$config_key2=.*/$config_key2=$config_value2/" "$config_file"
                else
                    echo "$config_key2=$config_value2" >> "$config_file"
                fi
            fi
        else
            if [ "$config_type" == "string" ]; then
              value="Not set"
            else
              value="enabled"
            fi

            while read -r line; do
                if [[ $line == "$config_key="* ]]; then
                    config_value=${line#*=}
                    if [ "$config_type" == "string" ]; then
                      value=$config_value
                    else
                      # Check if the value is "true"
                      if [ "$config_value" == "true" ]; then
                          value="disabled"
                      fi
                    fi

                    break
                fi
            done < "$config_file"

            if [ "$1" == "--request-token" ] || [ "$1" == "--verify-token" ] || [ "$1" == "--refresh-license" ]; then
                hardware_id=$value
                url="https://eu.driver-backend.xronlinux.com/tokens/v1"

                if [ "$1" == "--request-token" ]; then
                    postbody=$(jq -n \
                                --arg hardwareId "$hardware_id" \
                                --arg email "$2" \
                                '{hardwareId: $hardwareId, email: $email}')
                    message=$(curl -s -X POST -H "Content-Type: application/json" -d "$postbody" "$url" | jq -r '.message')
                elif [ "$1" == "--verify-token" ]; then
                    postbody=$(jq -n \
                                --arg hardwareId "$hardware_id" \
                                --arg token "$2" \
                                '{hardwareId: $hardwareId, token: $token}')
                    message=$(curl -s -X PUT -H "Content-Type: application/json" -d "$postbody" "$url" | jq -r '.message')
                elif [ "$1" == "--refresh-license" ]; then
                    echo "refresh_device_license=true" > /dev/shm/xr_driver_control
                    message="License refresh requested"
                fi

                if [ -n "$message" ]; then
                    echo "$message"
                fi
            else
                echo "$value"
            fi
        fi

        exit 0
    fi
fi

echo "Usage: $0 [options]
Options:
  -l, --view-log
  -d, --disable
  -e, --enable
  -s, --status
  -j, --use-joystick
  -m, --use-mouse
  -invx, --vr-lite-invert-x-enable
  -invxd, --vr-lite-invert-x-disable
  -invy, --vr-lite-invert-y-enable
  -invyd, --vr-lite-invert-y-disable
  -ms, --mouse-sensitivity [sensitivity_value]
  -mte, --multi-tap-enable
  -mtd, --multi-tap-disable
  -z, --display-zoom [zoom_value]
  -em, --external-mode
  -de, --disable-external
  -vd, --virtual-display
  -bd, --breezy-desktop
  -sv, --sideview
  -svp, --sideview-position [top_left|top_right|bottom_left|bottom_right]
  -svds, --sideview-display-size [display_size]
  -sfe, --smooth-follow-enable
  -sfd, --smooth-follow-disable
  -sft, --smooth-follow-threshold [threshold_value]
  -sbsms, --sbs-mode-stretched [true|false]
  -sbs3d, --sbs-content-3d [true|false]
  -sbsds, --sbs-display-size [display_size]
  -sbsdd, --sbs-display-distance [display_distance]
  -dm, --disable-metrics
  --request-token [email]
  --verify-token [token]
  --refresh-license
  --get-hardware-id"
