#!/bin/sh

OLDDIR=$(pwd)

if ! [ -f ./tool/hiperiso_lib.sh ]; then
    if [ -f ${0%Hiperiso2Disk.sh}/tool/hiperiso_lib.sh ]; then
        cd ${0%Hiperiso2Disk.sh}    
    fi
fi

if [ -f ./hiperiso/version ]; then
    curver=$(cat ./hiperiso/version) 
fi

if uname -m | grep -E -q 'aarch64|arm64'; then
    export TOOLDIR=aarch64
elif uname -m | grep -E -q 'x86_64|amd64'; then
    export TOOLDIR=x86_64
elif uname -m | grep -E -q 'mips64'; then
    export TOOLDIR=mips64el
else
    export TOOLDIR=i386
fi
export PATH="$PWD/tool/$TOOLDIR:$PATH"


echo ''
echo '**********************************************'
echo "      Hiperiso: $curver  $TOOLDIR"
echo "      longpanda admin@hiperiso.net"
echo "      https://www.hiperiso.net"
echo '**********************************************'
echo ''


if ! [ -f ./boot/boot.img ]; then
    if [ -d ./grub ]; then
        echo "Don't run Hiperiso2Disk.sh here, please download the released install package, and run the script in it."
    else
        echo "Please run under the correct directory!" 
    fi
    exit 1
fi

for req in ./boot/core.img.xz ./hiperiso/hiperiso.disk.img.xz ./tool/HiperisoWorker.sh; do
    if ! [ -f "$req" ]; then
        echo "Required file missing: $req"
        exit 1
    fi
done

echo "############# Hiperiso2Disk $* [$TOOLDIR] ################" >> ./log.txt
date >> ./log.txt

#decompress tool
echo "decompress tools" >> ./log.txt
cd ./tool/$TOOLDIR

ls *.xz > /dev/null 2>&1
if [ $? -eq 0 ]; then
    [ -f ./xzcat ] && chmod +x ./xzcat

    for file in $(ls *.xz); do
        echo "decompress $file" >> ./log.txt
        xzcat $file > ${file%.xz}
        [ -f ./${file%.xz} ] && chmod +x ./${file%.xz}
        [ -f ./$file ] && rm -f ./$file
    done
fi

#use static linked mkexfatfs for musl-libc environment
if [ -f mkexfatfs_static ]; then
    if ldd --version 2>&1 | grep -qi musl; then
        mv mkexfatfs mkexfatfs_shared
        mv mkexfatfs_static mkexfatfs
    else
        if ./mkexfatfs -V > /dev/null 2>&1; then
            echo "mkexfatfs can not run, check static version" >> ./log.txt
        else
            if ./mkexfatfs_static -V > /dev/null 2>&1; then
                echo "Use static version of mkexfatfs" >> ./log.txt
                mv mkexfatfs mkexfatfs_shared
                mv mkexfatfs_static mkexfatfs
            fi
        fi
    fi
fi

cd ../../
chmod +x -R ./tool/$TOOLDIR


if [ -f /bin/bash ]; then
    /bin/bash ./tool/HiperisoWorker.sh $*
else
    ash ./tool/HiperisoWorker.sh $*
fi

if [ -n "$OLDDIR" ]; then 
    CURDIR=$(pwd)
    if [ "$CURDIR" != "$OLDDIR" ]; then
        cd "$OLDDIR"
    fi
fi
