# shellcheck    shell=dash

___x_cmd_htag___ip(){
    x mkdirp "$___X_CMD_HTAG_METADATA"
    case "$1" in
        "") ___x_cmd_htag___ip_print
            ;;

        --auto)
            ___x_cmd_htag___ip_auto
            ;;

        *.*.*.*)
            ___x_cmd_htag___ip_set "$1"
            ;;
        set)
            shift
            ___x_cmd_htag___ip_set "$1"
            ;;
    esac
}

___x_cmd_htag___ip_auto(){
    local x_;
    ! ___x_cmd_htag___ip_ || \
        x ui yesno "current ip is $x_, do you want to reset it?" || return 0

    local ip;

    [ -z "$SSH_CONNECTION" ] || {
        ip="${SSH_CONNECTION#* * }"
        ip="${ip% *}"
        ___x_cmd_htag___ip set "$ip"
        return
    }

    ip="$(x ip echo)" || {
        N=host M="failed to get ip" log:ret:1
        return 1
    }

    ___x_cmd_htag___ip set "$ip"
}

___x_cmd_htag___ip_(){
    x_=
    [ -f "$___X_CMD_HTAG_METADATA/ip" ] && read -r x_ <"$___X_CMD_HTAG_METADATA/ip"
}

___x_cmd_htag___ip_print(){
    local x_
    ___x_cmd_htag___ip_ || return
    printf "%s\n" "$x_"
}

___x_cmd_htag___ip_set(){
    htag:info "Seting host ip tag as $1"
    printf "%s\n" "$1" >"$___X_CMD_HTAG_METADATA/ip"
}
