# shellcheck shell=dash

___x_cmd log init ish

# xrc:mod:lib     ish   __runcmd

___x_cmd_ish___main(){
    [ "$#" -gt 0 ] ||       set -- --help

    local op="$1";          shift
    case "$op" in
        -h|--help)          ___x_cmd help -m ish    "$@";    return 0 ;;
        ver|version)        ___x_cmd_ish_version ;;

        ka|keepawake)       ___x_cmd_ish_ka         "$@" ;;

        cr)                 ___x_cmd_ish_cr         "$@" ;;

        prep|prepare)       ___x_cmd_ish_prep       "$@" ;;

        *)                  N=ish M="Unknown subcmd -> $op" log:ret:64 ;;
    esac
}

___x_cmd_ish_version(){
    printf "version:  ";  ___x_cmd_cmds cat /proc/ish/version
    printf "colors:\n";   ___x_cmd_cmds cat /proc/ish/colors
}

___x_cmd_ish_prep(){
    # [ ! -e /ish ] || ___x_cmd_ish_cr

    # sqlite
    ___x_cmd apk add    curl git fzf bash jq yq sqlite python3
    # regenerate all ...
    # don't generate files again ...
    ___x_cmd boot init
}

# Open the app then set keepawake ...
# m ka
___x_cmd_ish_ka(){
    ish:info "Notice, choose 'Always'."
    ish:info "If this option is unavaiable, go to Preference -> Privacy -> Location Services, grant ish 'Always'."
    cat /dev/location > /dev/null &  # try not using ___x_cmd_cmds
}


___x_cmd_ish_cr(){
    local apkver="${1:-"v3.18"}"

    if ___x_cmd websrc is cn; then
        ish:info "Changing apk repo -> https://mirrors.tuna.tsinghua.edu.cn/alpine/$apkver"
        printf "%s\n" \
            "https://mirrors.tuna.tsinghua.edu.cn/alpine/$apkver/main"      \
            "https://mirrors.tuna.tsinghua.edu.cn/alpine/$apkver/community" > /etc/apk/repositories
    else
        ish:info "Changing apk repo -> https://dl-cdn.alpinelinux.org/alpine/$apkver"
        printf "%s\n" \
            "https://dl-cdn.alpinelinux.org/alpine/$apkver/main"      \
            "https://dl-cdn.alpinelinux.org/alpine/$apkver/community" > /etc/apk/repositories
    fi

    [ ! -e /ish ] || ___x_cmd_cmds rm -rf /ish || true
    ___x_cmd_cmds apk upgrade && ___x_cmd_cmds apk fix
}

