#!/bin/sh -e
#
# Copyright (c) 2009-2021 <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

ARCH=$(uname -m)
DIR=$PWD

. "${DIR}/system.sh"

#For:
#toolchain
. "${DIR}/version.sh"

if [  -f "${DIR}/.yakbuild" ] ; then
	. "${DIR}/recipe.sh"
fi

if [ -d $HOME/dl/gcc/ ] ; then
	gcc_dir="$HOME/dl/gcc"
else
	gcc_dir="${DIR}/dl"
fi

dl_gcc_generic () {
	WGET="wget -c --directory-prefix=${gcc_dir}/"
	if [ "x${extracted_dir}" = "x" ] ; then
		filename_prefix=${gcc_filename_prefix}
	else
		filename_prefix=${extracted_dir}
	fi

	if [ ! -f "${gcc_dir}/${filename_prefix}/${datestamp}" ] ; then
		echo "Installing Toolchain: ${toolchain}"
		echo "-----------------------------"
		${WGET} "${gcc_html_path}${gcc_filename_prefix}.tar.xz"
		if [ -d "${gcc_dir}/${filename_prefix}" ] ; then
			rm -rf "${gcc_dir}/${filename_prefix}" || true
		fi
		tar -xf "${gcc_dir}/${gcc_filename_prefix}.tar.xz" -C "${gcc_dir}/"
		if [ -f "${gcc_dir}/${filename_prefix}/${binary}gcc" ] ; then
			touch "${gcc_dir}/${filename_prefix}/${datestamp}"
		fi
	else
		echo "Using Existing Toolchain: ${toolchain}"
	fi

	if [ "x${ARCH}" = "xarmv7l" ] ; then
		#using native gcc
		CC=
	else
		CC="${gcc_dir}/${filename_prefix}/${binary}"
	fi
}

gcc_toolchain () {
	unset extracted_dir
	case "${toolchain}" in
	gcc_linaro_eabi_4_9)
		#
		#https://releases.linaro.org/components/toolchain/binaries/4.9-2017.01/arm-eabi/gcc-linaro-4.9.4-2017.01-x86_64_arm-eabi.tar.xz
		#

		gcc_html_path="https://releases.linaro.org/components/toolchain/binaries/4.9-2017.01/arm-eabi/"
		gcc_filename_prefix="gcc-linaro-4.9.4-2017.01-x86_64_arm-eabi"
		gcc_banner="arm-eabi-gcc (Linaro GCC 4.9-2017.01) 4.9.4"
		gcc_copyright="2015"
		datestamp="2017.01-gcc-arm-none-eabi"

		binary="bin/arm-eabi-"
		;;
	gcc_linaro_eabi_5)
		#
		#https://releases.linaro.org/components/toolchain/binaries/5.4-2017.05/arm-eabi/gcc-linaro-5.4.1-2017.05-x86_64_arm-eabi.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/5.5-2017.10/arm-eabi/gcc-linaro-5.5.0-2017.10-x86_64_arm-eabi.tar.xz
		#

		gcc_html_path="https://releases.linaro.org/components/toolchain/binaries/5.5-2017.10/arm-eabi/"
		gcc_filename_prefix="gcc-linaro-5.5.0-2017.10-x86_64_arm-eabi"
		gcc_banner="arm-eabi-gcc (Linaro GCC 5.5-2017.10) 5.5.0"
		gcc_copyright="2015"
		datestamp="2017.10-gcc-arm-none-eabi"

		binary="bin/arm-eabi-"
		;;
	gcc_linaro_eabi_6)
		#
		#https://releases.linaro.org/components/toolchain/binaries/6.3-2017.05/arm-eabi/gcc-linaro-6.3.1-2017.05-x86_64_arm-eabi.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/6.4-2017.08/arm-eabi/gcc-linaro-6.4.1-2017.08-x86_64_arm-eabi.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/6.4-2017.11/arm-eabi/gcc-linaro-6.4.1-2017.11-x86_64_arm-eabi.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/6.4-2018.05/arm-eabi/gcc-linaro-6.4.1-2018.05-x86_64_arm-eabi.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/6.5-2018.12/arm-eabi/gcc-linaro-6.5.0-2018.12-x86_64_arm-eabi.tar.xz
		#

		gcc_html_path="https://releases.linaro.org/components/toolchain/binaries/6.5-2018.12/arm-eabi/"
		gcc_filename_prefix="gcc-linaro-6.5.0-2018.12-x86_64_arm-eabi"
		gcc_banner="arm-eabi-gcc (Linaro GCC 6.5-2018.12) 6.5.0"
		gcc_copyright="2017"
		datestamp="2018.12-gcc-arm-none-eabi"

		binary="bin/arm-eabi-"
		;;
	gcc_linaro_eabi_7)
		#
		#https://releases.linaro.org/components/toolchain/binaries/7.1-2017.05/arm-eabi/gcc-linaro-7.1.1-2017.05-x86_64_arm-eabi.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/7.1-2017.08/arm-eabi/gcc-linaro-7.1.1-2017.08-x86_64_arm-eabi.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/7.2-2017.11/arm-eabi/gcc-linaro-7.2.1-2017.11-x86_64_arm-eabi.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/7.3-2018.05/arm-eabi/gcc-linaro-7.3.1-2018.05-x86_64_arm-eabi.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/7.4-2019.02/arm-eabi/gcc-linaro-7.4.1-2019.02-x86_64_arm-eabi.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/7.5-2019.12/arm-eabi/gcc-linaro-7.5.0-2019.12-x86_64_arm-eabi.tar.xz
		#

		gcc_html_path="https://releases.linaro.org/components/toolchain/binaries/7.5-2019.12/arm-eabi/"
		gcc_filename_prefix="gcc-linaro-7.5.0-2019.12-x86_64_arm-eabi"
		gcc_banner="arm-eabi-gcc (Linaro GCC 7.5-2019.12) 7.5.0"
		gcc_copyright="2017"
		datestamp="2019.12-gcc-arm-none-eabi"

		binary="bin/arm-eabi-"
		;;
	gcc_arm_eabi_8)
		#
		#https://developer.arm.com/-/media/Files/downloads/gnu-a/8.3-2019.03/binrel/gcc-arm-8.3-2019.03-x86_64-arm-eabi.tar.xz
		#

		gcc_html_path="https://developer.arm.com/-/media/Files/downloads/gnu-a/8.3-2019.03/binrel/"
		gcc_filename_prefix="gcc-arm-8.3-2019.03-x86_64-arm-eabi"
		gcc_banner="arm-eabi-gcc (GNU Toolchain for the A-profile Architecture 8.3-2019.03 (arm-rel-8.36)) 8.3.0"
		gcc_copyright="2018"
		datestamp="2019.03-gcc-arm-none-eabi"

		binary="bin/arm-eabi-"
		;;
	gcc_arm_eabi_9)
		#
		#https://developer.arm.com/-/media/Files/downloads/gnu-a/9.2-2019.12/binrel/gcc-arm-9.2-2019.12-x86_64-arm-none-eabi.tar.xz
		#

		gcc_html_path="https://developer.arm.com/-/media/Files/downloads/gnu-a/9.2-2019.12/binrel/"
		gcc_filename_prefix="gcc-arm-9.2-2019.12-x86_64-arm-none-eabi"
		gcc_banner="arm-none-eabi-gcc (GNU Toolchain for the A-profile Architecture 9.2-2019.12 (arm-9.10)) 9.2.1 20191025"
		gcc_copyright="2019"
		datestamp="2019.12-gcc-arm-none-eabi"

		binary="bin/arm-none-eabi-"
		;;
	gcc_arm_eabi_10)
		#
		#https://developer.arm.com/-/media/Files/downloads/gnu-a/10.2-2020.11/binrel/gcc-arm-10.2-2020.11-x86_64-arm-none-eabi.tar.xz
		#

		gcc_html_path="https://developer.arm.com/-/media/Files/downloads/gnu-a/10.2-2020.11/binrel/"
		gcc_filename_prefix="gcc-arm-10.2-2020.11-x86_64-arm-none-eabi"
		gcc_banner="arm-none-eabi-gcc (GNU Toolchain for the A-profile Architecture 10.2-2020.11 (arm-10.16)) 10.2.1 20201103"
		gcc_copyright="2020"
		datestamp="2020.11-gcc-arm-none-eabi"

		binary="bin/arm-none-eabi-"
		;;
	gcc_linaro_gnueabihf_4_9)
		#
		#https://releases.linaro.org/components/toolchain/binaries/4.9-2017.01/arm-linux-gnueabihf/gcc-linaro-4.9.4-2017.01-x86_64_arm-linux-gnueabihf.tar.xz
		#

		gcc_html_path="https://releases.linaro.org/components/toolchain/binaries/4.9-2017.01/arm-linux-gnueabihf/"
		gcc_filename_prefix="gcc-linaro-4.9.4-2017.01-x86_64_arm-linux-gnueabihf"
		gcc_banner="arm-linux-gnueabihf-gcc (Linaro GCC 4.9-2017.01) 4.9.4"
		gcc_copyright="2015"
		datestamp="2017.01-gcc-arm-linux-gnueabihf"

		binary="bin/arm-linux-gnueabihf-"
		;;
	gcc_linaro_gnueabihf_5)
		#
		#https://releases.linaro.org/components/toolchain/binaries/5.4-2017.05/arm-linux-gnueabihf/gcc-linaro-5.4.1-2017.05-x86_64_arm-linux-gnueabihf.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/5.5-2017.10/arm-linux-gnueabihf/gcc-linaro-5.5.0-2017.10-x86_64_arm-linux-gnueabihf.tar.xz
		#

		gcc_html_path="https://releases.linaro.org/components/toolchain/binaries/5.5-2017.10/arm-linux-gnueabihf/"
		gcc_filename_prefix="gcc-linaro-5.5.0-2017.10-x86_64_arm-linux-gnueabihf"
		gcc_banner="arm-linux-gnueabihf-gcc (Linaro GCC 5.5-2017.10) 5.5.0"
		gcc_copyright="2015"
		datestamp="2017.10-gcc-arm-linux-gnueabihf"

		binary="bin/arm-linux-gnueabihf-"
		;;
	gcc_linaro_gnueabihf_6)
		#
		#https://releases.linaro.org/components/toolchain/binaries/6.3-2017.05/arm-linux-gnueabihf/gcc-linaro-6.3.1-2017.05-x86_64_arm-linux-gnueabihf.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/6.4-2017.08/arm-linux-gnueabihf/gcc-linaro-6.4.1-2017.08-x86_64_arm-linux-gnueabihf.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/6.4-2017.11/arm-linux-gnueabihf/gcc-linaro-6.4.1-2017.11-x86_64_arm-linux-gnueabihf.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/6.4-2018.05/arm-linux-gnueabihf/gcc-linaro-6.4.1-2018.05-x86_64_arm-linux-gnueabihf.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/6.5-2018.12/arm-linux-gnueabihf/gcc-linaro-6.5.0-2018.12-x86_64_arm-linux-gnueabihf.tar.xz
		#

		gcc_html_path="https://releases.linaro.org/components/toolchain/binaries/6.5-2018.12/arm-linux-gnueabihf/"
		gcc_filename_prefix="gcc-linaro-6.5.0-2018.12-x86_64_arm-linux-gnueabihf"
		gcc_banner="arm-linux-gnueabihf-gcc (Linaro GCC 6.5-2018.12) 6.5.0"
		gcc_copyright="2017"
		datestamp="2018.12-gcc-arm-linux-gnueabihf"

		binary="bin/arm-linux-gnueabihf-"
		;;
	gcc_linaro_gnueabihf_7)
		#
		#https://releases.linaro.org/components/toolchain/binaries/7.1-2017.05/arm-linux-gnueabihf/gcc-linaro-7.1.1-2017.05-x86_64_arm-linux-gnueabihf.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/7.1-2017.08/arm-linux-gnueabihf/gcc-linaro-7.1.1-2017.08-x86_64_arm-linux-gnueabihf.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/7.2-2017.11/arm-linux-gnueabihf/gcc-linaro-7.2.1-2017.11-x86_64_arm-linux-gnueabihf.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/7.3-2018.05/arm-linux-gnueabihf/gcc-linaro-7.3.1-2018.05-x86_64_arm-linux-gnueabihf.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/7.4-2019.02/arm-linux-gnueabihf/gcc-linaro-7.4.1-2019.02-x86_64_arm-linux-gnueabihf.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/7.5-2019.12/arm-linux-gnueabihf/gcc-linaro-7.5.0-2019.12-x86_64_arm-linux-gnueabihf.tar.xz
		#

		gcc_html_path="https://releases.linaro.org/components/toolchain/binaries/7.5-2019.12/arm-linux-gnueabihf/"
		gcc_filename_prefix="gcc-linaro-7.5.0-2019.12-x86_64_arm-linux-gnueabihf"
		gcc_banner="arm-linux-gnueabihf-gcc (Linaro GCC 7.5-2019.12) 7.5.0"
		gcc_copyright="2017"
		datestamp="2019.12-gcc-arm-linux-gnueabihf"

		binary="bin/arm-linux-gnueabihf-"
		;;
	gcc_arm_gnueabihf_8)
		#
		#https://developer.arm.com/-/media/Files/downloads/gnu-a/8.2-2018.08/gcc-arm-8.2-2018.08-x86_64-arm-linux-gnueabihf.tar.xz
		#https://developer.arm.com/-/media/Files/downloads/gnu-a/8.2-2018.11/gcc-arm-8.2-2018.11-x86_64-arm-linux-gnueabihf.tar.xz
		#https://developer.arm.com/-/media/Files/downloads/gnu-a/8.2-2019.01/gcc-arm-8.2-2019.01-x86_64-arm-linux-gnueabihf.tar.xz
		#https://developer.arm.com/-/media/Files/downloads/gnu-a/8.3-2019.03/binrel/gcc-arm-8.3-2019.03-x86_64-arm-linux-gnueabihf.tar.xz
		#

		gcc_html_path="https://developer.arm.com/-/media/Files/downloads/gnu-a/8.3-2019.03/binrel/"
		gcc_filename_prefix="gcc-arm-8.3-2019.03-x86_64-arm-linux-gnueabihf"
		gcc_banner="arm-linux-gnueabihf-gcc (GNU Toolchain for the A-profile Architecture 8.3-2019.03 (arm-rel-8.36)) 8.3.0"
		gcc_copyright="2018"
		datestamp="2019.03-gcc-arm-linux-gnueabihf"

		binary="bin/arm-linux-gnueabihf-"
		;;
	gcc_arm_gnueabihf_9)
		#
		#https://developer.arm.com/-/media/Files/downloads/gnu-a/9.2-2019.12/binrel/gcc-arm-9.2-2019.12-x86_64-arm-none-linux-gnueabihf.tar.xz
		#

		gcc_html_path="https://developer.arm.com/-/media/Files/downloads/gnu-a/9.2-2019.12/binrel/"
		gcc_filename_prefix="gcc-arm-9.2-2019.12-x86_64-arm-none-linux-gnueabihf"
		gcc_banner="arm-none-linux-gnueabihf-gcc (GNU Toolchain for the A-profile Architecture 9.2-2019.12 (arm-9.10)) 9.2.1 20191025"
		gcc_copyright="2019"
		datestamp="2019.12-gcc-arm-linux-gnueabihf"

		binary="bin/arm-none-linux-gnueabihf-"
		;;
	gcc_arm_gnueabihf_10)
		#
		#https://developer.arm.com/-/media/Files/downloads/gnu-a/10.2-2020.11/binrel/gcc-arm-10.2-2020.11-x86_64-arm-none-linux-gnueabihf.tar.xz
		#

		gcc_html_path="https://developer.arm.com/-/media/Files/downloads/gnu-a/10.2-2020.11/binrel/"
		gcc_filename_prefix="gcc-arm-10.2-2020.11-x86_64-arm-none-linux-gnueabihf"
		gcc_banner="arm-none-linux-gnueabihf-gcc (GNU Toolchain for the A-profile Architecture 10.2-2020.11 (arm-10.16)) 10.2.1 20201103"
		gcc_copyright="2020"
		datestamp="2020.11-gcc-arm-linux-gnueabihf"

		binary="bin/arm-none-linux-gnueabihf-"
		;;
	gcc_linaro_aarch64_gnu_5)
		#
		#https://releases.linaro.org/components/toolchain/binaries/5.4-2017.05/aarch64-linux-gnu/gcc-linaro-5.4.1-2017.05-x86_64_aarch64-linux-gnu.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/5.5-2017.10/aarch64-linux-gnu/gcc-linaro-5.5.0-2017.10-x86_64_aarch64-linux-gnu.tar.xz
		#

		gcc_html_path="https://releases.linaro.org/components/toolchain/binaries/5.5-2017.10/aarch64-linux-gnu/"
		gcc_filename_prefix="gcc-linaro-5.5.0-2017.10-x86_64_aarch64-linux-gnu"
		gcc_banner="aarch64-linux-gnu-gcc (Linaro GCC 5.5-2017.10) 5.5.0"
		gcc_copyright="2015"
		datestamp="2017.10-gcc-aarch64-linux-gnu"

		binary="bin/aarch64-linux-gnu-"
		;;
	gcc_linaro_aarch64_gnu_6)
		#
		#https://releases.linaro.org/components/toolchain/binaries/6.3-2017.05/aarch64-linux-gnu/gcc-linaro-6.3.1-2017.05-x86_64_aarch64-linux-gnu.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/6.4-2017.08/aarch64-linux-gnu/gcc-linaro-6.4.1-2017.08-x86_64_aarch64-linux-gnu.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/6.4-2017.11/aarch64-linux-gnu/gcc-linaro-6.4.1-2017.11-x86_64_aarch64-linux-gnu.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/6.4-2018.05/aarch64-linux-gnu/gcc-linaro-6.4.1-2018.05-x86_64_aarch64-linux-gnu.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/6.5-2018.12/aarch64-linux-gnu/gcc-linaro-6.5.0-2018.12-x86_64_aarch64-linux-gnu.tar.xz
		#

		gcc_html_path="https://releases.linaro.org/components/toolchain/binaries/6.5-2018.12/aarch64-linux-gnu/"
		gcc_filename_prefix="gcc-linaro-6.5.0-2018.12-x86_64_aarch64-linux-gnu"
		gcc_banner="aarch64-linux-gnu-gcc (Linaro GCC 6.5-2018.12) 6.5.0"
		gcc_copyright="2017"
		datestamp="2018.12-gcc-aarch64-linux-gnu"

		binary="bin/aarch64-linux-gnu-"
		;;
	gcc_linaro_aarch64_gnu_7)
		#
		#https://releases.linaro.org/components/toolchain/binaries/7.1-2017.05/aarch64-linux-gnu/gcc-linaro-7.1.1-2017.05-x86_64_aarch64-linux-gnu.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/7.1-2017.08/aarch64-linux-gnu/gcc-linaro-7.1.1-2017.08-x86_64_aarch64-linux-gnu.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/7.2-2017.11/aarch64-linux-gnu/gcc-linaro-7.2.1-2017.11-x86_64_aarch64-linux-gnu.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/7.3-2018.05/aarch64-linux-gnu/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/7.4-2019.02/aarch64-linux-gnu/gcc-linaro-7.4.1-2019.02-x86_64_aarch64-linux-gnu.tar.xz
		#https://releases.linaro.org/components/toolchain/binaries/7.5-2019.12/aarch64-linux-gnu/gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnu.tar.xz
		#

		gcc_html_path="https://releases.linaro.org/components/toolchain/binaries/7.5-2019.12/aarch64-linux-gnu/"
		gcc_filename_prefix="gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnu"
		gcc_banner="aarch64-linux-gnu-gcc (Linaro GCC 7.5-2019.12) 7.5.0"
		gcc_copyright="2017"
		datestamp="2019.12-gcc-aarch64-linux-gnu"

		binary="bin/aarch64-linux-gnu-"
		;;
	gcc_arm_aarch64_gnu_8)
		#
		#https://developer.arm.com/-/media/Files/downloads/gnu-a/8.2-2018.08/gcc-arm-8.2-2018.08-x86_64-aarch64-linux-gnu.tar.xz
		#https://developer.arm.com/-/media/Files/downloads/gnu-a/8.2-2018.11/gcc-arm-8.2-2018.11-x86_64-aarch64-linux-gnu.tar.xz
		#https://developer.arm.com/-/media/Files/downloads/gnu-a/8.2-2019.01/gcc-arm-8.2-2019.01-x86_64-aarch64-linux-gnu.tar.xz
		#https://developer.arm.com/-/media/Files/downloads/gnu-a/8.3-2019.03/binrel/gcc-arm-8.3-2019.03-x86_64-aarch64-linux-gnu.tar.xz
		#

		gcc_html_path="https://developer.arm.com/-/media/Files/downloads/gnu-a/8.3-2019.03/binrel/"
		gcc_filename_prefix="gcc-arm-8.3-2019.03-x86_64-aarch64-linux-gnu"
		gcc_banner="aarch64-linux-gnu-gcc (GNU Toolchain for the A-profile Architecture 8.3-2019.03 (arm-rel-8.36)) 8.3.0"
		gcc_copyright="2018"
		datestamp="2019.03-gcc-aarch64-linux-gnu"

		binary="bin/aarch64-linux-gnu-"
		;;
	gcc_arm_aarch64_gnu_9)
		#
		#https://developer.arm.com/-/media/Files/downloads/gnu-a/9.2-2019.12/binrel/gcc-arm-9.2-2019.12-x86_64-aarch64-none-linux-gnu.tar.xz
		#

		gcc_html_path="https://developer.arm.com/-/media/Files/downloads/gnu-a/9.2-2019.12/binrel/"
		gcc_filename_prefix="gcc-arm-9.2-2019.12-x86_64-aarch64-none-linux-gnu"
		gcc_banner="aarch64-none-linux-gnu-gcc (GNU Toolchain for the A-profile Architecture 9.2-2019.12 (arm-9.10)) 9.2.1 20191025"
		gcc_copyright="2019"
		datestamp="2019.12-gcc-aarch64-linux-gnu"

		binary="bin/aarch64-none-linux-gnu-"
		;;
	gcc_arm_aarch64_gnu_10)
		#
		#https://developer.arm.com/-/media/Files/downloads/gnu-a/10.2-2020.11/binrel/gcc-arm-10.2-2020.11-x86_64-aarch64-none-linux-gnu.tar.xz
		#

		gcc_html_path="https://developer.arm.com/-/media/Files/downloads/gnu-a/10.2-2020.11/binrel/"
		gcc_filename_prefix="gcc-arm-10.2-2020.11-x86_64-aarch64-none-linux-gnu"
		gcc_banner="aarch64-none-linux-gnu-gcc (GNU Toolchain for the A-profile Architecture 10.2-2020.11 (arm-10.16)) 10.2.1 20201103"
		gcc_copyright="2020"
		datestamp="2020.11-gcc-aarch64-linux-gnu"

		binary="bin/aarch64-none-linux-gnu-"
		;;
	gcc_8_riscv64)
		#
		#https://mirrors.edge.kernel.org/pub/tools/crosstool/files/bin/x86_64/8.4.0/x86_64-gcc-8.4.0-nolibc-riscv64-linux.tar.xz
		#

		gcc_html_path="https://mirrors.edge.kernel.org/pub/tools/crosstool/files/bin/x86_64/8.4.0/"
		gcc_filename_prefix="x86_64-gcc-8.4.0-nolibc-riscv64-linux"
		extracted_dir="gcc-8.4.0-nolibc/riscv64-linux"
		gcc_banner="riscv64-linux-gcc (GCC) 8.4.0"
		gcc_copyright="2018"
		datestamp="2018.8.4.0-riscv64-linux-gcc"

		binary="bin/riscv64-linux-"
		;;
	gcc_9_riscv64)
		#
		#https://mirrors.edge.kernel.org/pub/tools/crosstool/files/bin/x86_64/9.3.0/x86_64-gcc-9.3.0-nolibc-riscv64-linux.tar.xz
		#

		gcc_html_path="https://mirrors.edge.kernel.org/pub/tools/crosstool/files/bin/x86_64/9.3.0/"
		gcc_filename_prefix="x86_64-gcc-9.3.0-nolibc-riscv64-linux"
		extracted_dir="gcc-9.3.0-nolibc/riscv64-linux"
		gcc_banner="riscv64-linux-gcc (GCC) 9.3.0"
		gcc_copyright="2019"
		datestamp="2019.9.3.0-riscv64-linux-gcc"

		binary="bin/riscv64-linux-"
		;;
	gcc_10_riscv64)
		#
		#https://mirrors.edge.kernel.org/pub/tools/crosstool/files/bin/x86_64/10.1.0/x86_64-gcc-10.1.0-nolibc-riscv64-linux.tar.xz
		#https://mirrors.edge.kernel.org/pub/tools/crosstool/files/bin/x86_64/10.3.0/x86_64-gcc-10.3.0-nolibc-riscv64-linux.tar.xz
		#

		gcc_html_path="https://mirrors.edge.kernel.org/pub/tools/crosstool/files/bin/x86_64/10.3.0/"
		gcc_filename_prefix="x86_64-gcc-10.3.0-nolibc-riscv64-linux"
		extracted_dir="gcc-10.3.0-nolibc/riscv64-linux"
		gcc_banner="riscv64-linux-gcc (GCC) 10.3.0"
		gcc_copyright="2020"
		datestamp="2020.10.3.0-riscv64-linux-gcc"

		binary="bin/riscv64-linux-"
		;;
	*)
		echo "bug: maintainer forgot to set:"
		echo "toolchain=\"xzy\" in version.sh"
		exit 1
		;;
	esac

	dl_gcc_generic
}

if [ "x${CC}" = "x" ] && [ "x${ARCH}" != "xarmv7l" ] ; then
	gcc_toolchain
fi

unset check
if [ "x${KERNEL_ARCH}" = "xarm" ] ; then
	check="arm"
fi
if [ "x${KERNEL_ARCH}" = "xarm64" ] ; then
	check="aarch64"
fi
if [ "x${KERNEL_ARCH}" = "xriscv" ] ; then
	check="riscv"
fi

if [ "x${check}" = "x" ] ; then
	echo "ERROR: fix: scripts/gcc.sh..."
	exit 2
else
	GCC_TEST=$(LC_ALL=C "${CC}gcc" -v 2>&1 | grep "Target:" | grep ${check} || true)
fi

if [ "x${GCC_TEST}" = "x" ] ; then
	echo "-----------------------------"
	echo "scripts/gcc: Error: The GCC Cross Compiler you setup in system.sh (CC variable) is invalid."
	echo "-----------------------------"
	gcc_toolchain
fi

echo "-----------------------------"
echo "scripts/gcc: Using: $(LC_ALL=C "${CC}"gcc --version)"
echo "-----------------------------"
echo "CC=${CC}" > "${DIR}/.CC"


<filename>Swan-crond.sh<gh_stars>1-10
#!/usr/bin/env bash
#=================================================================#
#   System Required:  CentOS, Debian, Ubuntu                      #
#   Description: Check Shadowsocks Server is running or not       #
#   Author: Teddysun <<EMAIL>>                             #
#   Visit: https://teddysun.com/548.html                          #
#=================================================================#

name=(Shadowsocks Shadowsocks-Python ShadowsocksR Shadowsocks-Go Shadowsocks-libev)
path=/var/log
[[ ! -d ${path} ]] && mkdir -p ${path}
log=${path}/shadowsocks-crond.log

shadowsocks_init[0]=/etc/init.d/shadowsocks
shadowsocks_init[1]=/etc/init.d/shadowsocks-python
shadowsocks_init[2]=/etc/init.d/shadowsocks-r
shadowsocks_init[3]=/etc/init.d/shadowsocks-go
shadowsocks_init[4]=/etc/init.d/shadowsocks-libev

i=0
for init in "${shadowsocks_init[@]}"; do
    pid=""
    if [ -f ${init} ]; then
        ss_status=$(${init} status)
        if [ $? -eq 0 ]; then
            pid=$(echo "$ss_status" | sed -e 's/[^0-9]*//g')
        fi

        if [ -z "${pid}" ]; then
            echo "$(date +'%Y-%m-%d %H:%M:%S') ${name[$i]} is not running" >> ${log}
            echo "$(date +'%Y-%m-%d %H:%M:%S') Starting ${name[$i]}" >> ${log}
            ${init} start &>/dev/null
            if [ $? -eq 0 ]; then
                echo "$(date +'%Y-%m-%d %H:%M:%S') ${name[$i]} start success" >> ${log}
            else
                echo "$(date +'%Y-%m-%d %H:%M:%S') ${name[$i]} start failed" >> ${log}
            fi
        else
            echo "$(date +'%Y-%m-%d %H:%M:%S') ${name[$i]} is running with pid $pid" >> ${log}
        fi

    fi
    ((i++))
done


#!/bin/bash
#
# Copyright 2017-2021 O2 Czech Republic, a.s.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

function deploy() {

  VERSION=$1
  TRY=0

  echo "Going to deploy version ${VERSION}"

  mvn versions:set -DnewVersion=${VERSION}

  while [ $TRY -lt 3 ]; do
    CMD="mvn -s /tmp/settings.xml deploy -DskipTests -Prelease-snapshot -Pallow-snapshots"
    if [ ! -z "${RESUME}" ]; then
      CMD="${CMD} $(echo $RESUME | sed "s/.\+\(-rf .\+\)/\1/")"
    fi
    echo "Starting to deploy step $((TRY + 1)) with command ${CMD}"
    touch output${TRY}.log
    tail -f output${TRY}.log &
    RESUME=$(${CMD} | tee output${TRY}.log | grep -A1 "After correcting the problems, you can resume the build with the command" | tail -1)
    if [ -z "${RESUME}" ]; then
      break
    fi
    TRY="$((TRY+1))"
  done
  if [ $TRY -lt 3 ]; then
    echo "Success deploying snapshot"
  else
    echo "Failed to deploy snapshot"
    return 1
  fi

}

function verify_jdk() {
  JDK=$1

  if ! mvn -version | grep "Java version: ${JDK}"; then
    echo "Failed to verify required JDK version ${JDK}"
    return 1
  fi
}

set -eu

VERSION=$(mvn org.apache.maven.plugins:maven-help-plugin:2.1.1:evaluate -Dexpression=project.version | grep SNAPSHOT | grep -v INFO)
JDK11_VERSION=$(echo $VERSION | sed "s/\(.\+\)-SNAPSHOT/\1-jdk11-SNAPSHOT/")

if [ -z "${VERSION}" ]; then
  echo "Failed to retrieve version from repository"
  exit 1
fi

TARGET_JDK=$([ $# -gt 0 ] && echo $1 || echo "")

if [ -z "${TARGET_JDK}" ] || [ "${TARGET_JDK}" != "8" -a "${TARGET_JDK}" != "11" ]; then
  echo "Missing target JDK argument, must be either 8 or 11"
  exit 1
fi

echo ${MAVEN_SETTINGS} > /tmp/settings.xml
echo ${GOOGLE_CREDENTIALS} > /tmp/google-credentials.json

export GOOGLE_APPLICATION_CREDENTIALS=/tmp/google-credentials.json

RESUME=""
if echo ${VERSION} | grep SNAPSHOT >/dev/null && echo ${GITHUB_REPOSITORY} | grep O2-Czech-Republic >/dev/null; then

  case "${TARGET_JDK}" in

    "8")
      verify_jdk "1\.8"
      deploy ${VERSION}
      ;;

    "11")
      verify_jdk "11"
      deploy ${JDK11_VERSION}
      ;;

  esac

fi


<reponame>JavierCabezas/pokemon-day-plays-pokemon
#!/bin/bash
export DISPLAY=":0"
XAUTHORITY=./.Xauthority
xdotool key w
xdotool key w


<gh_stars>0
#!/bin/bash
# Runs appcfg.py update after prompting for the application name and version,
# reading defaults from app.yaml and the ouput of git describe --tags.
#
# Assumes this is run from the project root directory.
#
# Any arguments are passed to appcfg.py e.g.
# ./deploy.sh --oauth2

set -eu

pushd "$(dirname "$0")"

APPLICATION=$(grep -E '^application:' app.yaml | sed 's/application: *//')
VERSION=$(git describe --tags --long --dirty | tr '[:upper:].' '[:lower:]-')

read -r -p "Application (default '$APPLICATION'): " user_application
read -r -p "Version (default '$VERSION'): " user_version

if [[ ! "$user_application" ]]; then
    user_application="$APPLICATION"
fi

if [[ ! "$user_version" ]]; then
    user_version="$VERSION"
fi

if [[ ! ("$user_version" && "$user_application") ]] ; then
    echo "Please specify an application name and version for deployment."
    exit 1
fi

echo "Deploying '$user_application' version '$user_version'."

npm run build
npm run uglify
appcfg.py --application "$user_application" --version "$user_version" $@ update .

popd


#!/bin/bash

#SBATCH --job-name=thg2 # create a short name for your job
#SBATCH --account=pi-dachxiu
#SBATCH --partition=caslake
#SBATCH --ntasks=120       # 1 CPU core to drive GPU
#SBATCH --cpus-per-task=4        # cpu-cores per task (>1 if multi-threaded tasks)
#SBATCH --mem-per-cpu=10G  # NOTE DO NOT USE THE --mem= OPTION
#SBATCH --time=30:00:00          # total run time limit (HH:MM:SS)

echo "Job ID: $SLURM_JOB_ID"
echo "Job User: $SLURM_JOB_USER"
echo "Num Cores: $SLURM_JOB_CPUS_PER_NODE"

module load parallel

srun="srun --exclusive -N1 -n1"
parallel="parallel --delay 0.2 -j $SLURM_NTASKS --joblog thg_run.log --resume"

# $parallel "$srun ./single_run.sh {1} {2}" :::  ai_hot_1_1_20_3.yaml ai_hot_1_4_20_3.yaml ai_hot_3_1_20_3.yaml ai_hot_3_4_20_3.yaml ai_sin_1_1_20_3.yaml ai_sin_1_4_20_3.yaml ai_sin_3_1_20_3.yaml ai_sin_3_4_20_3.yaml ::: {1..15}
$parallel "$srun ./single_run.sh {1} {2}" :::  ai_hot_3_1_20_3.yaml ai_hot_3_4_20_3.yaml ai_sin_3_1_20_3.yaml ai_sin_3_4_20_3.yaml ::: {1..15}


#!/bin/bash
set -euo pipefail

J2OBJC_VERSION="2.5"
# SHA1_CHECKSUM=e9d2ae81dfbed6610af3ae744dd0636140e3c928

if [[ -d dist ]]; then
  exit
fi

echo "Fetching J2ObjC v${J2OBJC_VERSION} from https://github.com/google/j2objc/releases/download/${J2OBJC_VERSION}/j2objc-${J2OBJC_VERSION}.zip"
curl -OL https://github.com/google/j2objc/releases/download/${J2OBJC_VERSION}/j2objc-${J2OBJC_VERSION}.zip
# echo "${SHA1_CHECKSUM}  j2objc-${J2OBJC_VERSION}.zip" | shasum -c
unzip -o -q j2objc-${J2OBJC_VERSION}.zip

J2OBJC_PATH=j2objc-${J2OBJC_VERSION}

mkdir dist
mv  $J2OBJC_PATH/include \
    $J2OBJC_PATH/lib \
    $J2OBJC_PATH/j2objc \
    $J2OBJC_PATH/j2objcc \
    dist
rm -rf j2objc-${J2OBJC_VERSION} j2objc-${J2OBJC_VERSION}.zip

touch dist/VERSION
echo $J2OBJC_VERSION > dist/VERSION


# Creates Password less Login for Max OS X on most linux systems
# Written 2013/05/01   By: <NAME>
# sh $(nvram get usb_tomato)/Scripts/BashDowner.sh
# ============================================================================

# COLOR( "Your Text" ) --------------------------------------------------
# Color Function (No Logger) - 2013/04/20 - v5.1 MacOSX
NTFY() { echo -e "$@"; synodsmnotify @administrators "Terminal Message" "$(echo $@)"; }
BLK() { echo -e "\033[30;40;1m$@\033[0m"; }
RED() { echo -e "\033[31;40;1m$@\033[0m"; }
GRN() { echo -e "\033[32;40;1m$@\033[0m"; }
YEL() { echo -e "\033[33;40;1m$@\033[0m"; }
BLU() { echo -e "\033[34;40;1m$@\033[0m"; }
MAG() { echo -e "\033[35;40;1m$@\033[0m"; }
CYN() { echo -e "\033[36;40;1m$@\033[0m"; }
WHT() { echo -e "\033[37;40;1m$@\033[0m"; }
WRN() { echo -e "\033[31;40;1m/\033[33;40;1m!\033[31;40;1m\\ \033[33;40;1mWARNING:\033[37;40;1m $@ \033[31;40;1m/\033[33;40;1m!\033[31;40;1m\\ \033[0m $(tput bel)"; } # "$(tput bel)" = BEL = Bell Sound
PASS() { echo -e "\033[30;40;1m$@ \t \033[37;40;1m[\033[32;40;1mPass\033[37;40;1m]\033[0m"; }
FAIL() { echo -e "\033[37;40;1m$@ \t \033[37;40;1m[\033[31;40;1mFail\033[37;40;1m]\033[0m $(tput bel)"; }
QSTYN()
{
	read -t 30 -n 1 -p "$(echo -e "\033[35;40;1m(\033[34;40;1m?\033[35;40;1m) \033[34;40;1mQUESTION:\033[37;40;1m $@? \033[37;40;1m(\033[32;40;1my\033[37;40;1m/\033[31;40;1mn\033[37;40;1m) \033[32;40;1m:\033[0m$(tput bel) ")"
	echo " " # Creates Newline
}
QST()
{
	read -p "$(echo -e "\033[35;40;1m(\033[34;40;1m?\033[35;40;1m) \033[34;40;1mQUESTION:\033[37;40;1m $@\033[32;40;1m:\033[0m$(tput bel) ")"
	echo " " # Creates Newline
}
BRK()
{
	if [ $1 == 1 ]; then
		YEL "***<=============>*****<=============>***"
	elif [ $1 == 2 ]; then
		BLU "========================================="
	elif [ $1 == 3 ]; then
		BLK "~---------------------------------------~"
	elif [ $1 == 4 ]; then
		BLU "~ - - - - - - - - - - - - - - - - - - - ~"
	elif [ $1 == 5 ]; then
		BLK "~   -   -   -   -   -   -   -   -   -   ~"
	elif [ $1 == 6 ]; then
		BLK "........................................."
	elif [ $1 == 7 ]; then
		BLK "_________________________________________\n"
	else
		WRN "Break Formatting ERROR [ $2 ]"
	fi
}

# == [ Build Keys ] ================================================
#read -t 30 -n 1 -p "Build New Key on Client (y/n)? []"
while true; do
    QSTYN "Build New Key on Client [n]"
    case $REPLY in
        [Yy]* ) YEL "Building New Key"; echo ssh-keygen -t rsa; break;; # On client (Mac OS X): On you host computer (not the diskstation) open a terminal and run the following command:
        [Nn]* ) BLK "Using Current Key"; break;;
        * ) RED "Please answer (y/n).";;
    esac
done

# Pause and wait
read -t 60 -n 1 -p "Press any key to exit…(60 sec timeout)"

# == [ Send Keys to Server / NAS ] ================================================
# Adds a clients id_rsa.pub to authorized_keys for user on NAS

QST "Server Hostname or IP"
SERVER="$REPLY"
QST "Username on \"$SERVER\""
USERNAME="$REPLY"

# [ These run from workstation and connect to server ]
# On NAS: You need to create a directory with a file containing the the authorized keys of clients being able to connect.
# On NAS: Copy the content of your id_rsa.pub file from your Host-computer (the one you want to connect from) into the authorized_keys file.
# On NAS: Change the file permissions of the authorized-key file.
cat ~/.ssh/id_rsa.pub | ssh $USERNAME@$SERVER 'mkdir ~/.ssh; touch ~/.ssh/authorized_keys; cat >> ~/.ssh/authorized_keys; chmod 700 ~/.ssh; chmod 644 ~/.ssh/authorized_keys; echo "========================"; cat ~/.ssh/authorized_keys; echo "========================";'

# Pause and wait
read -t 60 -n 1 -p "Press any key to exit…(60 sec timeout)"


#!/system/bin/sh
# Niko Tweaks created by haxislancelot @ GitHub, If you're going to use some code from my module, give me the credits, I'll be grateful.
DEBUG=true

if [[ ! -e "/sdcard/Niko Logs" ]]; then
   rm -rf /sdcard/Niko Logs
fi

mkdir "/sdcard/Niko Logs"

log=/sdcard/Niko Logs/installation.log
echo "If this file is useless to you, you can delete it." >> $log

sleep 4
ui_print "╭━╮╱╭╮╭━━╮╭╮╭━╮╭━━━╮"
ui_print "┃┃╰╮┃┃╰┫┣╯┃┃┃╭╯┃╭━╮┃"
ui_print "┃╭╮╰╯┃╱┃┃╱┃╰╯╯╱┃┃╱┃┃"
ui_print "┃┃╰╮┃┃╱┃┃╱┃╭╮┃╱┃┃╱┃┃"
ui_print "┃┃╱┃┃┃╭┫┣╮┃┃┃╰╮┃╰━╯┃"
ui_print "╰╯╱╰━╯╰━━╯╰╯╰━╯╰━━━╯"
ui_print "╭━━━━╮╭╮╭╮╭╮╭━━━╮╭━━━╮╭╮╭━╮╭━━━╮"
ui_print "┃╭╮╭╮┃┃┃┃┃┃┃┃╭━━╯┃╭━╮┃┃┃┃╭╯┃╭━╮┃"
ui_print "╰╯┃┃╰╯┃┃┃┃┃┃┃╰━━╮┃┃╱┃┃┃╰╯╯╱┃╰━━╮"
ui_print "╱╱┃┃╱╱┃╰╯╰╯┃┃╭━━╯┃╰━╯┃┃╭╮┃╱╰━━╮┃"
ui_print "╱╱┃┃╱╱╰╮╭╮╭╯┃╰━━╮┃╭━╮┃┃┃┃╰╮┃╰━╯┃"
ui_print "╱╱╰╯╱╱╱╰╯╰╯╱╰━━━╯╰╯╱╰╯╰╯╰━╯╰━━━╯"
ui_print ""
ui_print "- Niko Tweaks is a full featured Magisk module to enhance your device experience,"
ui_print "- Improve your gaming, ram and battery!"
sleep 2
ui_print ""
ui_print "- Module created with much love ♥ by haxislancelot @ GitHub."
sleep 2
ui_print ""
ui_print "- Thank you for trusting my work, I thank you deeply."
sleep 2
ui_print ""
ui_print "- Thanks to all testers and supporters of the project!"
ui_print ""
sleep 2

set_permissions() {
  set_perm_recursive "$MODPATH"/system/bin 0 0 0777 0755
}

SKIPUNZIP=0
unzip -qjo "$ZIPFILE" 'common/functions.sh' -d "$TMPDIR" >&2
. "$TMPDIR"/functions.sh

ui_print "- Installation completed successfully!"
echo "Installation completed successfully!" >> $log


#!/bin/bash

ORG=$PWD
if [ ! -e include ]; then
    echo "Cannot find include directory"
    exit 1
fi
cd include/coopy || exit 1
for f in `ls *.h`; do
    cp $f /tmp
    cp $f /tmp/fix_for_swig.hxx
    $ORG/fix_for_swig1.pl /tmp/fix_for_swig.hxx > $f
done
ls $PWD/*.h
cd ../hx || exit 1
grep -v SWIGFIX Object.h > /tmp/Object.h
sed "s|void operator delete|void operator delete(void*){} // SWIGFIX\n   void operator delete|" /tmp/Object.h > Object.h
ls Object.h


#!/bin/bash
set -eo pipefail

IMAGE=kubeovn/kube-ovn:v1.9.1

echo "[Step 0/8] Update CRD"
cat <<EOF > kube-ovn-crd-1.9.yaml
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: vpc-nat-gateways.kubeovn.io
spec:
  group: kubeovn.io
  names:
    plural: vpc-nat-gateways
    singular: vpc-nat-gateway
    shortNames:
      - vpc-nat-gw
    kind: VpcNatGateway
    listKind: VpcNatGatewayList
  scope: Cluster
  versions:
    - additionalPrinterColumns:
        - jsonPath: .spec.vpc
          name: Vpc
          type: string
        - jsonPath: .spec.subnet
          name: Subnet
          type: string
        - jsonPath: .spec.lanIp
          name: LanIP
          type: string
      name: v1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                dnatRules:
                  type: array
                  items:
                    type: object
                    properties:
                      eip:
                        type: string
                      externalPort:
                        type: string
                      internalIp:
                        type: string
                      internalPort:
                        type: string
                      protocol:
                        type: string
                eips:
                  type: array
                  items:
                    type: object
                    properties:
                      eipCIDR:
                        type: string
                      gateway:
                        type: string
                floatingIpRules:
                  type: array
                  items:
                    type: object
                    properties:
                      eip:
                        type: string
                      internalIp:
                        type: string
                lanIp:
                  type: string
                snatRules:
                  type: array
                  items:
                    type: object
                    properties:
                      eip:
                        type: string
                      internalCIDR:
                        type: string
                subnet:
                  type: string
                vpc:
                  type: string
                selector:
                  type: array
                  items:
                    type: string
      subresources:
        status: {}
  conversion:
    strategy: None
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: vpcs.kubeovn.io
spec:
  group: kubeovn.io
  versions:
    - additionalPrinterColumns:
        - jsonPath: .status.standby
          name: Standby
          type: boolean
        - jsonPath: .status.subnets
          name: Subnets
          type: string
        - jsonPath: .spec.namespaces
          name: Namespaces
          type: string
      name: v1
      schema:
        openAPIV3Schema:
          properties:
            spec:
              properties:
                namespaces:
                  items:
                    type: string
                  type: array
                staticRoutes:
                  items:
                    properties:
                      policy:
                        type: string
                      cidr:
                        type: string
                      nextHopIP:
                        type: string
                    type: object
                  type: array
                policyRoutes:
                  items:
                    properties:
                      priority:
                        type: integer
                      action:
                        type: string
                      match:
                        type: string
                      nextHopIP:
                        type: string
                    type: object
                  type: array
              type: object
            status:
              properties:
                conditions:
                  items:
                    properties:
                      lastTransitionTime:
                        type: string
                      lastUpdateTime:
                        type: string
                      message:
                        type: string
                      reason:
                        type: string
                      status:
                        type: string
                      type:
                        type: string
                    type: object
                  type: array
                default:
                  type: boolean
                defaultLogicalSwitch:
                  type: string
                router:
                  type: string
                standby:
                  type: boolean
                subnets:
                  items:
                    type: string
                  type: array
                tcpLoadBalancer:
                  type: string
                tcpSessionLoadBalancer:
                  type: string
                udpLoadBalancer:
                  type: string
                udpSessionLoadBalancer:
                  type: string
              type: object
          type: object
      served: true
      storage: true
      subresources:
        status: {}
  names:
    kind: Vpc
    listKind: VpcList
    plural: vpcs
    shortNames:
      - vpc
    singular: vpc
  scope: Cluster
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: ips.kubeovn.io
spec:
  group: kubeovn.io
  versions:
    - name: v1
      served: true
      storage: true
      additionalPrinterColumns:
      - name: V4IP
        type: string
        jsonPath: .spec.v4IpAddress
      - name: V6IP
        type: string
        jsonPath: .spec.v6IpAddress
      - name: Mac
        type: string
        jsonPath: .spec.macAddress
      - name: Node
        type: string
        jsonPath: .spec.nodeName
      - name: Subnet
        type: string
        jsonPath: .spec.subnet
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                podName:
                  type: string
                namespace:
                  type: string
                subnet:
                  type: string
                attachSubnets:
                  type: array
                  items:
                    type: string
                nodeName:
                  type: string
                ipAddress:
                  type: string
                v4IpAddress:
                  type: string
                v6IpAddress:
                  type: string
                attachIps:
                  type: array
                  items:
                    type: string
                macAddress:
                  type: string
                attachMacs:
                  type: array
                  items:
                    type: string
                containerID:
                  type: string
  scope: Cluster
  names:
    plural: ips
    singular: ip
    kind: IP
    shortNames:
      - ip
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: subnets.kubeovn.io
spec:
  group: kubeovn.io
  versions:
    - name: v1
      served: true
      storage: true
      subresources:
        status: {}
      additionalPrinterColumns:
      - name: Provider
        type: string
        jsonPath: .spec.provider
      - name: Vpc
        type: string
        jsonPath: .spec.vpc
      - name: Protocol
        type: string
        jsonPath: .spec.protocol
      - name: CIDR
        type: string
        jsonPath: .spec.cidrBlock
      - name: Private
        type: boolean
        jsonPath: .spec.private
      - name: NAT
        type: boolean
        jsonPath: .spec.natOutgoing
      - name: Default
        type: boolean
        jsonPath: .spec.default
      - name: GatewayType
        type: string
        jsonPath: .spec.gatewayType
      - name: V4Used
        type: number
        jsonPath: .status.v4usingIPs
      - name: V4Available
        type: number
        jsonPath: .status.v4availableIPs
      - name: V6Used
        type: number
        jsonPath: .status.v6usingIPs
      - name: V6Available
        type: number
        jsonPath: .status.v6availableIPs
      - name: ExcludeIPs
        type: string
        jsonPath: .spec.excludeIps
      schema:
        openAPIV3Schema:
          type: object
          properties:
            status:
              type: object
              properties:
                v4availableIPs:
                  type: number
                v4usingIPs:
                  type: number
                v6availableIPs:
                  type: number
                v6usingIPs:
                  type: number
                activateGateway:
                  type: string
                conditions:
                  type: array
                  items:
                    type: object
                    properties:
                      type:
                        type: string
                      status:
                        type: string
                      reason:
                        type: string
                      message:
                        type: string
                      lastUpdateTime:
                        type: string
                      lastTransitionTime:
                        type: string
            spec:
              type: object
              properties:
                vpc:
                  type: string
                default:
                  type: boolean
                protocol:
                  type: string
                cidrBlock:
                  type: string
                namespaces:
                  type: array
                  items:
                    type: string
                gateway:
                  type: string
                provider:
                  type: string
                excludeIps:
                  type: array
                  items:
                    type: string
                gatewayType:
                  type: string
                allowSubnets:
                  type: array
                  items:
                    type: string
                gatewayNode:
                  type: string
                natOutgoing:
                  type: boolean
                externalEgressGateway:
                  type: string
                policyRoutingPriority:
                  type: integer
                  minimum: 1
                  maximum: 32765
                policyRoutingTableID:
                  type: integer
                  minimum: 1
                  maximum: 2147483647
                  not:
                    enum:
                      - 252 # compat
                      - 253 # default
                      - 254 # main
                      - 255 # local
                private:
                  type: boolean
                vlan:
                  type: string
                logicalGateway:
                  type: boolean
                disableGatewayCheck:
                  type: boolean
                disableInterConnection:
                  type: boolean
                htbqos:
                  type: string
  scope: Cluster
  names:
    plural: subnets
    singular: subnet
    kind: Subnet
    shortNames:
      - subnet
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: vlans.kubeovn.io
spec:
  group: kubeovn.io
  versions:
    - name: v1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                id:
                  type: integer
                  minimum: 0
                  maximum: 4095
                provider:
                  type: string
                vlanId:
                  type: integer
                  description: Deprecated in favor of id
                providerInterfaceName:
                  type: string
                  description: Deprecated in favor of provider
              required:
                - provider
            status:
              type: object
              properties:
                subnets:
                  type: array
                  items:
                    type: string
      additionalPrinterColumns:
      - name: ID
        type: string
        jsonPath: .spec.id
      - name: Provider
        type: string
        jsonPath: .spec.provider
  scope: Cluster
  names:
    plural: vlans
    singular: vlan
    kind: Vlan
    shortNames:
      - vlan
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: provider-networks.kubeovn.io
spec:
  group: kubeovn.io
  versions:
    - name: v1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            metadata:
              type: object
              properties:
                name:
                  type: string
                  maxLength: 12
                  not:
                    enum:
                      - int
                      - external
            spec:
              type: object
              properties:
                defaultInterface:
                  type: string
                  maxLength: 15
                  pattern: '^[^/\s]+$'
                customInterfaces:
                  type: array
                  items:
                    type: object
                    properties:
                      interface:
                        type: string
                        maxLength: 15
                        pattern: '^[^/\s]+$'
                      nodes:
                        type: array
                        items:
                          type: string
                excludeNodes:
                  type: array
                  items:
                    type: string
              required:
                - defaultInterface
            status:
              type: object
              properties:
                ready:
                  type: boolean
                readyNodes:
                  type: array
                  items:
                    type: string
                vlans:
                  type: array
                  items:
                    type: string
                conditions:
                  type: array
                  items:
                    type: object
                    properties:
                      node:
                        type: string
                      type:
                        type: string
                      status:
                        type: string
                      reason:
                        type: string
                      message:
                        type: string
                      lastUpdateTime:
                        type: string
                      lastTransitionTime:
                        type: string
      additionalPrinterColumns:
      - name: DefaultInterface
        type: string
        jsonPath: .spec.defaultInterface
      - name: Ready
        type: boolean
        jsonPath: .status.ready
  scope: Cluster
  names:
    plural: provider-networks
    singular: provider-network
    kind: ProviderNetwork
    listKind: ProviderNetworkList
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: security-groups.kubeovn.io
spec:
  group: kubeovn.io
  names:
    plural: security-groups
    singular: security-group
    shortNames:
      - sg
    kind: SecurityGroup
    listKind: SecurityGroupList
  scope: Cluster
  versions:
    - name: v1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                ingressRules:
                  type: array
                  items:
                    type: object
                    properties:
                      ipVersion:
                        type: string
                      protocol:
                        type: string
                      priority:
                        type: integer
                      remoteType:
                        type: string
                      remoteAddress:
                        type: string
                      remoteSecurityGroup:
                        type: string
                      portRangeMin:
                        type: integer
                      portRangeMax:
                        type: integer
                      policy:
                        type: string
                egressRules:
                  type: array
                  items:
                    type: object
                    properties:
                      ipVersion:
                        type: string
                      protocol:
                        type: string
                      priority:
                        type: integer
                      remoteType:
                        type: string
                      remoteAddress:
                        type: string
                      remoteSecurityGroup:
                        type: string
                      portRangeMin:
                        type: integer
                      portRangeMax:
                        type: integer
                      policy:
                        type: string
                allowSameGroupTraffic:
                  type: boolean
            status:
              type: object
              properties:
                portGroup:
                  type: string
                allowSameGroupTraffic:
                  type: boolean
                ingressMd5:
                  type: string
                egressMd5:
                  type: string
                ingressLastSyncSuccess:
                  type: boolean
                egressLastSyncSuccess:
                  type: boolean
      subresources:
        status: {}
  conversion:
    strategy: None
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: htbqoses.kubeovn.io
spec:
  group: kubeovn.io
  versions:
    - name: v1
      served: true
      storage: true
      additionalPrinterColumns:
      - name: PRIORITY
        type: string
        jsonPath: .spec.priority
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                priority:
                  type: string					# Value in range 0 to 4,294,967,295.
  scope: Cluster
  names:
    plural: htbqoses
    singular: htbqos
    kind: HtbQos
    shortNames:
      - htbqos
EOF

kubectl apply -f kube-ovn-crd-1.9.yaml
echo "-------------------------------"
echo ""

echo "[Step 1/8] Update Cluster Role"

cat <<EOF > kube-ovn-cluster-role-1.9.yaml
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  annotations:
    rbac.authorization.k8s.io/system-only: "true"
  name: system:ovn
rules:
  - apiGroups: ['policy']
    resources: ['podsecuritypolicies']
    verbs:     ['use']
    resourceNames:
      - kube-ovn
  - apiGroups:
      - "kubeovn.io"
    resources:
      - vpcs
      - vpcs/status
      - vpc-nat-gateways
      - subnets
      - subnets/status
      - ips
      - vlans
      - provider-networks
      - provider-networks/status
      - security-groups
      - security-groups/status
      - htbqoses
    verbs:
      - "*"
  - apiGroups:
      - ""
    resources:
      - pods
      - pods/exec
      - namespaces
      - nodes
      - configmaps
    verbs:
      - create
      - get
      - list
      - watch
      - patch
      - update
  - apiGroups:
      - ""
      - networking.k8s.io
      - apps
      - extensions
    resources:
      - networkpolicies
      - services
      - endpoints
      - statefulsets
      - daemonsets
      - deployments
      - deployments/scale
    verbs:
      - create
      - delete
      - update
      - patch
      - get
      - list
      - watch
  - apiGroups:
      - ""
    resources:
      - events
    verbs:
      - create
      - patch
      - update
  - apiGroups:
      - "k8s.cni.cncf.io"
    resources:
      - network-attachment-definitions
    verbs:
      - create
      - delete
      - get
      - list
      - update
  - apiGroups:
      - "kubevirt.io"
    resources:
      - virtualmachines
      - virtualmachineinstances
    verbs:
      - get
      - list
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: ovn
roleRef:
  name: system:ovn
  kind: ClusterRole
  apiGroup: rbac.authorization.k8s.io
subjects:
  - kind: ServiceAccount
    name: ovn
    namespace: kube-system
EOF

kubectl apply -f kube-ovn-cluster-role-1.9.yaml
echo "-------------------------------"
echo ""

echo "[Step 2/8] Update ovn-central"
kubectl set image deployment/ovn-central -n kube-system ovn-central="$IMAGE"
kubectl rollout status deployment/ovn-central -n kube-system
echo "-------------------------------"
echo ""

echo "[Step 3/8] Update ovs-ovn"
kubectl set image ds/ovs-ovn -n kube-system openvswitch="$IMAGE"
kubectl delete pod -n kube-system -lapp=ovs
echo "-------------------------------"
echo ""

echo "[Step 4/8] Update kube-ovn-controller"
kubectl set image deployment/kube-ovn-controller -n kube-system kube-ovn-controller="$IMAGE"
if [[ ! $(kubectl get deploy -n kube-system kube-ovn-controller -o jsonpath='{.spec.template.spec.containers[0].args}') =~ "logtostderr" ]]; then
  kubectl patch deploy/kube-ovn-controller -n kube-system --type='json' -p='[{"op": "add", "path": "/spec/template/spec/containers/0/args/-", "value": "--logtostderr=false"}, {"op": "add", "path": "/spec/template/spec/containers/0/args/-", "value": "--alsologtostderr=true"}, {"op": "add", "path": "/spec/template/spec/containers/0/args/-", "value": "--log_file=/var/log/kube-ovn/kube-ovn-controller.log"}, {"op": "add", "path": "/spec/template/spec/containers/0/volumeMounts/-", "value": {"mountPath": "/var/log/kube-ovn", "name": "kube-ovn-log"}}, {"op": "add", "path": "/spec/template/spec/volumes/-", "value": {"hostPath": {"path": "/var/log/kube-ovn"}, "name": "kube-ovn-log"}}]'
fi
kubectl patch deploy/kube-ovn-controller -n kube-system --type='json' -p='[{"op": "replace", "path": "/spec/template/spec/containers/0/readinessProbe/exec/command", "value": ["/kube-ovn/kube-ovn-controller-healthcheck"]}, {"op": "replace", "path": "/spec/template/spec/containers/0/livenessProbe/exec/command", "value": ["/kube-ovn/kube-ovn-controller-healthcheck"]}]'
kubectl rollout status deployment/kube-ovn-controller -n kube-system
echo "-------------------------------"
echo ""

echo "[Step 5/8] Update kube-ovn-cni"
kubectl set image ds/kube-ovn-cni -n kube-system cni-server="$IMAGE"
if [[ ! $(kubectl get ds -n kube-system kube-ovn-cni -o jsonpath='{.spec.template.spec.containers[0].args}') =~ "logtostderr" ]]; then
  kubectl patch ds/kube-ovn-cni -n kube-system --type='json' -p='[{"op": "add", "path": "/spec/template/spec/containers/0/args/-", "value": "--logtostderr=false"}, {"op": "add", "path": "/spec/template/spec/containers/0/args/-", "value": "--alsologtostderr=true"}, {"op": "add", "path": "/spec/template/spec/containers/0/args/-", "value": "--log_file=/var/log/kube-ovn/kube-ovn-cni.log"}, {"op": "add", "path": "/spec/template/spec/containers/0/volumeMounts/-", "value": {"mountPath": "/var/log/kube-ovn", "name": "kube-ovn-log"}}, {"op": "add", "path": "/spec/template/spec/volumes/-", "value": {"hostPath": {"path": "/var/log/kube-ovn"}, "name": "kube-ovn-log"}}]'
fi
kubectl rollout status daemonset/kube-ovn-cni -n kube-system
echo "-------------------------------"
echo ""

echo "[Step 6/8] Update kube-ovn-pinger"
kubectl set image ds/kube-ovn-pinger -n kube-system pinger="$IMAGE"
kubectl rollout status daemonset/kube-ovn-pinger -n kube-system
echo "-------------------------------"
echo ""

echo "[Step 7/8] Update kube-ovn-monitor"
kubectl set image deployment/kube-ovn-monitor -n kube-system kube-ovn-monitor="$IMAGE"
kubectl rollout status deployment/kube-ovn-monitor -n kube-system
echo "-------------------------------"
echo ""

echo "[Step 8/8] Update kubectl ko plugin"
mkdir -p /usr/local/bin
cat <<\EOF > /usr/local/bin/kubectl-ko
#!/bin/bash
set -euo pipefail

KUBE_OVN_NS=kube-system
OVN_NB_POD=
OVN_SB_POD=
KUBE_OVN_VERSION=
REGISTRY="kubeovn"

showHelp(){
  echo "kubectl ko {subcommand} [option...]"
  echo "Available Subcommands:"
  echo "  [nb|sb] [status|kick|backup|dbstatus|restore]     ovn-db operations show cluster status, kick stale server, backup database, get db consistency status or restore ovn nb db when met 'inconsistent data' error"
  echo "  nbctl [ovn-nbctl options ...]    invoke ovn-nbctl"
  echo "  sbctl [ovn-sbctl options ...]    invoke ovn-sbctl"
  echo "  vsctl {nodeName} [ovs-vsctl options ...]   invoke ovs-vsctl on the specified node"
  echo "  ofctl {nodeName} [ovs-ofctl options ...]   invoke ovs-ofctl on the specified node"
  echo "  dpctl {nodeName} [ovs-dpctl options ...]   invoke ovs-dpctl on the specified node"
  echo "  appctl {nodeName} [ovs-appctl options ...]   invoke ovs-appctl on the specified node"
  echo "  tcpdump {namespace/podname} [tcpdump options ...]     capture pod traffic"
  echo "  trace {namespace/podname} {target ip address} {icmp|tcp|udp} [target tcp or udp port]    trace ovn microflow of specific packet"
  echo "  diagnose {all|node} [nodename]    diagnose connectivity of all nodes or a specific node"
  echo "  reload restart all kube-ovn components"
}

tcpdump(){
  namespacedPod="$1"; shift
  namespace=$(echo "$namespacedPod" | cut -d "/" -f1)
  podName=$(echo "$namespacedPod" | cut -d "/" -f2)
  if [ "$podName" = "$namespacedPod" ]; then
    namespace="default"
  fi

  nodeName=$(kubectl get pod "$podName" -n "$namespace" -o jsonpath={.spec.nodeName})
  hostNetwork=$(kubectl get pod "$podName" -n "$namespace" -o jsonpath={.spec.hostNetwork})

  if [ -z "$nodeName" ]; then
    echo "Pod $namespacedPod not exists on any node"
    exit 1
  fi

  ovnCni=$(kubectl get pod -n $KUBE_OVN_NS -o wide| grep kube-ovn-cni| grep " $nodeName " | awk '{print $1}')
  if [ -z "$ovnCni" ]; then
    echo "kube-ovn-cni not exist on node $nodeName"
    exit 1
  fi

  if [ "$hostNetwork" = "true" ]; then
    set -x
    kubectl exec "$ovnCni" -n $KUBE_OVN_NS -- tcpdump -nn "$@"
  else
    nicName=$(kubectl exec "$ovnCni" -n $KUBE_OVN_NS -- ovs-vsctl --data=bare --no-heading --columns=name find interface external-ids:iface-id="$podName"."$namespace" | tr -d '\r')
    if [ -z "$nicName" ]; then
      echo "nic doesn't exist on node $nodeName"
      exit 1
    fi
    podNicType=$(kubectl get pod "$podName" -n "$namespace" -o jsonpath={.metadata.annotations.ovn\\.kubernetes\\.io/pod_nic_type})
    podNetNs=$(kubectl exec "$ovnCni" -n $KUBE_OVN_NS -- ovs-vsctl --data=bare --no-heading get interface "$nicName" external-ids:pod_netns | tr -d '\r' | sed -e 's/^"//' -e 's/"$//')
    set -x
    if [ "$podNicType" = "internal-port" ]; then
      kubectl exec "$ovnCni" -n $KUBE_OVN_NS -- nsenter --net="$podNetNs" tcpdump -nn -i "$nicName" "$@"
    else
      kubectl exec "$ovnCni" -n $KUBE_OVN_NS -- nsenter --net="$podNetNs" tcpdump -nn -i eth0 "$@"
    fi
  fi
}

trace(){
  namespacedPod="$1"
  namespace=$(echo "$1" | cut -d "/" -f1)
  podName=$(echo "$1" | cut -d "/" -f2)
  if [ "$podName" = "$1" ]; then
    namespace="default"
  fi

  dst="$2"
  if [ -z "$dst" ]; then
    echo "need a target ip address"
    exit 1
  fi

  af="4"
  nw="nw"
  proto=""
  if [[ "$dst" =~ .*:.* ]]; then
    af="6"
    nw="ipv6"
    proto="6"
  fi

  hostNetwork=$(kubectl get pod "$podName" -n "$namespace" -o jsonpath={.spec.hostNetwork})
  if [ "$hostNetwork" = "true" ]; then
    echo "Can not trace host network pod"
    exit 1
  fi

  ls=$(kubectl get pod "$podName" -n "$namespace" -o jsonpath={.metadata.annotations.ovn\\.kubernetes\\.io/logical_switch})
  if [ -z "$ls" ]; then
    echo "pod address not ready"
    exit 1
  fi

  podIPs=($(kubectl get pod "$podName" -n "$namespace" -o jsonpath="{.status.podIPs[*].ip}"))
  if [ ${#podIPs[@]} -eq 0 ]; then
    podIPs=($(kubectl get pod "$podName" -n "$namespace" -o jsonpath={.metadata.annotations.ovn\\.kubernetes\\.io/ip_address} | sed 's/,/ /g'))
    if [ ${#podIPs[@]} -eq 0 ]; then
      echo "pod address not ready"
      exit 1
    fi
  fi

  mac=$(kubectl get pod "$podName" -n "$namespace" -o jsonpath={.metadata.annotations.ovn\\.kubernetes\\.io/mac_address})
  nodeName=$(kubectl get pod "$podName" -n "$namespace" -o jsonpath={.spec.nodeName})

  podIP=""
  for ip in ${podIPs[@]}; do
    if [ "$af" = "4" ]; then
      if [[ ! "$ip" =~ .*:.* ]]; then
        podIP=$ip
        break
      fi
    elif [[ "$ip" =~ .*:.* ]]; then
      podIP=$ip
      break
    fi
  done

  if [ -z "$podIP" ]; then
    echo "Pod has no IPv$af address"
    exit 1
  fi

  gwMac=""
  vlan=$(kubectl get subnet "$ls" -o jsonpath={.spec.vlan})
  logicalGateway=$(kubectl get subnet "$ls" -o jsonpath={.spec.logicalGateway})
  if [ ! -z "$vlan" -a "$logicalGateway" != "true" ]; then
    gateway=$(kubectl get subnet "$ls" -o jsonpath={.spec.gateway})
    if [[ "$gateway" =~ .*,.* ]]; then
      if [ "$af" = "4" ]; then
        gateway=${gateway%%,*}
      else
        gateway=${gateway##*,}
      fi
    fi

    ovnCni=$(kubectl get pod -n $KUBE_OVN_NS -o wide | grep -w kube-ovn-cni | grep " $nodeName " | awk '{print $1}')
    if [ -z "$ovnCni" ]; then
      echo "No kube-ovn-cni Pod running on node $nodeName"
      exit 1
    fi

    nicName=$(kubectl exec "$ovnCni" -n $KUBE_OVN_NS -- ovs-vsctl --data=bare --no-heading --columns=name find interface external-ids:iface-id="$podName"."$namespace" | tr -d '\r')
    if [ -z "$nicName" ]; then
      echo "nic doesn't exist on node $nodeName"
      exit 1
    fi

    podNicType=$(kubectl get pod "$podName" -n "$namespace" -o jsonpath={.metadata.annotations.ovn\\.kubernetes\\.io/pod_nic_type})
    podNetNs=$(kubectl exec "$ovnCni" -n $KUBE_OVN_NS -- ovs-vsctl --data=bare --no-heading get interface "$nicName" external-ids:pod_netns | tr -d '\r' | sed -e 's/^"//' -e 's/"$//')
    if [ "$podNicType" != "internal-port" ]; then
      nicName="eth0"
    fi

    if [[ "$gateway" =~ .*:.* ]]; then
      cmd="ndisc6 -q $gateway $nicName"
      output=$(kubectl exec "$ovnCni" -n $KUBE_OVN_NS -- nsenter --net="$podNetNs" ndisc6 -q "$gateway" "$nicName")
    else
      cmd="arping -c3 -C1 -i1 -I $nicName $gateway"
      output=$(kubectl exec "$ovnCni" -n $KUBE_OVN_NS -- nsenter --net="$podNetNs" arping -c3 -C1 -i1 -I "$nicName" "$gateway")
    fi

    if [ $? -ne 0 ]; then
      echo "failed to run '$cmd' in Pod's netns"
      exit 1
    fi
    gwMac=$(echo "$output" | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}')
  else
    lr=$(kubectl get pod "$podName" -n "$namespace" -o jsonpath={.metadata.annotations.ovn\\.kubernetes\\.io/logical_router})
    if [ -z "$lr" ]; then
      lr=$(kubectl get subnet "$ls" -o jsonpath={.spec.vpc})
    fi
    gwMac=$(kubectl exec $OVN_NB_POD -n $KUBE_OVN_NS -c ovn-central -- ovn-nbctl --data=bare --no-heading --columns=mac find logical_router_port name="$lr"-"$ls" | tr -d '\r')
  fi

  if [ -z "$gwMac" ]; then
    echo "get gw mac failed"
    exit 1
  fi

  type="$3"
  case $type in
    icmp)
      set -x
      kubectl exec "$OVN_SB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovn-trace --ct=new "$ls" "inport == \"$podName.$namespace\" && ip.ttl == 64 && icmp && eth.src == $mac && ip$af.src == $podIP && eth.dst == $gwMac && ip$af.dst == $dst"
      ;;
    tcp|udp)
      set -x
      kubectl exec "$OVN_SB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovn-trace --ct=new "$ls" "inport == \"$podName.$namespace\" && ip.ttl == 64 && eth.src == $mac && ip$af.src == $podIP && eth.dst == $gwMac && ip$af.dst == $dst && $type.src == 10000 && $type.dst == $4"
      ;;
    *)
      echo "type $type not supported"
      echo "kubectl ko trace {namespace/podname} {target ip address} {icmp|tcp|udp} [target tcp or udp port]"
      exit 1
      ;;
  esac

  set +x
  echo "--------"
  echo "Start OVS Tracing"
  echo ""
  echo ""

  ovsPod=$(kubectl get pod -n $KUBE_OVN_NS -o wide | grep " $nodeName " | grep ovs-ovn | awk '{print $1}')
  if [ -z "$ovsPod" ]; then
    echo "ovs pod doesn't exist on node $nodeName"
    exit 1
  fi

  inPort=$(kubectl exec "$ovsPod" -n $KUBE_OVN_NS -- ovs-vsctl --format=csv --data=bare --no-heading --columns=ofport find interface external_id:iface-id="$podName"."$namespace")
  case $type in
    icmp)
      set -x
      kubectl exec "$ovsPod" -n $KUBE_OVN_NS -- ovs-appctl ofproto/trace br-int "in_port=$inPort,icmp$proto,${nw}_src=$podIP,${nw}_dst=$dst,dl_src=$mac,dl_dst=$gwMac"
      ;;
    tcp|udp)
      set -x
      kubectl exec "$ovsPod" -n $KUBE_OVN_NS -- ovs-appctl ofproto/trace br-int "in_port=$inPort,$type$proto,${nw}_src=$podIP,${nw}_dst=$dst,dl_src=$mac,dl_dst=$gwMac,${type}_src=1000,${type}_dst=$4"
      ;;
    *)
      echo "type $type not supported"
      echo "kubectl ko trace {namespace/podname} {target ip address} {icmp|tcp|udp} [target tcp or udp port]"
      exit 1
      ;;
  esac
}

xxctl(){
  subcommand="$1"; shift
  nodeName="$1"; shift
  kubectl get no "$nodeName" > /dev/null
  ovsPod=$(kubectl get pod -n $KUBE_OVN_NS -o wide | grep " $nodeName " | grep ovs-ovn | awk '{print $1}')
  if [ -z "$ovsPod" ]; then
    echo "ovs pod  doesn't exist on node $nodeName"
    exit 1
  fi
  kubectl exec "$ovsPod" -n $KUBE_OVN_NS -- ovs-$subcommand "$@"
}

checkLeader(){
  component="$1"; shift
  count=$(kubectl get ep ovn-$component -n $KUBE_OVN_NS -o yaml | grep ip | wc -l)
  if [ $count -eq 0 ]; then
    echo "no ovn-$component exists !!"
    exit 1
  fi

  if [ $count -gt 1 ]; then
    echo "ovn-$component has more than one leader !!"
    exit 1
  fi

  echo "ovn-$component leader check ok"
}

diagnose(){
  kubectl get crd vpcs.kubeovn.io
  kubectl get crd vpc-nat-gateways.kubeovn.io
  kubectl get crd subnets.kubeovn.io
  kubectl get crd ips.kubeovn.io
  kubectl get crd vlans.kubeovn.io
  kubectl get crd provider-networks.kubeovn.io
  set +eu
  if ! kubectl get svc kube-dns -n kube-system ; then
     echo "Warning: kube-dns doesn't exist, maybe there is coredns service."
  fi
  set -eu
  kubectl get svc kubernetes -n default
  kubectl get sa -n kube-system ovn
  kubectl get clusterrole system:ovn
  kubectl get clusterrolebinding ovn

  kubectl get no -o wide
  kubectl ko nbctl show
  kubectl ko nbctl lr-policy-list ovn-cluster
  kubectl ko nbctl lr-route-list ovn-cluster
  kubectl ko nbctl ls-lb-list ovn-default
  kubectl ko nbctl list address_set
  kubectl ko nbctl list acl
  kubectl ko sbctl show

  checkKubeProxy
  checkDeployment ovn-central
  checkDeployment kube-ovn-controller
  checkDaemonSet kube-ovn-cni
  checkDaemonSet ovs-ovn
  checkDeployment coredns

  checkLeader nb
  checkLeader sb
  checkLeader northd

  type="$1"
  case $type in
    all)
      echo "### kube-ovn-controller recent log"
      set +e
      kubectl logs -n $KUBE_OVN_NS -l app=kube-ovn-controller --tail=100 | grep E$(date +%m%d)
      set -e
      echo ""
      pingers=$(kubectl -n $KUBE_OVN_NS get po --no-headers -o custom-columns=NAME:.metadata.name -l app=kube-ovn-pinger)
      for pinger in $pingers
      do
        nodeName=$(kubectl get pod "$pinger" -n "$KUBE_OVN_NS" -o jsonpath={.spec.nodeName})
        echo "### start to diagnose node $nodeName"
        echo "#### ovn-controller log:"
        kubectl exec -n $KUBE_OVN_NS "$pinger" -- tail /var/log/ovn/ovn-controller.log
        echo ""
        echo "#### ovs-vswitchd log:"
        kubectl exec -n $KUBE_OVN_NS "$pinger" -- tail /var/log/openvswitch/ovs-vswitchd.log
        echo ""
        echo "#### ovs-vsctl show results:"
        kubectl exec -n $KUBE_OVN_NS "$pinger" -- ovs-vsctl show
        echo ""
        echo "#### pinger diagnose results:"
        kubectl exec -n $KUBE_OVN_NS "$pinger" -- /kube-ovn/kube-ovn-pinger --mode=job
        echo "### finish diagnose node $nodeName"
        echo ""
      done
      ;;
    node)
      nodeName="$2"
      kubectl get no "$nodeName" > /dev/null
      pinger=$(kubectl -n $KUBE_OVN_NS get po -l app=kube-ovn-pinger -o 'jsonpath={.items[?(@.spec.nodeName=="'$nodeName'")].metadata.name}')
      if [ ! -n "$pinger" ]; then
        echo "Error: No kube-ovn-pinger running on node $nodeName"
        exit 1
      fi
      echo "### start to diagnose node $nodeName"
      echo "#### ovn-controller log:"
      kubectl exec -n $KUBE_OVN_NS "$pinger" -- tail /var/log/ovn/ovn-controller.log
      echo ""
      echo "#### ovs-vswitchd log:"
      kubectl exec -n $KUBE_OVN_NS "$pinger" -- tail /var/log/openvswitch/ovs-vswitchd.log
      echo ""
      kubectl exec -n $KUBE_OVN_NS "$pinger" -- /kube-ovn/kube-ovn-pinger --mode=job
      echo "### finish diagnose node $nodeName"
      echo ""
      ;;
    *)
      echo "type $type not supported"
      echo "kubectl ko diagnose {all|node} [nodename]"
      ;;
    esac
}

getOvnCentralPod(){
    NB_POD=$(kubectl get pod -n $KUBE_OVN_NS -l ovn-nb-leader=true | grep ovn-central | head -n 1 | awk '{print $1}')
    if [ -z "$NB_POD" ]; then
      echo "nb leader not exists"
      exit 1
    fi
    OVN_NB_POD=$NB_POD
    SB_POD=$(kubectl get pod -n $KUBE_OVN_NS -l ovn-sb-leader=true | grep ovn-central | head -n 1 | awk '{print $1}')
    if [ -z "$SB_POD" ]; then
      echo "nb leader not exists"
      exit 1
    fi
    OVN_SB_POD=$SB_POD
    VERSION=$(kubectl  -n kube-system get pods -l ovn-sb-leader=true -o yaml | grep  "image: $REGISTRY/kube-ovn:" | head -n 1 | awk -F ':' '{print $3}')
    if [ -z "$VERSION" ]; then
          echo "kubeovn version not exists"
          exit 1
        fi
    KUBE_OVN_VERSION=$VERSION
}

checkDaemonSet(){
  name="$1"
  currentScheduled=$(kubectl get ds -n $KUBE_OVN_NS "$name" -o jsonpath={.status.currentNumberScheduled})
  desiredScheduled=$(kubectl get ds -n $KUBE_OVN_NS "$name" -o jsonpath={.status.desiredNumberScheduled})
  available=$(kubectl get ds -n $KUBE_OVN_NS "$name" -o jsonpath={.status.numberAvailable})
  ready=$(kubectl get ds -n $KUBE_OVN_NS "$name" -o jsonpath={.status.numberReady})
  if [ "$currentScheduled" = "$desiredScheduled" ] && [ "$desiredScheduled" = "$available" ] && [ "$available" = "$ready" ]; then
    echo "ds $name ready"
  else
    echo "Error ds $name not ready"
    exit 1
  fi
}

checkDeployment(){
  name="$1"
  ready=$(kubectl get deployment -n $KUBE_OVN_NS "$name" -o jsonpath={.status.readyReplicas})
  updated=$(kubectl get deployment -n $KUBE_OVN_NS "$name" -o jsonpath={.status.updatedReplicas})
  desire=$(kubectl get deployment -n $KUBE_OVN_NS "$name" -o jsonpath={.status.replicas})
  available=$(kubectl get deployment -n $KUBE_OVN_NS "$name" -o jsonpath={.status.availableReplicas})
  if [ "$ready" = "$updated" ] && [ "$updated" = "$desire" ] && [ "$desire" = "$available" ]; then
    echo "deployment $name ready"
  else
    echo "Error deployment $name not ready"
    exit 1
  fi
}

checkKubeProxy(){
  dsMode=`kubectl get ds -n kube-system | grep kube-proxy || true`
  if [ -z "$dsMode" ]; then
    nodeIps=`kubectl get node -o wide | grep -v "INTERNAL-IP" | awk '{print $6}'`
    for node in $nodeIps
    do
      healthResult=`curl -g -6 -sL -w %{http_code} http://[$node]:10256/healthz -o /dev/null | grep -v 200 || true`
      if [ -n "$healthResult" ]; then
        echo "$node kube-proxy's health check failed"
        exit 1
      fi
    done
  else
    checkDaemonSet kube-proxy
  fi
  echo "kube-proxy ready"
}

dbtool(){
  suffix=$(date +%m%d%H%M%s)
  component="$1"; shift
  action="$1"; shift
  case $component in
    nb)
      case $action in
        status)
          kubectl exec "$OVN_NB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovs-appctl -t /var/run/ovn/ovnnb_db.ctl cluster/status OVN_Northbound
          kubectl exec "$OVN_NB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovs-appctl -t /var/run/ovn/ovnnb_db.ctl ovsdb-server/get-db-storage-status OVN_Northbound
          ;;
        kick)
          kubectl exec "$OVN_NB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovs-appctl -t /var/run/ovn/ovnnb_db.ctl cluster/kick OVN_Northbound "$1"
          ;;
        backup)
          kubectl exec "$OVN_NB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovsdb-tool cluster-to-standalone /etc/ovn/ovnnb_db.$suffix.backup /etc/ovn/ovnnb_db.db
          kubectl cp $KUBE_OVN_NS/$OVN_NB_POD:/etc/ovn/ovnnb_db.$suffix.backup $(pwd)/ovnnb_db.$suffix.backup
          kubectl exec "$OVN_NB_POD" -n $KUBE_OVN_NS -c ovn-central -- rm -f /etc/ovn/ovnnb_db.$suffix.backup
          echo "backup ovn-$component db to $(pwd)/ovnnb_db.$suffix.backup"
          ;;
        dbstatus)
          kubectl exec "$OVN_NB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovn-appctl -t /var/run/ovn/ovnnb_db.ctl ovsdb-server/get-db-storage-status OVN_Northbound
          ;;
        restore)
          # set ovn-central replicas to 0
          replicas=$(kubectl get deployment -n $KUBE_OVN_NS ovn-central -o jsonpath={.spec.replicas})
          kubectl scale deployment -n $KUBE_OVN_NS ovn-central --replicas=0
          echo "ovn-central original replicas is $replicas"

          # backup ovn-nb db
          declare nodeIpArray
          declare podNameArray
          nodeIps=`kubectl get node -lkube-ovn/role=master -o wide | grep -v "INTERNAL-IP" | awk '{print $6}'`
          firstIP=${nodeIps[0]}
          podNames=`kubectl get pod -n $KUBE_OVN_NS | grep ovs-ovn | awk '{print $1}'`
          echo "first nodeIP is $firstIP"

          i=0
          for nodeIp in $nodeIps
          do
            for pod in $podNames
            do
              hostip=$(kubectl get pod -n $KUBE_OVN_NS $pod -o jsonpath={.status.hostIP})
              if [ $nodeIp = $hostip ]; then
                nodeIpArray[$i]=$nodeIp
                podNameArray[$i]=$pod
                i=`expr $i + 1`
                echo "ovs-ovn pod on node $nodeIp is $pod"
                break
              fi
            done
          done

          echo "backup nb db file"
          docker run -it -v /etc/origin/ovn:/etc/ovn $REGISTRY/kube-ovn:$KUBE_OVN_VERSION bash -c "ovsdb-tool cluster-to-standalone  /etc/ovn/ovnnb_db_standalone.db  /etc/ovn/ovnnb_db.db"

          # mv all db files
          for pod in ${podNameArray[@]}
          do
            kubectl exec -it -n $KUBE_OVN_NS $pod -- mv /etc/ovn/ovnnb_db.db /tmp
            kubectl exec -it -n $KUBE_OVN_NS $pod -- mv /etc/ovn/ovnsb_db.db /tmp
          done

          # restore db and replicas
          echo "restore nb db file, operate in pod ${podNameArray[0]}"
          kubectl exec -it -n $KUBE_OVN_NS ${podNameArray[0]} -- mv /etc/ovn/ovnnb_db_standalone.db /etc/ovn/ovnnb_db.db
          kubectl scale deployment -n $KUBE_OVN_NS ovn-central --replicas=$replicas
          echo "finish restore nb db file and ovn-central replicas"
          ;;
        *)
          echo "unknown action $action"
      esac
      ;;
    sb)
      case $action in
        status)
          kubectl exec "$OVN_SB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovs-appctl -t /var/run/ovn/ovnsb_db.ctl cluster/status OVN_Southbound
          kubectl exec "$OVN_SB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovs-appctl -t /var/run/ovn/ovnsb_db.ctl ovsdb-server/get-db-storage-status OVN_Southbound
          ;;
        kick)
          kubectl exec "$OVN_SB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovs-appctl -t /var/run/ovn/ovnsb_db.ctl cluster/kick OVN_Southbound "$1"
          ;;
        backup)
          kubectl exec "$OVN_SB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovsdb-tool cluster-to-standalone /etc/ovn/ovnsb_db.$suffix.backup /etc/ovn/ovnsb_db.db
          kubectl cp $KUBE_OVN_NS/$OVN_SB_POD:/etc/ovn/ovnsb_db.$suffix.backup $(pwd)/ovnsb_db.$suffix.backup
          kubectl exec "$OVN_SB_POD" -n $KUBE_OVN_NS -c ovn-central -- rm -f /etc/ovn/ovnsb_db.$suffix.backup
          echo "backup ovn-$component db to $(pwd)/ovnsb_db.$suffix.backup"
          ;;
        dbstatus)
          kubectl exec "$OVN_NB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovn-appctl -t /var/run/ovn/ovnsb_db.ctl ovsdb-server/get-db-storage-status OVN_Southbound
          ;;
        restore)
          echo "restore cmd is only used for nb db"
          ;;
        *)
          echo "unknown action $action"
      esac
      ;;
    *)
      echo "unknown subcommand $component"
  esac
}

reload(){
  kubectl delete pod -n kube-system -l app=ovn-central
  kubectl rollout status deployment/ovn-central -n kube-system
  kubectl delete pod -n kube-system -l app=ovs
  kubectl delete pod -n kube-system -l app=kube-ovn-controller
  kubectl rollout status deployment/kube-ovn-controller -n kube-system
  kubectl delete pod -n kube-system -l app=kube-ovn-cni
  kubectl rollout status daemonset/kube-ovn-cni -n kube-system
  kubectl delete pod -n kube-system -l app=kube-ovn-pinger
  kubectl rollout status daemonset/kube-ovn-pinger -n kube-system
  kubectl delete pod -n kube-system -l app=kube-ovn-monitor
  kubectl rollout status deployment/kube-ovn-monitor -n kube-system
}

if [ $# -lt 1 ]; then
  showHelp
  exit 0
else
  subcommand="$1"; shift
fi

getOvnCentralPod

case $subcommand in
  nbctl)
    kubectl exec "$OVN_NB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovn-nbctl "$@"
    ;;
  sbctl)
    kubectl exec "$OVN_SB_POD" -n $KUBE_OVN_NS -c ovn-central -- ovn-sbctl "$@"
    ;;
  vsctl|ofctl|dpctl|appctl)
    xxctl "$subcommand" "$@"
    ;;
  nb|sb)
    dbtool "$subcommand" "$@"
    ;;
  tcpdump)
    tcpdump "$@"
    ;;
  trace)
    trace "$@"
    ;;
  diagnose)
    diagnose "$@"
    ;;
  reload)
    reload
    ;;
  *)
    showHelp
    ;;
esac

EOF

echo "Update Success!"
echo "
                    ,,,,
                    ,::,
                   ,,::,,,,
            ,,,,,::::::::::::,,,,,
         ,,,::::::::::::::::::::::,,,
       ,,::::::::::::::::::::::::::::,,
     ,,::::::::::::::::::::::::::::::::,,
    ,::::::::::::::::::::::::::::::::::::,
   ,:::::::::::::,,   ,,:::::,,,::::::::::,
 ,,:::::::::::::,       ,::,     ,:::::::::,
 ,:::::::::::::,   :x,  ,::  :,   ,:::::::::,
,:::::::::::::::,  ,,,  ,::, ,,  ,::::::::::,
,:::::::::::::::::,,,,,,:::::,,,,::::::::::::,    ,:,   ,:,            ,xx,                            ,:::::,   ,:,     ,:: :::,    ,x
,::::::::::::::::::::::::::::::::::::::::::::,    :x: ,:xx:        ,   :xx,                          :xxxxxxxxx, :xx,   ,xx:,xxxx,   :x
,::::::::::::::::::::::::::::::::::::::::::::,    :xxxxx:,  ,xx,  :x:  :xxx:x::,  ::xxxx:           :xx:,  ,:xxx  :xx, ,xx: ,xxxxx:, :x
,::::::::::::::::::::::::::::::::::::::::::::,    :xxxxx,   :xx,  :x:  :xxx,,:xx,:xx:,:xx, ,,,,,,,,,xxx,    ,xx:   :xx:xx:  ,xxx,:xx::x
,::::::,,::::::::,,::::::::,,:::::::,,,::::::,    :x:,xxx:  ,xx,  :xx  :xx:  ,xx,xxxxxx:, ,xxxxxxx:,xxx:,  ,xxx,    :xxx:   ,xxx, :xxxx
,::::,    ,::::,   ,:::::,   ,,::::,    ,::::,    :x:  ,:xx,,:xx::xxxx,,xxx::xx: :xx::::x: ,,,,,,   ,xxxxxxxxx,     ,xx:    ,xxx,  :xxx
,::::,    ,::::,    ,::::,    ,::::,    ,::::,    ,:,    ,:,  ,,::,,:,  ,::::,,   ,:::::,            ,,:::::,        ,,      :x:    ,::
,::::,    ,::::,    ,::::,    ,::::,    ,::::,
 ,,,,,    ,::::,    ,::::,    ,::::,    ,:::,             ,,,,,,,,,,,,,
          ,::::,    ,::::,    ,::::,    ,:::,        ,,,:::::::::::::::,
          ,::::,    ,::::,    ,::::,    ,::::,  ,,,,:::::::::,,,,,,,:::,
          ,::::,    ,::::,    ,::::,     ,::::::::::::,,,,,
           ,,,,     ,::::,     ,,,,       ,,,::::,,,,
                    ,::::,
                    ,,::,
"


<reponame>Symbolics/clotho
#!/bin/sh

# remove build products

rm -rf ./presenter-*


<reponame>linkux-it/dev<gh_stars>1-10
#!/bin/bash
# modified from http://ficate.com/blog/2012/10/15/battery-life-in-the-land-of-tmux/

HEART='♥ '

current_charge=$(cat /proc/acpi/battery/BAT1/state | grep 'remaining capacity' | awk '{print $3}')
total_charge=$(cat /proc/acpi/battery/BAT1/info | grep 'last full capacity' | awk '{print $4}')

charged_slots=$(echo "(($current_charge/$total_charge)*5)+1" | bc -l | cut -d '.' -f 1)
if [[ $charged_slots -gt 5 ]]; then
  charged_slots=5
fi

echo -n '#[fg=colour196]'
for i in `seq 1 $charged_slots`; do echo -n "$HEART"; done

if [[ $charged_slots -lt 5 ]]; then
  echo -n '#[fg=colour254]'
  for i in `seq 1 $(echo "5-$charged_slots" | bc)`; do echo -n "$HEART"; done
fi


<gh_stars>0
#!/bin/bash

while [ "$#" -gt 0 ]; do
    key="$1"
    case $key in
        --quick)
        QUICK="y"
        shift
        ;;
        --full)
        FULL="y"
        shift
        ;;
        --qutip)
        BACKEND="qutip"
        shift
        ;;
        --projectq)
        BACKEND="projectq"
        shift
        ;;
        --stabilizer)
        BACKEND="stabilizer"
        shift
        ;;
        *)
        echo "Unknown argument ${key}"
        exit 1
    esac
done

BACKEND=${BACKEND:-"projectq"} #If not set, use projectq backend

if [ "$QUICK" = y ]; then
    if [ "$FULL" = y ]; then
        echo "Cannot specify both --quick and --full"
        exit 1
    else
        echo "Since --quick is specified we skip tests of optional noise."
        exit 1
    fi
fi

echo "Starting SimulaQron server (noisy setting and using $BACKEND as backend))"
sh "${NETSIM}/run/startAll.sh" -nd "Alice" --noisy_qubits "True" --t1 "0.0001" --backend "$BACKEND"
sleep 1s
echo "Started SimulaQron server (noise setting)"
python "${NETSIM}/tests/auto/optional_noise/test_optional_noise.py"


<filename>commitar.sh
#!/bin/bash
git config credential.helper store
#find ./ -iname .gitignore -exec rm {} \;
#echo "##### GITIGNORE EXCLUIDO ==> OK #####"
git add .
echo "##### GIT ADD ==> OK #####"
data=`date +%d-%m-%Y_%H:%M:%S`
git commit -m $data
echo "##### COMMIT ==> OK #####"
git push origin master #empurrar
echo "##### PUSH ==> OK #####"


<reponame>AnyVisionltd/nvidia-container-runtime
#!/usr/bin/env bats

load ../helpers

function setup() {
    check_runtime
}

@test "ubuntu:12.04 nvidia-smi" {
    run_nvidia_smi "ubuntu:12.04"
}

@test "ubuntu:14.04 nvidia-smi" {
    run_nvidia_smi "ubuntu:14.04"
}

@test "ubuntu:16.04 nvidia-smi" {
    run_nvidia_smi "ubuntu:16.04"
}

@test "ubuntu:16.10 nvidia-smi" {
    run_nvidia_smi "ubuntu:16.10"
}

@test "ubuntu:17.04 nvidia-smi" {
    run_nvidia_smi "ubuntu:17.04"
}


#!/bin/sh -e
# update the repo daily and generate links

#Define the Project direct path
origin=<insert folder path here>

#Predefine subpaths
dbp=$origin/links/dbpedia.org
xdbp=$origin/links/xxx.dbpedia.org

#Define date for new backup
DATE=`date +%Y-%m-%d`
backup=<define folder path here>/$DATE
mkdir $backup

#Clean Directory / File-names
find $origin/links/ -depth -name "* *" -execdir rename 's/ /_/g' "{}" \;

mkdir $backup/dbpedia.org
find $dbp -type f -name "*.nt" -exec cp {} $backup/dbpedia.org \;
find $dbp -type f -name "*.nt.bz2" -exec cp {} $backup/dbpedia.org \;

mkdir $backup/xxx.dbpedia.org
for subdir in $xdbp/*/; do
        xdbpsub=$(basename $subdir)
        mkdir $backup/xxx.dbpedia.org/$xdbpsub
        find $xdbp/$xdbpsub -type f -name "*.nt" -exec cp {} $backup/xxx.dbpedia.org/$xdbpsub \;
        find $xdbp/$xdbpsub -type f -name "*.nt.bz2" -exec cp {} $backup/xxx.dbpedia.org/$xdbpsub \;
done

find $backup -type f -name "*.nt" -exec bzip2 -z {} \;

#Create softlink
ln -s $backup <define folder path here>/$DATE
ln -s $backup <define folder path here>/current

#Create backlinks
python3.4 $origin/tools/scripts/backlinks.py $origin <define folder path here>
find <define folder path here> -type f -name "*.nt.bz2" -exec rm {} \;
find <define folder path here> -type f -name "*.nt" -exec bzip2 -z {} \;

#Fix redirects and convert URI to IRI
alldbpFilenames=""
alldbpRecodedFilenames=""

for file in $backup/dbpedia.org/*nt.bz2; do
        filename=$(basename "$file")
        filename="${filename%%.*}"
        alldbpFilenames="$filename,$alldbpFilenames"
        alldbpRecodedFilenames="$filename-recoded,$alldbpRecodedFilenames"
done
cd <define folder path here>
../run RecodeUris $backup/dbpedia.org .nt.bz2 -recoded.nt.bz2 true ${alldbpFilenames%?}
../run MapSubjectUris <define folder path here> transitive-redirects .ttl.bz2 ${alldbpRecodedFilenames%?} -redirected .nt.bz2 @external $backup/dbpedia.org

find $backup/dbpedia.org/ -type f ! -name "*-recoded-redirected.nt.bz2" -exec rm {} \;

for subdir in $backup/xxx.dbpedia.org/*; do
        allsubFilenames=""
        allsubRecodedFilenames=""
        for file in $subdir/*nt.bz2; do
                filename=$(basename "$file")
                filename="${filename%%.*}"
                allsubFilenames="$filename,$allsubFilenames"
                allsubRecodedFilenames="$filename-recoded,$allsubRecodedFilenames"
        done
        tmp=$(basename $subdir)
        ../run RecodeUris $backup/xxx.dbpedia.org/$tmp .nt.bz2 -recoded.nt.bz2 true ${allsubFilenames%?}
        ../run MapSubjectUris <define folder path here> transitive-redirects .ttl.bz2 ${allsubRecodedFilenames%?} -redirected .nt.bz2 @external $backup/xxx.dbpedia.org/$tmp

        find $backup/xxx.dbpedia.org/$tmp -type f ! -name "*-recoded-redirected.nt.bz2" -exec rm {} \;
done

#Zipping Subdirs and Parent directory
cd $backup
zip -r links.zip .

#Git update
cd $origin
git checkout master
git pull origin master

#Generate, path and validate
cd $origin/code
sh ./bin/generate.sh
sh ./bin/patch.sh
sh ./bin/validate.sh


<gh_stars>1-10
#!/usr/bin/env bash

set -euo pipefail

# web-rust-lang
open http://localhost:4000/

# web-crates-io
open http://localhost:4001/

# web-components
open http://localhost:4050

# web-api-proxy
open http://localhost:8000/api/v1/summary


<gh_stars>100-1000
#!/bin/bash

rustc --emit mir -Z mir-opt-level=3 - <<EOF
// build-pass
#![allow(dead_code)]
trait Foo {
    fn foo(&self);
}

fn foo<'a>(s: &'a mut ()) where &'a mut (): Foo {
    s.foo();
}
fn main() {}
EOF


#!/bin/bash
SCRCPY_SERVER_PATH="$MESON_BUILD_ROOT/server/scrcpy-server" "$MESON_BUILD_ROOT/app/scrcpy"


<reponame>saurabh-kataria/jsalt2019-diadet
#!/bin/bash
# Copyright
#                2018   Johns Hopkins University (Author: <NAME>)
#                2017   <NAME>
#                2017   Johns Hopkins University (Author: <NAME>)
#                2017   Johns Hopkins University (Author: <NAME>)
# Apache 2.0.
#

. ./cmd.sh
. ./path.sh
set -e
mfccdir=`pwd`/mfcc
vaddir=`pwd`/mfcc
vaddiardir=`pwd`/vad_diar

stage=1
config_file=default_config.sh

. parse_options.sh || exit 1;
. datapath.sh
. $config_file

# In this script, we augment SITW dev/eval data with reverberation,
# noise, music, and babble, to use it for test

if [ $stage -le 1 ]; then
    #if we already prepared the noise data for train, we don't have to do it again here
    if [ ! -d "data/chime3background_train" ];then
	kaldi_augmentation/aug_step1_prepare_noise_rir_data.sh data/rirs_info
    fi
fi

if [ $stage -le 2 ]; then
    # Because of the way that wav-reverberate works, we need to apply a correction to SNR to obtain the SNR
    # that we really want, if we mix N files to generate babble (we fix N=7),
    # SNR_real(dB) = SNR_argument(dB) - 10 log10(N)
    kaldi_augmentation/aug_step2_make_aug_data.sh --mode eval \
						  --snrs "15 10 5 0 -5" \
						  --snrs-babble "24 19 14 9 4" \
						  --num-noises-babble "7" \
						  --normalize-output true \
						  "sitw_dev_test sitw_eval_test"
    #remove all backups
    rm -rf data/sitw_*/.backup

    #change names of directories for babble
    snr_arg=(24 19 14 9 4)
    snr_real=(15 10 5 0 -5)
    for((i=0;i<${#snr_arg[*]};i++))
    do
	mv data/sitw_dev_test_babble_snr${snr_arg[$i]} data/sitw_dev_test_babble_snr${snr_real[$i]}
	mv data/sitw_eval_test_babble_snr${snr_arg[$i]} data/sitw_eval_test_babble_snr${snr_real[$i]}
    done
fi

if [ $stage -le 3 ];then
    #put suffixes to test segments in trial files
    for dset in sitw_dev_test sitw_eval_test
    do
	#for noise
	for noise in noise music babble chime3bg
	do
	    for snr in 15 10 5 0 -5
	    do
		if [ "$noise" == "babble" ];then
		    snr_suff=$(($snr+9))
		else
		    snr_suff=$snr
		fi
		suff="${noise}-snr${snr_suff}"
		name=${dset}_${noise}_snr${snr}
		input_list=data/$dset/trials/core-core.lst
		output_list=data/$name/trials/core-core.lst
		mkdir -p data/$name/trials
		awk -v suff=$suff '{ print $1,$2"-"suff,$3}' $input_list > $output_list
	    done
	done
	#for reverb
	for rt60 in 0.0-0.5 0.5-1.0 1.0-1.5 1.5-4.0
	do
	    suff=reverb-rt60-$rt60
	    name=${dset}_reverb_rt60-$rt60
	    input_list=data/$dset/trials/core-core.lst
	    output_list=data/$name/trials/core-core.lst
	    mkdir -p data/$name/trials
	    awk -v suff=$suff '{ print $1,$2"-"suff,$3}' $input_list > $output_list
	done
    done

fi


axel -n 30 https://npm.taobao.org/mirrors/electron/12.0.9/electron-v12.0.9-linux-arm64.zip
axel -n 30 https://npm.taobao.org/mirrors/electron/12.0.9/electron-v12.0.9-win32-x64.zip
axel -n 30 https://npm.taobao.org/mirrors/electron/12.0.9/electron-v12.0.9-win32-ia32.zip
axel -n 30 https://npm.taobao.org/mirrors/electron/12.0.9/electron-v12.0.9-darwin-x64.zip
axel -n 30 https://npm.taobao.org/mirrors/electron/12.0.9/electron-v12.0.9-mas-x64.zip
axel -n 30 https://npm.taobao.org/mirrors/electron/12.0.9/ffmpeg-v12.0.9-linux-ia32.zip
axeln -n 30 https://npm.taobao.org/mirrors/electron/12.0.9/electron-v12.0.9-linux-ia32.zip
axel -n 30 https://npm.taobao.org/mirrors/electron/12.0.9/electron-v12.0.9-linux-ia32.zip
axel -n 30 https://npm.taobao.org/mirrors/electron/12.0.9/electron-v12.0.9-linux-x64.zip
axel -n 30 https://github.com/electron-userland/electron-builder-binaries/releases/download/nsis-3.0.4.1/nsis-3.0.4.1.7z


#!/bin/bash

python3 ../../../scripts/hold_out.py \
    --input_dir celebA_org \
    --output_dir celebA \
    --train_rate 9 \
    --valid_rate 1


<reponame>gitter-badger/megadepth<filename>release.sh
#!/usr/bin/env bash
#build "statlib" version (or main linux version) of megadepth
./run_hbb_build_container.sh
./run_macos_build_container.sh
./run_windows_build_container.sh
#build latest Docker runner image:
/bin/bash -x create_docker_to_run_megadepth.sh


#!/bin/bash

bandcli config chain-id odin

echo "usage ketchup faculty bench jewel rocket latin absurd decide field party reunion cook entry scout scene miss box memory museum decorate guide few verify" \
    | bandcli keys add $1 --recover --keyring-backend test

# Create system validator
echo "y" | bandcli tx staking create-validator \
  --amount 100000000loki \
  --commission-max-change-rate 0.010000000000000000 \
  --commission-max-rate 0.200000000000000000 \
  --commission-rate 0.100000000000000000 \
  --from $1 \
  --moniker oracle-validator \
  --pubkey <KEY> \
  --min-self-delegation 1 \
  --broadcast-mode block \
  --keyring-backend test \
  --node $2

# Create data source and oracle script
echo "y" | bandcli tx oracle create-data-source \
  --name "mock data source" \
  --description "mock data source with 'Hello, World!'" \
  --script /home/stepan/Projects/band/GeoDB-Limited/odin-developer-edition/data-source-scripts/geo-data-v3.py \
  --owner odin1nnfeguq30x6nwxjhaypxymx3nulyspsuja4a2x \
  --from $1 \
  --gas auto \
  --broadcast-mode block \
  --keyring-backend test \
  --node $2

echo "y" | bandcli tx oracle create-oracle-script \
  --name "mock oracle script" \
  --description "mock oracle script with 'Hello, World!' going on 1 DS" \
  --script /home/stepan/Projects/band/GeoDB-Limited/odin-developer-edition/oracle-scripts/geo_data_source_v3.wasm \
  --owner odin1nnfeguq30x6nwxjhaypxymx3nulyspsuja4a2x \
  --from $1 \
  --gas auto \
  --broadcast-mode block \
  --keyring-backend test \
  --node $2

./chain/scripts/start_yoda_odin.sh $1 $2


#!/bin/bash
# ##############################################################################
# Your-SB-Parent-POM/bin/locally-install-stacks.sh
# Script to spin through stacks directory and perform a Maven install on each.
#
# ##############################################################################
for dir in $(find stacks -type d); do
  if [ "${dir}" != "stacks" ]
    then
      echo "Installing Stack: ${dir} from $PWD"
      mvn -f ./${dir}/pom.xml install
  fi
done


#!/bin/zsh

# Utility for auto connecting a bluetooth device
# 	Uses bluetoothctl, bt-device, grep and awk binaries!

if [ $# -eq 0 ] ; then
	printf "\nNo option given. Run with '--help' for more info.\n"
	exit 1
fi
# help option
if [ $1 = "-h" ] || [ $1 = "--help" ] ; then
	# print help message
	printf "\nUtility for auto connecting to bluetooth device.\n"
	printf "Use it with '&' at the end to run it in background.\n\n"
	printf "USAGE: $0 [OPTION] [DEVICE]\n"
	printf "OPTIONS:\n"
	printf "  -h, --help       Display this message and exit\n"
	printf "  -n, --name       Connect to device by name\n"
	printf "  -m, --mac        Connect to device by mac address\n\n"
	printf "For more info please contact me at: <EMAIL>\n"
	# exit process
	exit 0
fi

# get device by name option
if [ $1 = "-n" ] || [ $1 = "--name" ] ; then
	# get the name of the device
	name=$2

	# get the mac address of the device
	macaddress=`bt-device -l | grep "$name" | grep -o "(.*)" | grep -o "[0-9A-Z]\{2\}\:.*[0-9A-Z]\{2\}"`

	# check device existance
	finddevice=`bt-device -l | grep "$name"`
	if [ $? -ne 0 ] ; then
		printf "\nDevice not found! Process stoped.\n"
		exit 1
	fi

# get device by mac address option
elif [ $1 = "-m" ] || [ $1 = "--mac" ] ; then
	# get the mac address of the device
	macaddress=$2

	# check device existance
	finddevice=`bt-device -l | grep "$macaddress"`
	if [ $? -ne 0 ] ; then
		printf "\nDevice not found! Process stoped.\n"
		exit 1
	fi

# option does not exist
else
	printf "\nInvalid option! Run with '--help' for more info.\n"
	# exit process
	exit 1
fi

printf "\nProcess started.\n"

# loop searching for device and connecting to it
while true
do
	# wait 2 seconds between connecting attempts
	sleep 2
	# test the connection status of the given device
	if [ `bt-device -i $macaddress | grep -i "connected" | awk '{print $2}'` = 0 ] ; then
		# connect to device via bluetoothctl command if not connected already
		`bluetoothctl << EOF >> /tmp/auto-con-bt-dev.log 2>&1
		connect $macaddress
		EOF`
	fi
done


<reponame>deepakkum21/xsd2pgschema
#!/bin/bash

sync_update=true

if [ ! `which indexer` ] ; then

 echo "indexer: command not found..."
 echo "Please install Sphinx (http://sphinxsearch.com/)."
 exit 1

fi

XML_DIR=uniprot_xml
SHARD_SIZE=4

XSD_SCHEMA=uniprot.xsd
PREFIX=uniprotkb

IDX_DIR=sphinx_shard
DIC_DIR=sphinx_dic

if [ -d $IDX_DIR ] ; then

 echo
 echo "Do you want to update sphinx index? (y [n]) "

 read ans

 case $ans in
  y*|Y*) ;;
  *) echo stopped.
   exit 1;;
 esac

 if [ $sync_update != "true" ] ; then
  rm -rf $IDX_DIR
 fi

fi

mkdir -p $IDX_DIR

DIC_NAMES=("all" "aut" "pol" "org")
ATTRS=("--attr entry.accession --attr entry.name --attr entry.created" "" "" "")
FIELDS=("" "--field personType.name" "--field evidencedStringType.content" "--field organismNameType.content --field dbReferenceType.id")

dic_id=0

for dic_name in ${DIC_NAMES[@]} ; do

 attrs=${ATTRS[dic_id]}
 fields=${FIELDS[dic_id]}

 let dic_id++

 echo $dic_name

 WORK_DIR=sphinx_work_$dic_name
 DIC_WORK_DIR=sphinx_dic_work_$dic_name
 ERR_DIR=$WORK_DIR/err

 if [ $sync_update != "true" ] ; then
  rm -rf $WORK_DIR
 else
  MD5_DIR=chk_sum_sphinx_$dic_name
 fi

 mkdir -p $WORK_DIR
 mkdir -p $DIC_WORK_DIR
 mkdir -p $ERR_DIR

 err_file=$ERR_DIR/all_err

 if [ $sync_update != "true" ] ; then

  java -classpath ../xsd2pgschema.jar xml2sphinxds --xsd $XSD_SCHEMA --xml $XML_DIR --ds-dir $WORK_DIR --ds-name $PREFIX $attrs $fields --shard-size $SHARD_SIZE 2> $err_file

 else

  java -classpath ../xsd2pgschema.jar xml2sphinxds --xsd $XSD_SCHEMA --xml $XML_DIR --ds-dir $WORK_DIR --ds-name $PREFIX $attrs $fields --shard-size $SHARD_SIZE --sync $MD5_DIR 2> $err_file

 fi

 if [ $? = 0 ] && [ ! -s $err_file ] ; then

  rm -f $err_file

 else

  echo $0 aborted.
  exit 1

 fi

 red='\e[0;31m'
 normal='\e[0m'

 errs=`ls $ERR_DIR/*_err 2> /dev/null | wc -l`

 if [ $errs = 0 ] ; then

  echo

  for proc_id in `seq 1 $SHARD_SIZE` ; do

   _proc_id=`expr $proc_id - 1`

   if [ $dic_name = "all" ] ; then

    mkdir -p $IDX_DIR/"part-"$_proc_id -m 777
    indexer $PREFIX"_p"$_proc_id
    indexer $PREFIX"_p"$_proc_id --buildstops $DIC_WORK_DIR/dictionary_p$_proc_id.txt 100000 --buildfreqs

   else

    indexer $PREFIX"_"$dic_name"_p"$_proc_id
    indexer $PREFIX"_"$dic_name"_p"$_proc_id --buildstops $DIC_WORK_DIR/dictionary_p$_proc_id.txt 100000 --buildfreqs

   fi

   if [ $? != 0 ] ; then

    echo $0 aborted.
    exit 1

   fi

  done

  mkdir -p $DIC_DIR -m 777

  DIC_FILES=

  for proc_id in `seq 1 $SHARD_SIZE` ; do

   _proc_id=`expr $proc_id - 1`
    DIC_FILES="$DIC_FILES$DIC_WORK_DIR/dictionary_p$_proc_id.txt "

  done

  SRC_DIC_FILES=`echo " "$DIC_FILES | sed -e 's/ / \-\-dic /g'`

  java -classpath ../xsd2pgschema.jar dicmerge4sphinx --ds-dir $DIC_WORK_DIR $SRC_DIC_FILES --freq 1

  if [ $dic_name = "all" ] ; then
   indexer $PREFIX"_dic"
  else
   indexer $PREFIX"_dic_"$dic_name
  fi

  if [ $? = 0 ] ; then

   echo "Sphinx index (UniProtKB:"$dic_name") is update."

   if [ $sync_update != "true" ] ; then
    rm -rf $WORK_DIR
   else
    rm -rf $ERR_DIR
   fi

  fi

 else

  echo
  echo -e "${red}$errs errors were detected. Please check the log files for more details.${normal}"
  exit 1

 fi

done

date


# colorize ls output & print in ordered fashion by default
alias ls='ls -Ghal'


#!/bin/bash
docker build "$@" -t bmichalski/base .


#!/bin/bash
#
#$ -cwd
#$ -j y
#$ -S /bin/bash
#
#$ -l mem_free=8G
#

FASTPHASE=/share/apps/fastphase/fastPHASE-1.4

# your code goes here

$FASTPHASE -otest test.inp