#!/bin/bash

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

patch_dir="$script_dir/../patch"
pacth_tmp_dir=$patch_dir/tmp
release_root="$script_dir/../release"
release_date=`date +%Y%m%d`
src_ocs_dir="$script_dir/../../ocs"
ocs_bin_dir=$src_ocs_dir/bin
ocs_bin_file=agtocs

usage() {
    echo "Usage: $0 [ocs|scp|ussdgw [Option] "
    echo 
    echo "Build OCS patch, option as follow:"
    echo "  ocs|scp|ussdgw,                     ocs: OCS package build by dpkg"
    echo "                                      scp: SCP package build by dpkg"
    echo "                                      ussdgw: USSD Gateway package, build by dpkg"
    echo
    echo "  Option:"
    echo "      -t [norfolk|cook|pncc|zed]      Build binary tag, only for ocs, default is pncc"
    echo "      -h, --help                      Display this help and exit"
    echo "                                      goproxy: Golang RestProxy package build by dpkg" 
    echo
    echo "Example:"
    echo "  $0 ocs -t cook"
    echo "  $0 scp -t zed "
    echo "  $0 ussdgw -t zed"
    exit 1
}

pkg_type=""
new_args=()
# Traverse all parameters
for arg in "$@"; do
    if [[ "$arg" == "ocs" || "$arg" == "scp" || "$arg" == "ussdgw" ]]; then
        pkg_type=$arg
    else
        new_args+=("$arg") # Add non pkg_type parameters to a new parameter list
    fi  
done

if [ -z "$pkg_type" ]; then
    usage
    exit 1    
fi

# Use a new parameter list
set -- "${new_args[@]}"

while getopts "t:h" option; do
    case $option in
        t)
            bin_tag=$OPTARG
            ;;
        h)
            usage
            ;;
        \?)
            echo "Invalid option: -$OPTARG" >&2
            usage
            ;;
    esac
done

# Get the output of uname -a
uname_a=$(uname -a)
# Extract hardware architecture
if [[ $uname_a =~ "x86_64" ]]; then
    deb_arch=amd64
    rpm_arch=x86_64
    rel_arch=amd64
elif [[ $uname_a =~ "aarch64" ]]; then
    deb_arch=arm64
    rpm_arch=aarch64
    rel_arch=arm64
    echo "ARM64 is not supported"
    exit 1
else
    echo "Unsupported hardware architecture"
    exit 1
fi

get_os_info() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        echo $ID
    else
        echo "unknown"
    fi
}

get_os_version() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        echo $VERSION_ID
    else
        echo "unknown"
    fi
}

os_version=$(get_os_version)
case $(get_os_info) in
    ubuntu|debian)
        if [[ "$os_version" == "22.04" ]]; then
            rel_os=ub22
        elif [[ "$os_version" == "12.04" ]]; then
            rel_os=ub12         
        else
            echo "Unsupported Ubuntu version: $os_version"
            exit 1
        fi
        pkg_ext=deb
        ;;
    centos|rhel)
        rel_os=ct8
        pkg_ext=rpm
        echo "CentOS/RHEL is not supported"
        exit 1
        ;;
    openEuler)
        rel_os=oe20
        pkg_ext=rpm
        echo "openEuler is not supported"
        exit 1
        ;;
    *)
        echo "Unsupported OS"
        exit 1
        ;;
esac

make_ocs_bin()
{
    if [ -z $bin_tag ]; then
        bin_tag="pncc"
    fi

    # 如果是build cook版本且当前为Ubuntu22，则调用Ubuntu 12.04容器打包
    if [ "$bin_tag" = "cook" ] && [ "$rel_os" = "ub22" ]; then
        echo "Detected cook build on Ubuntu 22.04, switching to Ubuntu 12.04 container environment."
        make_cook_ocs_bin_in_ub12
        exit $?
    fi

    cd $src_ocs_dir    
    if [ $bin_tag = "cook" ]; then
        git checkout cook
        git pull
    else
        git checkout main
        git pull
    fi

    echo -n "make clean ... "
    make clean 1>/dev/null 2>&1
    echo "done"
    echo -n "make $bin_tag $pkg_type ... "
    make ${bin_tag} 1>make.log 2>&1
    if [ $? -ne 0 ]; then
        echo "failed"
        echo "Please refer to make.log for details"
        exit 1
    fi 
    echo "done"
    cd $OLDPWD
}

make_cook_ocs_bin_in_ub12()
{
    container_id=$(docker ps -a -f name=ubuntu12-dev -q)
    if [ -n "$container_id" ]; then
        if [ "$(docker ps -a -f name=ubuntu12-dev -f status=exited -q)" ]; then
            docker start ubuntu12-dev
        fi
        docker exec -it ubuntu12-dev /bin/bash -c "cd ~/ocs.git/build/bin && ./patch.sh ocs -t cook"
    else
        echo "Error: Container 'ubuntu12-dev' does not exist. Please create it before running this script."
        exit 1
    fi
}

pre_common_patch()
{
    release_dir=$release_root/$pkg_type/$rel_arch
    mkdir -p $release_dir
}

case $pkg_type in
    ocs)
        pre_common_patch
        make_ocs_bin
        if [ ! -d $pacth_tmp_dir ]; then
            mkdir -p $pacth_tmp_dir
        fi
        cp $patch_dir/$bin_tag/control $pacth_tmp_dir/
        sed -i "s/YYYYMMDD/${release_date}/g" $pacth_tmp_dir/control
        package_name=$(grep '^Package:' ${pacth_tmp_dir}/control | awk '{print $2}') 
        release_ver=$(grep '^Version:' ${pacth_tmp_dir}/control | awk '{print $2}')
        tar_file_name=${package_name}-r${release_ver}-${bin_tag}-${rel_os}.tgz

        echo -n "tar -cvf $release_dir/$tar_file_name ... "
        tar cvfz $release_dir/$tar_file_name -C $ocs_bin_dir $ocs_bin_file > /dev/null 2>&1
        if [ $? -ne 0 ]; then
            echo "failed"
            exit 1
        fi
        echo "done"
        ;;
    scp)
        pre_common_patch
        make_ocs_bin
        if [ ! -d $pacth_tmp_dir ]; then
            mkdir -p $pacth_tmp_dir
        fi

        sed -i "s/YYYYMMDD/${release_date}/g" $pacth_tmp_dir/control
        package_name=$(grep '^Package:' ${pacth_tmp_dir}/control | awk '{print $2}') 
        release_ver=$(grep '^Version:' ${pacth_tmp_dir}/control | awk '{print $2}')
        tar_file_name=${package_name}-r${release_ver}-${bin_tag}-${rel_os}.tgz

        echo -n "tar -cvf $release_dir/$tar_file_name ... "
        tar cvfz $release_dir/$tar_file_name -C $ocs_bin_dir $ocs_bin_file > /dev/null 2>&1
        if [ $? -ne 0 ]; then
            echo "failed"
            exit 1
        fi
        echo "done"
        ;;
    ussdgw)
        pre_common_patch
        make_ocs_bin
        if [ ! -d $pacth_tmp_dir ]; then
            mkdir -p $pacth_tmp_dir
        fi
        cp $patch_dir/$bin_tag/control $pacth_tmp_dir/
        sed -i "s/YYYYMMDD/${release_date}/g" $pacth_tmp_dir/control
        package_name=$(grep '^Package:' ${pacth_tmp_dir}/control | awk '{print $2}') 
        release_ver=$(grep '^Version:' ${pacth_tmp_dir}/control | awk '{print $2}')
        tar_file_name=${package_name}-r${release_ver}-${bin_tag}-${rel_os}.tgz

        echo -n "tar -cvf $release_dir/$tar_file_name ... "
        tar cvfz $release_dir/$tar_file_name -C $ocs_bin_dir $ocs_bin_file > /dev/null 2>&1
        if [ $? -ne 0 ]; then
            echo "failed"
            exit 1
        fi
        echo "done"
        ;;
    *)
        usage
        ;;
esac