My Scripts

Bash Scripts

allfiles.sh

#!/usr/bin/env bash
# ability to ignore some file
if [[ $1 == "-h" ]]
then
    echo "un-hidden files"
    exit
fi

find . \( ! -regex '.*/\..*' \) -type f

alpine.sh

#/usr/bin/env bash

# parsing arguments
VERSION=latest
while [[ ${OPTIND} -le $# ]]; do
    getopts "lhe" opt
    case "${opt}" in
    l|h)
        echo "aarch64 riscv64 x86_64 16.04 18.04 20.04 22.04 22.10 23.04 latest -h -e"
        exit 0
    ;;
    e)
        ECHO=1
    ;;
    *)
        arg=${!OPTIND}
        case "$arg" in
        aarch64|riscv64|x86_64)
            ARCH=$arg
        ;;
        *)
            VERSION=$arg
        ;;
        esac
        shift
    ;;
    esac
done
NAME=alpine-${ARCH}

OPTS=(
    "-u root"
    # "--userns=keep-id" # [rootless container]
    "--env debian_chroot=$NAME"
    # "-h" "container-$NAME" # host name
    "-h localhost" # host name # avoid edit /etc/hosts
    "--name=$NAME-$VERSION" # container name

    "-v $HOME:$HOME"
    "-v $HOME:/root"
    "-v /nix:/nix" # make sure symbol links in home work
    "-v /run/binfmt:/run/binfmt"
    "-w $PWD" # working directory

    # this will cause guest /etc/hosts override by host's
    # use host ip instead, see host's ip address
    "--network=host" # use host network stack

    "-it"
    "$NAME:$VERSION"
    "/bin/sh"
)

# Pull image
podman images ${NAME}:${VERSION} | grep ${NAME} &> /dev/null
if [[ $? != 0 ]]; then
        image_id=$(podman pull --arch ${ARCH} alpine:$VERSION)
    podman tag $image_id ${NAME}:${VERSION}
fi

# Run container
if [[ -z $ECHO ]]; then
    eval "podman run ${OPTS[@]}"
    podman commit $NAME-$VERSION $NAME:$VERSION
    podman rm $NAME-$VERSION
else
    echo "podman run ${OPTS[@]}"
    echo podman commit $NAME-$VERSION $NAME:$VERSION
    echo podman rm $NAME-$VERSION
fi

asm.sh

#!/usr/bin/env bash
# input: native assmblies
# output: native machine codes
CMD="${0##*/}"
usage() {
    echo "asm => bin"
    echo "Usage: ${CMD} [-h] <asm>"
    echo "  Convert <asm> to machine code, by GNU assembler 'as'."
    echo "Symbol needs to be escaped:"
    echo "  dolar (\\\$), hash tag (\\#), simicolon (\\;), slash (\\\\)"
    echo "Example:"
    echo "  ${CMD} \"int \\\$0x80\""
    echo "  ${CMD} \"add \\\$12, %eax\""
    echo "  ${CMD} \"nop\\nnop\""
    echo "  ${CMD} \"nop;nop\""
    echo "  ${CMD} \"movl \\\$0x5657e589, 0x55(%esp)\""
    echo "  ${CMD} \"movq \\\$0x12345678, %gs:0x9abcdef(%rax, %rbx, 2)\""
    exit 0
}
if [[ $# -lt 1 ]]
then
    usage
fi
if [[ $1 == "-h" ]]
then
    usage
fi

echo -e "$@" | as -al -o /dev/null
# echo -e "$@" | as -al --32 -o /dev/null

chroot.sh

#!/usr/bin/env bash

# TODO: /debootstrap/debootstrap --second-stage
#       failed, because of no mail group
#       see /debootstrap/debootstrap.log

CHROOT=~/Img/chroot_u22_a64.1
# $HOME is defined in host bash
#HOME=/home/xieby1

# ${HOME} /proc /sys /dev
DIRS="/nix /run/binfmt"
for dir in ${DIRS}; do
    sudo mkdir -p ${CHROOT}${dir}
    sudo mount --bind ${dir} ${CHROOT}${dir}
done
FILES="/etc/hosts /etc/passwd /etc/group"
for file in ${FILES}; do
    sudo touch ${CHROOT}${file}
    sudo mount --bind ${file} ${CHROOT}${file}
done
echo miao
CMD=(
    "sudo"
    "chroot"
    # "--userspec=xieby1:users"
    "${CHROOT}"
    "/usr/bin/env"
    # start with an empty environment
    "-i"
    "HOME=${HOME}"
    "TERM=$TERM"
    "PS1='\u:\w\$ '"
    "PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin"
    "/bin/bash"
)
eval "${CMD[@]}"
echo wang

for dir in ${DIRS}; do
    sudo umount ${CHROOT}${dir}
done
for file in ${FILES}; do
    sudo umount ${CHROOT}${file}
done

conenv.sh

#!/usr/bin/env bash

# TODO: auto detect docker and podman

usage() {
    echo "Container Environment"
    echo "Usage: ${0##*/} [options] <container>"
    echo "Options:"
    echo "  -h: show this help"
    echo "  -e: echo command, without execution"
    echo "  -c: create image"
    exit 0
}

while [[ ${OPTIND} -le $# ]]
do
    getopts "lhce" opt
    case "${opt}" in
    l)
        CONTAINERS=""
        for FILE in ~/Gist/script/container/*; do
            FILE=${FILE##*/}
            CONTAINERS+="${FILE%.*} "
        done
        echo "${CONTAINERS} -h -e -c"
        exit 0
    ;;
    h)
        usage
    ;;
    c)
        CREATE=1
    ;;
    e)
        ECHO=1
    ;;
    *)
        CONTAINER=${!OPTIND}
        CONTAINERFILE=~/Gist/script/container/${CONTAINER}.*
        shift
    esac
done
if [[ -z ${CONTAINERFILE} ]]; then
    usage
fi

# DONE: sudo broken inside container
#       https://www.redhat.com/sysadmin/sudo-rootless-podman
#   tldr: not recommend use su/sudo in rootless container
# podman volumes always owned by root:
#   https://github.com/containers/podman/issues/2898
# if the first line of containerfile contains sudo
if head --lines=1 ${CONTAINERFILE} | grep sudo > /dev/null; then
    SUDO="sudo"
fi
if head --lines=1 ${CONTAINERFILE} | grep commit > /dev/null; then
    COMMIT=1
fi

CMDRUN=("run")
if [[ -n ${SUDO} ]]; then
    CMDRUN+=("-u" "${USER}") # [root container]
else
    CMDRUN+=("--userns=keep-id") # [rootless container]
fi
CMDRUN+=(
#"-d" # deamon, not exit
# "--rm" # exit then remove this container
"--env" "debian_chroot=$CONTAINER"
# "-h" "container-$CONTAINER" # host name
"-h" "localhost" # host name # avoid edit /etc/hosts
"--name=$CONTAINER" # container name

"-v" "/home/${USER}:/home/${USER}"
"-v" "/nix:/nix" # make sure symbol links in home work

"-w" "${PWD}" # working directory

# this will cause guest /etc/hosts override by host's
# use host ip instead, see host's ip address
"--network=host" # use host network stack

"-it"
"$CONTAINER"
# "/usr/bin/tmux"
)

CMDCREATE=(
"build"
"--network=host"
"--build-arg=UID=${UID}"
"--build-arg=USER=${USER}"
"-t" "${CONTAINER}"
"-f" "${CONTAINERFILE}"
"."
)

if [[ ${CREATE} == 1 ]]; then
    CMD="${CMDCREATE[@]}"
else
    CMD="${CMDRUN[@]}"
fi

# detect container backend
if command -v podman > /dev/null; then
    BACKEND=podman
elif command -v docker > /dev/null; then
    BACKEND=docker
else
    echo "Not found valid container backend"
    exit 1
fi
CMD=("${SUDO}" "${BACKEND}" "${CMD[@]}")

if [[ ${ECHO} == 1 ]]; then
    CMD=("echo" "${CMD[@]}")
fi
eval "${CMD[@]}"

if [[ -z ${CREATE} && -z ${ECHO} ]]; then
    if [[ -n ${COMMIT} ]]; then
        eval "${SUDO} ${BACKEND} commit ${CONTAINER} ${CONTAINER}"
    fi
    # remove container
    eval "${SUDO} ${BACKEND} rm ${CONTAINER}"
fi

coninit.sh

#/usr/bin/env bash
# run this script in ubuntu based docker
echo 'root:miqbxgyfdA.PY' | chpasswd -e
useradd -u 1000 -G users,sudo -p miqbxgyfdA.PY -s /bin/bash xieby1
# sed -i 's/http.*com/http:\/\/mirrors.tuna.tsinghua.edu.cn/g' /etc/apt/sources.list
echo 'Acquire::http::Proxy "http://127.0.0.1:8889";' > /etc/apt/apt.conf
apt update
apt install -y sudo

essays.sh

#!/usr/bin/env -S bash -i
pdfs=$(find ~/Documents/Tech/ -name "*.pdf")
for pdf in $pdfs; do
    filename=${pdf##*/}
    publication_citation_pdf=${filename#*.*.*.}
    publication=${publication_citation_pdf%.*.*}
    echo $publication
    # [[ $publication == "$1" ]] && echo ${pdf#*Tech/}
done

ff.sh

#!/usr/bin/env bash
# This script does not use the fzf to search,
# instead it use `rg` (case-ignored mode) to search,
# fzf is just a selector or a UI infrastructure to call `rg`
# From https://github.com/junegunn/fzf/wiki/Examples#searching-file-contents
##
# Interactive search.
# Usage: `ff` or `ff <folder>`.
#

if [[ $1 == "-h" ]]
then
    echo "fuzzy find"
    exit
fi

[[ -n $1 ]] && cd $1 # go to provided folder or noop
RG_DEFAULT_COMMAND="rg -i -l --hidden --no-ignore-vcs --sortr path"

selected=$(
FZF_DEFAULT_COMMAND="rg --files" fzf \
  -m \
  -e \
  --ansi \
  --phony \
  --reverse \
  --bind "ctrl-a:select-all" \
  --bind "f12:execute-silent:(subl -b {})" \
  --bind "change:reload:$RG_DEFAULT_COMMAND {q} || true" \
  --preview "rg -i --pretty --context 2 {q} {}" | cut -d":" -f1,2
)

echo "${selected}"
# [[ -n $selected ]] && gedit $selected # open multiple files in editor 

formatxml.sh

#!/usr/bin/env bash

if [[ $1 == "-h" ]]
then
    echo "${0##*/} <xml_file>"
    echo "  Format xml file in place."
    echo "  If the file extension is .drawio,"
    echo "  this script will try to uncompress it first."
    exit
fi

IN=$1
BAK=${1%.*}.bak.${1##*.}
mv "$IN" "$BAK"
if [[ "${IN##*.}" == "drawio" ]]
then
    drawio -u -x -f xml "$BAK" &> /dev/null
    xmllint --format "${BAK%.*}.xml" > "$IN"
    rm -f "${BAK%.*}.xml"
else
    xmllint --format "$BAK" > "$IN"
fi
mv "$BAK" "/tmp/${IN##*/}"

grep.sh

#!/usr/bin/env bash

if [[ $1 == "-h" ]]
then
    echo "my grep"
    exit
fi

EXTRA_OPTION=(
    --color=always
    --line-number
)

EXCLUDE_BASIC=(
    -I
    --exclude="*.html"
    --exclude="*.js"
    --exclude="*.svg"
    --exclude="*.obj"
    --exclude="*.json"
    --exclude="*.drawio"
    --exclude="*.xml"
    --exclude="*.css"
    --exclude="*.csv"
    --exclude="tags"
    --exclude-dir="expm"
    --exclude-dir=".git"
    --exclude-dir=".stversions"
)

grep "$1" . -r \
    ${EXTRA_OPTION[@]} \
    ${EXCLUDE_BASIC[@]} \
    ${@:2}

ldd-grep.sh

#!/usr/bin/env bash
# input: the file (or diretory) to be examed,
# output: its (or files under the directory, recursively) depending lib

# default value
TARGET=.

while [[ ${OPTIND} -le $# ]]; do
    getopts "ho:" opt
    case "${opt}" in
        h)
            echo "gather dep so"
            echo "Usage: ${0##*/} [-o DEST] [ FILE | DIR ]"
            echo "  List the lib dependencies of FILE or files under DIR"
            echo "  If FILE or DIR is not specified, '.' will be used"
            echo "  If -o DEST is specifed, dependencies will be copied to DEST"
            exit 0
            ;;
        o)
            if [[ -e ${OPTARG} ]]; then
                if [[ -d ${OPTARG} ]]; then
                    DEST_DIR=${OPTARG}
                else
                    echo "-o ${OPTARG} should be a directory"
                    exit 1
                fi
            else
                echo "${OPTARG} not exists"
                exit 1
            fi
            ;;
        ?)
            TARGET=${!OPTIND}
            shift
            ;;
        *)
            echo "unknown options arg${OPTIND} ${OPTARG}"
            exit 1
            ;;
    esac
done

ldd_real_path()
{
    ldd "$1" 2> /dev/null | while read Line; do
        # start with /
        if [[ $Line =~ ^\s*\/ ]]; then
            echo ${Line%% *}
        else
            _temp=${Line##*=> }
            echo ${_temp%% *}
        fi
    done

    # ldd "$1" 2> /dev/null |\
    #     sed 's/.*=>//' |\
    #     grep -E -o '\/.*\s' |\
    #     sed 's/\s//'
}

get_dependencies()
{
    if [[ -z ${DEST_DIR} ]]; then
        ldd_real_path $1
    else
        ldd_real_path $1 | while read DEP; do
            LIB_NEW_PATH="${DEST_DIR}/${DEP#/}"
            LIB_NEW_DIR="${LIB_NEW_PATH%/*}/"
            mkdir -p ${LIB_NEW_DIR}
            cp -n -v ${DEP} ${LIB_NEW_DIR}
        done
    fi
}

echo "ldd-grep from ${TARGET} to ${DEST_DIR}"

if [[ -d ${TARGET} ]]; then
    for FILE in $(find ${TARGET} -type f); do
        get_dependencies ${FILE}
    done
elif [[ -f ${TARGET} ]]; then
    get_dependencies ${TARGET}
fi

ls-git.sh

#!/usr/bin/env bash
# ls files & directories only contaion in git repo
if [[ $1 == "-h" ]]
then
    echo "ls files in git"
    exit
fi
FILES_IN_GIT=$(git ls-files .)
if [[ $? -ne 0 ]]; then
    exit $?
fi
echo ${FILES_IN_GIT} | \
    tr " " "\n" | \
    sed s,/.*,, | \
    uniq | \
    xargs ls -d --color=auto $*

malq.sh

#!/usr/bin/env bash
# mips as ld qemu
mipsel-linux-gnu-as -gstabs -o ${1%.*}.o $1
mipsel-linux-gnu-ld -o ${1%.*} ${1%.*}.o
/nix/store/00nnmqad2x3ssc9y2pn3kx0gh5m92bxv-qemu-7.1.0/bin/qemu-mipsel ${1%.*}

nbd-mount.sh

#!/usr/bin/env bash

# reference to https://askubuntu.com/questions/19430/mount-a-virtualbox-drive-image-vdi
# input: disk image to be mounted, mount destination folder

# clean should be done manually,
## sudo umount MOUNT_DIR
## sudo qemu-nbd -d /dev/nbd/nbd0p1

usage() {
    echo "nbd mount"
    echo "Usage: ${0##*/} DISK_IMAGE [-o MOUNT_DIR]"
    echo "  export DISK_IMAGE using the NBD protocol"
    echo "  mount the nbd dev to MOUNT_DIR"
    echo "  default MOUNT_DIR is c/, not create dir if c/ not exist"
    exit 0
}

if [[ $# -lt 1 ]]
then
    usage
fi

while [[ ${OPTIND} -le $# ]]; do
    getopts "ho:" opt
    case "${opt}" in
        h)
            usage
            ;;
        o)
            MOUNT_DIR=${OPTARG}
            ;;
        ?)
            DISK_IMAGE=${!OPTIND}
            shift
            ;;
        *)
            echo "unknown arg${OPTIND} ${OPTARG}"
            exit 1
            ;;
    esac
done

if [[ -z "${DISK_IMAGE}" ]]; then
    echo "DISK_IMAGE not specified"
    exit 1
fi
if [[ -z "${MOUNT_DIR}" ]]; then
    MOUNT_DIR=c
fi

# check nbd kernel module
if [[ ! -e /dev/nbd0 ]]; then
    sudo modprobe nbd max_part=16
fi
# create nbd
  # TODO: check available /dev/nbd
sudo qemu-nbd -c /dev/nbd0 ${DISK_IMAGE}
# mount
sudo mount /dev/nbd0p1 ${MOUNT_DIR}
# TODO: umount
# TODO: delete nbd

notify.sh

#!/usr/bin/env bash

if [[ $# -eq 0 || ($# -eq 1 && $1 == "-h") ]]; then
    echo "Popup desktop notification messages. (Default messages: $DEFAULT_MSG)"
    echo "Usage: ${0##*/} [-h] <Command and its args ...>"
    exit
fi

eval "$@"

if [[ "$TERM" =~ tmux ]]; then
    # https://github.com/tmux/tmux/issues/846
    printf '\033Ptmux;\033\x1b]99;;%s\033\x1b\\\033\\' "$*"
else
    printf '\x1b]99;;%s\x1b\\' "$*"
fi

pdbsf.sh

#!/usr/bin/env bash
if [[ $1 == "-h" ]]
then
    echo "pdb src file"
    exit
fi
CVDUMP=~/Softwares/Packages/Kernel/Windows/tools/cvdump.exe

wine "${CVDUMP}" -sf $1

pdfbookmark.sh

#!/usr/bin/env bash

echoHelp() {
    echo "md <=> pdf toc"
    echo "Usage:"
    echo "  Extract Bookmarks from pdf: ${0##*/} FILE.pdf [FILE.md]" 
    echo "  Update Bookmarks to pdf:  ${0##*/} FILE.md FILE.pdf"
    exit 0
}

# default value
BKMRK="Bookmark"
BEGIN="${BKMRK}Begin"
TITLE="${BKMRK}Title"
LEVEL="${BKMRK}Level"
PGNUM="${BKMRK}PageNumber"
## markdown default value
INDENTNUM=2
INDENTSYM="*"
INDENTSYM_ESC="\*"
PGNUMDELIMIT="@"

# value
TITLEV=""
LEVELV=""
PGNUMV=""

pdfdata_to_markdown() {
    #for LINE in $1; do
    cat $1 | while read LINE; do
        #echo ${LINE}
        case ${LINE} in
            ${BEGIN}*)
                TITLEV=""
                LEVELV=""
                PGNUMV=""
                ;;
            ${TITLE}*)
                TITLEV=${LINE#"${TITLE}: "}
                ;;
            ${LEVEL}*)
                LEVELV=${LINE#"${LEVEL}: "}
                ;;
            ${PGNUM}*)
                PGNUMV=${LINE#"${PGNUM}: "}
                output=""
                while [[ ${#output} -lt $(((LEVELV - 1)*INDENTNUM)) ]]; do
                    output="${output} "
                done
                output="${output}${INDENTSYM} ${TITLEV} ${PGNUMDELIMIT}${PGNUMV}"
                echo -e "${output}"
                ;;
        esac
    done
}

markdown_to_pdfdata() {
    IFS=''
    cat $1 | while read LINE; do
    indentStr="${LINE%%${INDENTSYM_ESC}*}"
    indentStrLen="${#indentStr}"
    LEVELV=$((indentStrLen / INDENTNUM + 1))

    PGNUMV="${LINE##*${PGNUMDELIMIT}}"

    TITLEV="${LINE#*${INDENTSYM_ESC} }"
    TITLEV="${TITLEV%${PGNUMDELIMIT}*}"

    echo "${BEGIN}"
    echo "${TITLE}: ${TITLEV}"
    echo "${LEVEL}: ${LEVELV}"
    echo "${PGNUM}: ${PGNUMV}"
done
}

# main function
FILE1=""
FILE2=""

while [[ ${OPTIND} -le $# ]]; do
    getopts "h" opt
    case "${opt}" in
        h)
            echoHelp
            ;;
        ?)
            if [[ -z ${FILE1} ]]; then
                FILE1=${!OPTIND}
            elif [[ -z ${FILE2} ]]; then
                FILE2=${!OPTIND}
            else
                echoHelp
            fi
            shift
            ;;
    esac
done

## create temporary directory
tempDir="/dev/shm/${0##*/}"
if [[ ! -d ${tempDir} ]]; then
    mkdir ${tempDir}
fi

## check input files
if [[ -z ${FILE1} ]]; then
    echoHelp
fi
if [[ -z ${FILE2} ]]; then
    FILE2=${FILE1%.*}.md
fi

tempFile=${tempDir}/${FILE2##*/}
tempFile=${tempFile%.*}
if [[ ${FILE1##*.} == "md" ]]; then
### md to pdf
    pdftk ${FILE2} dump_data_utf8 output ${tempFile}.dumpdata

    #### clear bookmark info
    grep -v "${BKMRK}" ${tempFile}.dumpdata > ${tempFile}.cleardata
    cp ${tempFile}.cleardata ${tempFile}.newdata

    #### append bookmark info
    markdown_to_pdfdata ${FILE1} >> ${tempFile}.newdata
    pdftk ${FILE2} update_info ${tempFile}.newdata output ${FILE2%.*}.toc.pdf
elif [[ ${FILE2##*.} == "md" ]]; then
    pdftk ${FILE1} dump_data_utf8 output ${tempFile}.dumpdata

    pdfdata_to_markdown ${tempFile}.dumpdata > ${FILE2}
else
    echoHelp
fi

## clear tempDir
#rm -r ${tempDir}

pwrThr.sh

#!/usr/bin/env bash

# Toggle Lenovo Power Threshold
# References
#  https://askubuntu.com/questions/1038471/problem-with-lenovo-battery-threshold
if [[ $1 == "-h" ]]
then
    echo "toggle pwrThr"
    exit
fi

INTERFACE="/sys/bus/platform/drivers/ideapad_acpi/VPC2004:00/conservation_mode"
THRSTATE=$(cat "${INTERFACE}")

# redirection is done by shell, so `sudo echo XXX >> XXX` is not work
# refers to: https://askubuntu.com/questions/230476/how-to-solve-permission-denied-when-using-sudo-with-redirection-in-bash
sudo bash -c "echo $((! THRSTATE)) > ${INTERFACE}"

echo "Power Threshold $THRSTATE => $((! THRSTATE))"

qemu-android.sh

#!/bin/bash
# By Chih-Wei Huang <cwhuang@linux.org.tw>
# License: GNU Generic Public License v2

continue_or_stop()
{
        echo "Please Enter to continue or Ctrl-C to stop."
        read
}

QEMU_ARCH=`uname -m`
QEMU=qemu-system-${QEMU_ARCH}

which $QEMU > /dev/null 2>&1 || QEMU=qemu-system-i386
if ! which $QEMU > /dev/null 2>&1; then
        echo -e "Please install $QEMU to run the program.\n"
        exit 1
fi

cd ${OUT:-ANDROID_ROOT}

[ -e system.img ] && SYSTEMIMG=system.img || SYSTEMIMG=system.sfs

if [ -d data ]; then
        if [ `id -u` -eq 0 ]; then
                DATA="-virtfs local,id=data,path=data,security_model=passthrough,mount_tag=data"
                DATADEV='DATA=9p'
        else
                echo -e "\n$(realpath data) subfolder exists.\nIf you want to save data to it, run $0 as root:\n\n$ sudo $0\n"
                continue_or_stop
        fi
elif [ -e data.img ]; then
        if [ -w data.img ]; then
                DATA="-drive index=2,if=virtio,id=data,file=data.img"
                DATADEV='DATA=vdc'
        else
                echo -e "\n$(realpath data.img) exists but is not writable.\nPlease grant the write permission if you want to save data to it.\n"
                continue_or_stop
        fi
fi

run_qemu_on_port()
{
        $QEMU -enable-kvm \
        -kernel kernel \
        -append "CMDLINE console=ttyS0 RAMDISK=vdb $DATADEV" \
        -initrd initrd.img \
        -m 2048 -smp 2 -cpu host \
        -usb -device usb-tablet,bus=usb-bus.0 \
        -machine vmport=off \
        -soundhw ac97 \
        -serial mon:stdio \
        -boot menu=on \
        -drive index=0,if=virtio,id=system,file=$SYSTEMIMG,format=raw,readonly \
        -drive index=1,if=virtio,id=ramdisk,file=ramdisk.img,format=raw,readonly \
        -netdev user,id=mynet,hostfwd=tcp::$port-:5555 -device virtio-net-pci,netdev=mynet \
        $DATA $@
}

run_qemu()
{
        port=5555
        while [ $port -lt 5600 ]; do
                run_qemu_on_port $@ && break
                let port++
        done
}

# Try to run QEMU in several VGA modes
run_qemu -vga virtio -display sdl,gl=on $@ || \
run_qemu -vga qxl -display sdl $@ || \
run_qemu -vga std -display sdl $@ || \
run_qemu $@

qpaeq.sh

#!/usr/bin/env bash

pactl load-module module-equalizer-sink
pactl load-module module-dbus-protocol
qpaeq

quteapp.sh

#!/usr/bin/env bash

usage()
{
    echo "Usage: ${0##*/} <window> <url>"
    exit 0
}

if [[ $# -lt 2 || $1 == "-h" ]]
then
    usage
fi

WID=$(xdotool search --onlyvisible --name "${1}.*qutebrowser")
URL=$2

if [[ -z ${WID} ]]
then
    qutebrowser "$URL"
else
    xdotool set_desktop_for_window ${WID} $(xdotool get_desktop)
    xdotool windowactivate ${WID}
fi

resize_gif.sh

#!/usr/bin/env bash

if [[ $# -eq 0 ||  $1 == "-h" || $1 == "--help" ]]
then
    echo "gif<=10M"
    echo "Usage: ${0##*/} <xxx.gif>"
    echo "  Compress <xxx.gif> under and near 10M,"
    echo "  output to <xxx.resized.gif>"
    exit 0
fi

# functions
get_pic_size()
{
    du "$1" | sed -n 's/\([0-9]*\).*/\1/p'
}

get_pic_width()
{
    identify "$1" | sed -n '1s/\S*\s\S*\s\([0-9]*\)x[0-9]*.*/\1/p'
}

get_pic_height()
{
    identify "$1" | sed -n '1s/\S*\s\S*\s[0-9]*x\([0-9]*\).*/\1/p'
}

# constants
VERBOSE=1
PIC_ORIG=$1
PIC_RESZ=${PIC_ORIG%.*}.resized.${PIC_ORIG##*.}
TEMP_DIR=${HOME}/.miao_temp
PIC_TEMP=${TEMP_DIR}/${PIC_RESZ##*/}
PIC_SIZE_LIMIT=9600
PIC_ORIG_SIZE=$(get_pic_size "$PIC_ORIG")
PIC_ORIG_WIDTH=$(get_pic_width "$PIC_ORIG")
PIC_ORIG_HEIGHT=$(get_pic_height "$PIC_ORIG")
# variables
PIC_RESZ_SIZE=$PIC_ORIG_SIZE
PIC_RESZ_WIDTH=$PIC_ORIG_WIDTH

#echo size $PIC_RESZ_SIZE width $PIC_RESZ_WIDTH

mkdir -p ${TEMP_DIR}

while [[ $PIC_RESZ_SIZE -gt $PIC_SIZE_LIMIT ]]
do
    BC="sqrt(0.9*$PIC_RESZ_WIDTH*$PIC_RESZ_WIDTH*$PIC_SIZE_LIMIT/$PIC_RESZ_SIZE)"
    PIC_RESZ_WIDTH=$(echo $BC | bc)
    convert $PIC_ORIG -resize ${PIC_RESZ_WIDTH}x${PIC_ORIG_HEIGHT} $PIC_TEMP
    PIC_RESZ_SIZE=$(get_pic_size $PIC_TEMP)
    PIC_RESZ_WIDTH=$(get_pic_width $PIC_TEMP)
#    echo size $PIC_RESZ_SIZE width $PIC_RESZ_WIDTH
done

mv $PIC_TEMP $PIC_RESZ
rm -rf ${TEMP_DIR}

route-ict-lx.sh

#!/usr/bin/env bash
sudo route add -net 172.17.103.0 netmask 255.255.255.0 gw 10.90.50.254 metric 300 dev enp3s0
sudo route add -net 10.25.1.0 netmask 255.255.255.0 gw 10.90.50.254 metric 300 dev enp3s0

spec2000_clean_without_run.sh

#!/usr/bin/env bash

# execute this script in root directory of spec2000
rm benchspec/*/*.bset*
rm benchspec/*/*/{Spec,data,docs,exe,result,src,version} -rf
rm benchspec/*/*/*/list
rm benchspec/*/*/*/*/*.{cmd,err,out,cmp}

spec2017_cmds.sh

#!/usr/bin/env bash
SPEC_DIR=/home/xieby1/Codes/MyRepos/spec2017/musl
RUN_IDX=run_base_refrate_nix.0000
EXT=nix
N=${N:=(($(nproc)))}

cmd=(
# intrate
"${SPEC_DIR}/benchspec/CPU/500.perlbench_r/run/${RUN_IDX}"
"../${RUN_IDX}/perlbench_r_base.${EXT} -I./lib checkspam.pl 2500 5 25 11 150 1 1 1 1 > checkspam.2500.5.25.11.150.1.1.1.1.out 2>> checkspam.2500.5.25.11.150.1.1.1.1.err"
"../${RUN_IDX}/perlbench_r_base.${EXT} -I./lib diffmail.pl 4 800 10 17 19 300 > diffmail.4.800.10.17.19.300.out 2>> diffmail.4.800.10.17.19.300.err"
"../${RUN_IDX}/perlbench_r_base.${EXT} -I./lib splitmail.pl 6400 12 26 16 100 0 > splitmail.6400.12.26.16.100.0.out 2>> splitmail.6400.12.26.16.100.0.err"

"${SPEC_DIR}/benchspec/CPU/502.gcc_r/run/${RUN_IDX}"
"../${RUN_IDX}/cpugcc_r_base.${EXT} gcc-pp.c -O3 -finline-limit=0 -fif-conversion -fif-conversion2 -o gcc-pp.opts-O3_-finline-limit_0_-fif-conversion_-fif-conversion2.s > gcc-pp.opts-O3_-finline-limit_0_-fif-conversion_-fif-conversion2.out 2>> gcc-pp.opts-O3_-finline-limit_0_-fif-conversion_-fif-conversion2.err"
"../${RUN_IDX}/cpugcc_r_base.${EXT} gcc-pp.c -O2 -finline-limit=36000 -fpic -o gcc-pp.opts-O2_-finline-limit_36000_-fpic.s > gcc-pp.opts-O2_-finline-limit_36000_-fpic.out 2>> gcc-pp.opts-O2_-finline-limit_36000_-fpic.err"
"../${RUN_IDX}/cpugcc_r_base.${EXT} gcc-smaller.c -O3 -fipa-pta -o gcc-smaller.opts-O3_-fipa-pta.s > gcc-smaller.opts-O3_-fipa-pta.out 2>> gcc-smaller.opts-O3_-fipa-pta.err"
"../${RUN_IDX}/cpugcc_r_base.${EXT} ref32.c -O5 -o ref32.opts-O5.s > ref32.opts-O5.out 2>> ref32.opts-O5.err"
"../${RUN_IDX}/cpugcc_r_base.${EXT} ref32.c -O3 -fselective-scheduling -fselective-scheduling2 -o ref32.opts-O3_-fselective-scheduling_-fselective-scheduling2.s > ref32.opts-O3_-fselective-scheduling_-fselective-scheduling2.out 2>> ref32.opts-O3_-fselective-scheduling_-fselective-scheduling2.err"

"${SPEC_DIR}/benchspec/CPU/505.mcf_r/run/${RUN_IDX}"
"../${RUN_IDX}/mcf_r_base.${EXT} inp.in  > inp.out 2>> inp.err"

"${SPEC_DIR}/benchspec/CPU/520.omnetpp_r/run/${RUN_IDX}"
"../${RUN_IDX}/omnetpp_r_base.${EXT} -c General -r 0 > omnetpp.General-0.out 2>> omnetpp.General-0.err"

"${SPEC_DIR}/benchspec/CPU/523.xalancbmk_r/run/${RUN_IDX}"
"../${RUN_IDX}/cpuxalan_r_base.${EXT} -v t5.xml xalanc.xsl > ref-t5.out 2>> ref-t5.err"

"${SPEC_DIR}/benchspec/CPU/525.x264_r/run/${RUN_IDX}"
"../${RUN_IDX}/x264_r_base.${EXT} --pass 1 --stats x264_stats.log --bitrate 1000 --frames 1000 -o BuckBunny_New.264 BuckBunny.yuv 1280x720 > run_000-1000_x264_r_base.sora-m64_x264_pass1.out 2>> run_000-1000_x264_r_base.sora-m64_x264_pass1.err"
"../${RUN_IDX}/x264_r_base.${EXT} --pass 2 --stats x264_stats.log --bitrate 1000 --dumpyuv 200 --frames 1000 -o BuckBunny_New.264 BuckBunny.yuv 1280x720 > run_000-1000_x264_r_base.sora-m64_x264_pass2.out 2>> run_000-1000_x264_r_base.sora-m64_x264_pass2.err"
"../${RUN_IDX}/x264_r_base.${EXT} --seek 500 --dumpyuv 200 --frames 1250 -o BuckBunny_New.264 BuckBunny.yuv 1280x720 > run_0500-1250_x264_r_base.sora-m64_x264.out 2>> run_0500-1250_x264_r_base.sora-m64_x264.err"

"${SPEC_DIR}/benchspec/CPU/531.deepsjeng_r/run/${RUN_IDX}"
"../${RUN_IDX}/deepsjeng_r_base.${EXT} ref.txt > ref.out 2>> ref.err"

"${SPEC_DIR}/benchspec/CPU/541.leela_r/run/${RUN_IDX}"
"../${RUN_IDX}/leela_r_base.${EXT} ref.sgf > ref.out 2>> ref.err"

"${SPEC_DIR}/benchspec/CPU/548.exchange2_r/run/${RUN_IDX}"
"../${RUN_IDX}/exchange2_r_base.${EXT} 6 > exchange2.txt 2>> exchange2.err"

"${SPEC_DIR}/benchspec/CPU/557.xz_r/run/${RUN_IDX}"
"../${RUN_IDX}/xz_r_base.${EXT} cld.tar.xz 160 19cf30ae51eddcbefda78dd06014b4b96281456e078ca7c13e1c0c9e6aaea8dff3efb4ad6b0456697718cede6bd5454852652806a657bb56e07d61128434b474 59796407 61004416 6 > cld.tar-160-6.out 2>> cld.tar-160-6.err"
"../${RUN_IDX}/xz_r_base.${EXT} cpu2006docs.tar.xz 250 055ce243071129412e9dd0b3b69a21654033a9b723d874b2015c774fac1553d9713be561ca86f74e4f16f22e664fc17a79f30caa5ad2c04fbc447549c2810fae 23047774 23513385 6e > cpu2006docs.tar-250-6e.out 2>> cpu2006docs.tar-250-6e.err"
"../${RUN_IDX}/xz_r_base.${EXT} input.combined.xz 250 a841f68f38572a49d86226b7ff5baeb31bd19dc637a922a972b2e6d1257a890f6a544ecab967c313e370478c74f760eb229d4eef8a8d2836d233d3e9dd1430bf 40401484 41217675 7 > input.combined-250-7.out 2>> input.combined-250-7.err"

# fprate
"${SPEC_DIR}/benchspec/CPU/503.bwaves_r/run/${RUN_IDX}"
"../${RUN_IDX}/bwaves_r_base.${EXT} bwaves_1 < bwaves_1.in > bwaves_1.out 2>> bwaves_1.err"
"../${RUN_IDX}/bwaves_r_base.${EXT} bwaves_2 < bwaves_2.in > bwaves_2.out 2>> bwaves_2.err"
"../${RUN_IDX}/bwaves_r_base.${EXT} bwaves_3 < bwaves_3.in > bwaves_3.out 2>> bwaves_3.err"
"../${RUN_IDX}/bwaves_r_base.${EXT} bwaves_4 < bwaves_4.in > bwaves_4.out 2>> bwaves_4.err"

"${SPEC_DIR}/benchspec/CPU/507.cactuBSSN_r/run/${RUN_IDX}"
"../${RUN_IDX}/cactusBSSN_r_base.${EXT} spec_ref.par   > spec_ref.out 2>> spec_ref.err"

"${SPEC_DIR}/benchspec/CPU/544.nab_r/run/${RUN_IDX}"
"../${RUN_IDX}/nab_r_base.${EXT} 1am0 1122214447 122 > 1am0.out 2>> 1am0.err"

"${SPEC_DIR}/benchspec/CPU/508.namd_r/run/${RUN_IDX}"
"../${RUN_IDX}/namd_r_base.${EXT} --input apoa1.input --output apoa1.ref.output --iterations 65 > namd.out 2>> namd.err"

"${SPEC_DIR}/benchspec/CPU/510.parest_r/run/${RUN_IDX}"
"../${RUN_IDX}/parest_r_base.${EXT}  ref.prm > ref.out 2>> ref.err"

"${SPEC_DIR}/benchspec/CPU/511.povray_r/run/${RUN_IDX}"
"../${RUN_IDX}/povray_r_base.${EXT}  SPEC-benchmark-ref.ini > SPEC-benchmark-ref.stdout 2>> SPEC-benchmark-ref.stderr"

"${SPEC_DIR}/benchspec/CPU/519.lbm_r/run/${RUN_IDX}"
"../${RUN_IDX}/lbm_r_base.${EXT} 3000 reference.dat 0 0 100_100_130_ldc.of > lbm.out 2>> lbm.err"

"${SPEC_DIR}/benchspec/CPU/521.wrf_r/run/${RUN_IDX}"
"../${RUN_IDX}/wrf_r_base.${EXT} > rsl.out.0000 2>> wrf.err"

"${SPEC_DIR}/benchspec/CPU/526.blender_r/run/${RUN_IDX}"
"../${RUN_IDX}/blender_r_base.${EXT} sh3_no_char.blend --render-output sh3_no_char_ --threads 1 -b -F RAWTGA -s 849 -e 849 -a > sh3_no_char.849.spec.out 2>> sh3_no_char.849.spec.err"

"${SPEC_DIR}/benchspec/CPU/527.cam4_r/run/${RUN_IDX}"
"../${RUN_IDX}/cam4_r_base.${EXT} > cam4_r_base.sora-m64.txt 2>> cam4_r_base.sora-m64.err"

"${SPEC_DIR}/benchspec/CPU/538.imagick_r/run/${RUN_IDX}"
"../${RUN_IDX}/imagick_r_base.${EXT} -limit disk 0 refrate_input.tga -edge 41 -resample 181% -emboss 31 -colorspace YUV -mean-shift 19x19+15% -resize 30% refrate_output.tga > refrate_convert.out 2>> refrate_convert.err"

"${SPEC_DIR}/benchspec/CPU/544.nab_r/run/${RUN_IDX}"
"../${RUN_IDX}/nab_r_base.${EXT} 1am0 1122214447 122 > 1am0.out 2>> 1am0.err"

"${SPEC_DIR}/benchspec/CPU/549.fotonik3d_r/run/${RUN_IDX}"
"../${RUN_IDX}/fotonik3d_r_base.${EXT} > fotonik3d_r.log 2>> fotonik3d_r.err"

"${SPEC_DIR}/benchspec/CPU/554.roms_r/run/${RUN_IDX}"
"../${RUN_IDX}/roms_r_base.${EXT} < ocean_benchmark2.in.x > ocean_benchmark2.log 2>> ocean_benchmark2.err"
)

for line in "${cmd[@]}"; do
    if [[ ${line:0:1} == "/" ]]; then
        dir="$line"
        idx=0
        name=${line#*Crate_Int/}
        name=${name%/run*}
        name=${name%/run*}
    else
        # interp="${QEMU} -d plugin -D ${PLUGIN_LOG_DIR}/${name}.${idx}.txt -plugin ${PLUGIN}"
        (
        echo "cd ${dir}"
        cd "${dir}" || exit
        echo "${interp} ${line}"
        eval "${interp} ${line}"
        ) &
        if [[ $(jobs -r -p | wc -l) -ge $N ]]; then
            wait -n
        fi
        (( idx++ ))
    fi
done
wait

tar-repo.sh

#!/usr/bin/env bash

usage()
{
    echo "tar git files"
    echo "Usage: ${0##*/} [-h] <DIR>"
    echo "  tar git repo <DIR>, exclude patterns from"
    echo "  * global gitignore"
    echo "  * repo's gitignore"
    echo "  * repo's git/info/exclude"
    echo "  output to <DIR>.tar.gz"
    exit 0
}

if [[ $# -lt 1 ]]
then
    usage
fi
if [[ $1 == "-h" ]]
then
    usage
fi

GI=~/Documents/Config/ignore/git
RI="$1/.gitignore"
RE="$1/.git/info/exclude"

tar \
    -X "${GI}" \
    -X "${RI}" \
    -X "${RE}" \
    -czf "${1%/}.tar.gz" \
    "$1"

ubuntu.sh

#/usr/bin/env bash

# parsing arguments
VERSION=latest
while [[ ${OPTIND} -le $# ]]; do
    getopts "lhe" opt
    case "${opt}" in
    l|h)
        echo "aarch64 riscv64 x86_64 16.04 18.04 20.04 22.04 22.10 23.04 latest -h -e"
        exit 0
    ;;
    e)
        ECHO=1
    ;;
    *)
        arg=${!OPTIND}
        case "$arg" in
        aarch64|riscv64|x86_64)
            ARCH=$arg
        ;;
        *)
            VERSION=$arg
        ;;
        esac
        shift
    ;;
    esac
done
NAME=ubuntu-${ARCH}

OPTS=(
    "-u root"
    # "--userns=keep-id" # [rootless container]
    "--env debian_chroot=$NAME"
    # "-h" "container-$NAME" # host name
    "-h localhost" # host name # avoid edit /etc/hosts
    "--name=$NAME-$VERSION" # container name

    "-v $HOME:$HOME"
    "-v $HOME:/root"
    "-v /nix:/nix" # make sure symbol links in home work
    "-v /run/binfmt:/run/binfmt"
    "-w $PWD" # working directory

    # this will cause guest /etc/hosts override by host's
    # use host ip instead, see host's ip address
    "--network=host" # use host network stack

    "-it"
    "$NAME:$VERSION"
    "/bin/bash"
)

# Pull image
podman images ${NAME}:${VERSION} | grep ${NAME} &> /dev/null
if [[ $? != 0 ]]; then
    if [[ $ARCH == "riscv64" ]]; then
        image_id=$(podman pull --arch ${ARCH} riscv64/ubuntu:$VERSION)
    else
        image_id=$(podman pull --arch ${ARCH} ubuntu:$VERSION)
    fi
    podman tag $image_id ${NAME}:${VERSION}
fi

# Run container
if [[ -z $ECHO ]]; then
    eval "podman run ${OPTS[@]}"
    podman commit $NAME-$VERSION $NAME:$VERSION
    podman rm $NAME-$VERSION
else
    echo "podman run ${OPTS[@]}"
    echo podman commit $NAME-$VERSION $NAME:$VERSION
    echo podman rm $NAME-$VERSION
fi

x-html-time_stamp.sh

#!/usr/bin/env bash
echo "<div style=\"text-align:right; font-size:3em;\">$(date +%Y.%m.%d)</div>"

x-sixu-all.sh

#!/usr/bin/env bash
cat <<EOL
#!/usr/bin/env -S dot -Tsvg -O

digraph {
// attributes
/// graph
rankdir=BT;
/// subgraph
newrank=true;
style=filled;
//// color name: https://graphviz.org/doc/info/colors.html
color=whitesmoke;
/// node
node[
shape=box,
style="filled, solid",
color=black,
fillcolor=white,
];
/// edge
edge[
minlen=1,
//weight=1,
// If false, the edge is not used in ranking the nodes.
//constraint=true,
];



}
EOL

x-sixu-today.sh

#!/usr/bin/env bash
YESTERDAY=$(LC_TIME=en_DK date --date="yesterday" +%y%b%d)
TODAY=$(LC_TIME=en_DK date +%y%b%d)
cat <<EOL
"${YESTERDAY}+" -> "${TODAY}-" -> "${TODAY}+";
subgraph cluster_${TODAY}
{
    x${TODAY}_
}
{rank=same; "${TODAY}-";
    x${TODAY}_
}
{rank=same; "${TODAY}+";
}
EOL

x.sh

#!/usr/bin/env bash
xdotool type --delay 30 "$(cd ~/Gist/script/bash/ && ls --color=never x-* | rofi -dmenu | xargs bash -c)"