#!/bin/bash
#Kindle Linux Deploy
#1.0.3
#By NightWind
hdir=/mnt/us/extensions/KLD/fs
v=1.0.3
if [ ! -f /usr/bin/kld ]
then
	mntroot rw
	cp /mnt/us/extensions/KLD/bin/kld /usr/bin
	mntroot ro
fi

deploy(){
		  read -p 'Enter a name of container:' NAME
		  mkdir ${hdir}/$NAME
		  cd ${hdir}/$NAME
		  mkdir rootfs/
		  set_mir
		  wget https://${MIR}/XTxiaoting14332/kindle-linux-deploy/releases/download/fs/${OS}.zip
		  unzip ${OS}.zip
		  rm ${OS}.zip
		  sleep 1
		  echo Done.
		  sleep 0.7
		  echo You can input [kld start ${NAME}] to start ${Linux}
		  sleep 0.5
		  echo Or input [kld remove ${NAME}] to remove it
}

hitokoto(){
ORIGIN_HITOKOTO=$(curl -Ls --connect-timeout 1 --max-time 1 "v1.hitokoto.cn")

HITOKOTO_ONE=$(printf "%s" ${ORIGIN_HITOKOTO} | sed 's@,@\n@g' | grep 'hitokoto.:' | awk -F '"' '{print $4}' | sed 's@^@“@'  | sed 's@$@”@')

HITOKOTO_AUTHOR=$(printf "%s" ${ORIGIN_HITOKOTO} | sed 's@,@\n@g' | grep -v 'commit_from' | grep 'from.:'  | awk -F '"' '{print $4}' | sed '/null,/d' | tr '/n' ' ' | sed 's@$@:@')

echo ${HITOKOTO_AUTHOR}${HITOKOTO_ONE}
}

mount_system() {
  mount -o bind /proc ${rootfs_dir}/proc
  mount -o bind /sys ${rootfs_dir}/sys
  mount -o bind /dev ${rootfs_dir}/dev
  mount -o bind /dev/pts ${rootfs_dir}/dev/pts
}

setup_resolv() {
  rm ${rootfs_dir}/etc/resolv.conf
  cp /etc/resolv.conf ${rootfs_dir}/etc/resolv.conf
}

unmount_system() {
  umount ${rootfs_dir}/dev/pts/ 
  umount ${rootfs_dir}/dev 
  umount ${rootfs_dir}/sys 
  umount ${rootfs_dir}/proc
}

unmount_mount() {
  umount ${rootfs_dir}
}

gl(){
	curl -sL --connect-timeout 1  api.github.com/repos/XTxiaoting14332/kindle-linux-deploy/releases/latest > ver
	sed -i 's/"name":/The latest version:/' ver && sed -i 's/,/ /' ver && sed -i 's/"/ /' ver && sed -i 's/"/ /' ver
	sed -i 's/"tag_name":/ /' ver && sed -i 's/tag_name ://' ver && sed -i 's/[[:space:]]//g' ver && sed -i 's/"//g' ver
	LATEST_VERSION=$(sed -n 28p ver)
	rm ver
}

ud(){
	gl
	if [ "${LATEST_VERSION}" != "${v}" ] && [ "${LATEST_VERSION}" != "" ]
	then
		echo Found new version
		sleep 0.3
		read -p 'Do you want to update KLD?[Y/N]:' udyn
		case $udyn in
			Y | y)
            if [ ! -d /mnt/us/kld_update ]
            then
                mkdir /mnt/us/kld_update
	    fi
			cp /mnt/us/extensions/KLD/bin/ota_update /mnt/us/kld_update
			cd /mnt/us/kld_update
			./ota_update
			;;
		*)
			echo	
			;;
		esac
fi
}
mk_conf(){
	echo #kld config > boot.config
	echo #GUN/Linux >> boot.config
	echo #${LINUX} >> boot.config
	echo rootfs_dir=${hdir}/${NAME}/rootfs >> boot.config
	echo motd=GUN/Linux_${LINUX} >> boot.config
	echo system_name=${LINUX} >> boot.config
	echo boot=${BOOT} >> boot.config
	echo GUI=${G} >> boot.config
}

if [ ! -d ${hdir} ]
then
	mkdir $hdir
fi

usage(){
	echo Usage
	echo kld [options]
	echo
	echo options:
	echo "-h/help ---Show this message"
	echo "-d/deploy ---Deploy a Linux"
	echo "-s/start [container_name]  ---Launch Linux" 
	echo "-l/list ---Get a list of your containers"
	echo "-r/remove [container_name] ---Remove container"
	echo "-g/gui [container_name] ---Start GUI"
	echo "-G/fgui [container_name] ---Start GUI quickly.[Much faster than -g]"
	echo "-v/version"
}

set_mir(){
	echo Select download mirror
	echo [1]github.com
	echo [2]hub.fastgit.xyz
	  read -p 'select:' SELECT_MIRROR
		case $SELECT_MIRROR in
		 1)
		  MIR=github.com
		  ;;
		 2)
		  MIR=kgithub.com
		  ;;
		 *)
		  echo Error:unknown option.Set mirror as [github.com]
		  MIR=github.com
		  ;;
		 esac

}
ud
if [ "$1" = -h ] || [ "$1" = help ]
then
	usage
elif [ "$1" = -d ] || [ "$1" = deploy ]
then
	echo Select a Linux system
	echo
	echo [1]Alpine-3.15[nogui]
	echo [2]Ubuntu14.04[Have many error]
	echo [3]Alpine-edge with GUI [xfce4]
	read -p 'select:' s
case $s in
	1)
	 echo Download [Alpine-3.15]
	 sleep 0.5
	 read -p 'It needs 1GB memories.Do you want to countinue?[Y/N]' yn
		case $yn in
		 y | Y)
		  OS=alpine
                  G=false
                  BOOT=ash
                  LINUX=alpine-3.15
                  deploy
                  mk_conf
		  ;;
		n | N)
		  echo Stop
		  exit 1
		  ;;
		  esac
		;;
	 2)
	 echo Download [Ubuntu14.04]
	 sleep 0.5
	 read -p 'It needs 1GB memories.Do you want to countinue?[Y/N]' yn
		case $yn in
		 y | Y)
		  OS=ubuntu
                  G=false
                  BOOT=bash
                  LINUX=Ubuntu14.04
                  deploy
                  mk_conf
		  ;;
		n | N)
		  echo Stop
		  exit 1
		  ;;
		  esac
		  ;;
	3)
	 echo Download [Alpine-edge]
	 sleep 0.5
	 read -p 'It needs 2GB memories.Do you want to countinue?[Y/N]' yn
		case $yn in
		 y | Y)
		  OS=alpine_xfce4
                  G=true
                  BOOT=ash
                  LINUX=alpine-edge
                  deploy
                  mk_conf
		  ;;
		n | N)
		  echo Stop
		  exit 1
		  ;;
		  esac
                  ;;
esac
elif [ "$1" = start ] || [ "$1" = -s ]
then
	if [ -d ${hdir}/${2} ]
	  then
		cd ${hdir}/${2}
		source ./boot.config
		mfs(){
		echo mounting...
		mount -o loop *.ext3 ${rootfs_dir}
		mount_system
		setup_resolv
		sleep 1
		}
		if [ ! -d ${hdir}/${2}/rootfs/home/ ]
		then
			mfs
		fi	
		hitokoto
		echo ${motd}
		sleep 2
		echo If you want to exit,please input [exit] to do that.
		if [ ${GUI} = true ]
		then
			if [ ! -f /mnt/base-us/swapfile ]
			then
				echo [X]Missing SWAP.
				sleep 1
				echo It needs 256M
				sleep 0.2
				echo -e "[>]Creating..."
				dd if=/dev/zero of=/mnt/base-us/swapfile bs=1M count=256
				mkswap /mnt/base-us/swapfile
			fi
			swapon /mnt/base-us/swapfile
			echo If you want to start GUI.Please type [kld-startgui.sh]
		fi
		chroot ${rootfs_dir} $boot
		unmount_system
		unmount_mount
			if [ ${GUI} = true ]
			then
				swapoff /mnt/base-us/swapfile
			fi
		echo Unmounted [${2}]
	else
		echo KLD:[E]${2}:Not found
	fi	
elif [ "$1" = list ] || [ "$1" = -l ]
then
	ls ${hdir} > /mnt/us/extensions/KLD/kld.list
	cat /mnt/us/extensions/KLD/kld.list
	rm /mnt/us/extensions/KLD/kld.list
elif [ "$1" = remove ] || [ "$1" = -r ]
then
	if [ -d ${hdir}/${2} ]
		then
		  read -p 'Do you want to remove it?[Y/N]' ryn
		  case $ryn in
			Y | y)
			hitokoto
			rm -rf ${hdir}/${2}/
			echo Removed [${2}]
			;;
			n | N)
			echo Stop
			exit 1
			;;
			*)
			echo KLD:[E]Unknown option.
			;;
		  esac
		else
		  echo KLD:[E]${2}:Not found
	fi
elif [ "$1" = -v ] || [ "$1" = version ]
	then
		echo 'Kindle Linux Delpoy[Beta] 1.0.2'
		echo 'By XTxiaoting14332'
		echo 'date:2022-06-11'
		echo 'If it has some bugs,please send email to xtxiaoting14332@gmail.com'
elif [ "$1" = gui ] || [ "$1" = "-g" ]
	then
		if [ -d ${hdir}/${2} ] && [ "$2" != " " ]
			then
				if [ ! -f /mnt/base-us/swapfile ]
				then
					echo Missing SWAP!Create now.
					dd if=/dev/zero of=/mnt/base-us/swapfile bs=1M count=256
					mkswap /mnt/base-us/swapfile
				fi
				if [ ! -d ${hdir}/${2}/rootfs/home ]
					then
                                        cd ${hdir}/$2 
					source ./boot.config
					echo mounting...
				        mount -o loop *.ext3 ${rootfs_dir}
		                        mount_system
		                        setup_resolv
				fi
			cd ${hdir}/${2}
			sleep 0.6
			echo -e "##########NOTICE##########"
			echo -e "#Please WAIT FOR A MINUTE until the wallpaper is displayed."
			echo -e "##########################"
			sleep 3
			source ./boot.config
			hitokoto
			sleep 0.3
			echo ${motd}
			swapon /mnt/base-us/swapfile	
			sysctl vm.swappiness=100
			chroot rootfs/ ${boot} -c kld-startgui.sh 
			swapoff /mnt/base-us/swapfile
			else
				echo KLD:${2}:Not found
			fi		
elif [ "$1" = -G ] || [ "$1" = fgui ]
then
	if [ -d ${hdir}/$2 ] && [ "$2" != "" ]
	then
		if [ ! -f /etc/upstart/kld_gui.conf ]
		then
		mntroot rw
		cp /mnt/us/extensions/KLD/conf/kld_gui.conf /etc/upstart/
		mntroot rw
		fi
	cd ${hdir}/${2}
	echo -e "##########NOTICE#########"
	echo -e "#Please WAIT FOR A MINUTE until the wallpaper is displayed."
	echo -e "#########################"
	echo CONTAINER=${2} > /mnt/us/extensions/KLD/conf/launch.config
	sleep 3.5
	start kld_gui
	else
	echo KLD:${2}:Not found.
	fi
elif [ "$1" = update ]
then
	ud
else
	usage
fi
