#!/bin/env fish
begin
    set -l dir (status dirname)
    source "$dir/../../Scripts/software.fish"

    function configureSW -V dir
        sudo cp "$dir/rclone.service" "$dir/rclone.target" "$dir/rclone@.service" /etc/systemd/user
    end

    function userConfig -V dir -a name
        source "$dir/../../Scripts/config.fish"
        set -l key "programs.rclone.configurations"
        set -l configs (getUserConfig "$name" "$key" --apply "builtins.attrNames" --json)

        if [ (echo "$configs" | jq "length") -gt 0 ]
            if [ "$XDG_SESSION_TYPE" = tty ]
                set -l sessionPid
                set -l freeTty
                set -l service
                set -l sessionConfig
                set -l welcomeConfig ~"$name"/.config/plasma-welcomerc
                set -l entryPoint ~"$name"/.config/autostart/PortValhallaProfile.desktop
                sudo -u "$name" mkdir -p "$(dirname "$entryPoint")"

                begin
                    set -l file (sudo mktemp)
                    sudo openvt -sw -- bash -c "tty > $(string escape $file)"
                    set freeTty (basename (sudo cat $file))
                    sudo rm $file
                end

                set service "getty@$freeTty"
                set sessionConfig "/etc/systemd/system/$service.service.d/autologin.conf"
                sudo mkdir -p (dirname $sessionConfig)

                begin
                    printf %s\n \
                        "[General]" \
                        "LastSeenVersion=1.0.0" \
                        "ShowUpdatePage=false"
                end | sudo -u "$name" tee "$welcomeConfig" >/dev/null

                begin
                    printf %s\n \
                        "#!/user/bin/env xdg-open" \
                        "[Desktop Entry]" \
                        "Name=PortValhalla Profile" \
                        "Type=Application" \
                        "Terminal=false" (
                            printf "%s " \
                                "Exec=env" \
                                "VALHALLA_REQUEST_LOGOUT=1" \
                                "CONFIG_NAME=$(echo "$CONFIG_NAME" | string escape)" \
                                "konsole -e fish $(realpath (status filename) | string escape) userConfig"
                        )
                end | sudo -u "$name" tee "$entryPoint" >/dev/null

                sudo chmod +x "$entryPoint"

                begin
                    printf %s\n \
                        "[Service]" \
                        "ExecStart=" \
                        "ExecStart=-/sbin/agetty -o '-p -f -- \\u' --noclear --autologin $name %I \$TERM"
                end | sudo tee "$sessionConfig" >/dev/null

                sudo systemctl daemon-reload
                sudo systemctl restart $service

                while [ -z "$sessionPid" ]
                    set sessionPid (sudo pgrep -t $freeTty -u "$name")
                end

                sudo openvt -sw -- sudo -u "$name" env (sudo cat /proc/$sessionPid/environ | string split0) /usr/lib/plasma-dbus-run-session-if-needed startplasma-wayland
                sudo rm "$entryPoint"
                sudo rm "$welcomeConfig"
                sudo rm "$sessionConfig"
                sudo rmdir (dirname "$sessionConfig")
                sudo systemctl daemon-reload
            else if [ -n "$name" ] && [ "$name" != "$USER" ]
                sudo -Eu "$name" CONFIG_NAME="$CONFIG_NAME" fish "$(status filename)" userConfig
            else
                systemctl --user enable rclone.service
                echo "Please complete the setup of your rclone configurations!"
                mkdir -p ~/.mnt
                touch ~/.mnt/.trackerignore

                for config in (echo "$configs" | jq '.[]' --raw-output0 | string split0)
                    set -l configKey "$key.$config"
                    set -l duration "$configKey.cacheDuration"

                    set -l serviceName "rclone@$config:$(getUserConfig "$name" "$configKey.dirName")"

                    if isUserSet "$name" "$duration"
                        set serviceName "$serviceName:$(getUserConfig "$name" "$duration")"
                    end

                    echo "Please create a remote called `$config`."
                    rclone config || true
                    systemctl --user enable "$serviceName" --now || true
                end

                echo "rclone was configured successfully!"

                if [ -n "$VALHALLA_REQUEST_LOGOUT" ]
                    read -P "Please log out"
                end
            end
        end
    end

    runInstaller $argv
end