#!/bin/bash

#check tools
TOOLS=( \
    dd                  \
    losetup             \
    parted              \
    lsblk               \
    mkfs.vfat           \
    mkfs.ext4           \
    debootstrap         \
    gzip                \
    cpio                \
    sync                \
    chroot              \
    apt-get             \
    dpkg-reconfigure    \
    sed                 \
    locale-gen          \
    update-locale       \
    qemu-arm-static     \
)

STOP=0
for (( i = 0; i < ${#TOOLS[@]}; i++ )); do
    TOOL=`which ${TOOLS[$i]}`
    if [ -z ${TOOL} ]; then
        echo -e "${TOOLS[$i]} ... \e[91mMISSING\e[0m"
        STOP=1
    else
        echo -e "${TOOLS[$i]} ... \e[92mINSTALLED\e[0m"
    fi
done

if [ $STOP -eq 1 ]; then
    echo "stop"
    exit
fi

export LANG=en_US.UTF-8
export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"
export LANGUAGE="en_US.UTF-8"

petadir=.
image=te0726-debian.img
# size=1792
size=7168

dd if=/dev/zero of=$image bs=1M count=$size status=progress

device=`losetup -f`
echo "++ Setting up device: $device"
losetup $device $image

boot_dir=/tmp/BOOT
root_dir=/tmp/ROOT


#mirror=http://ftp.uni-stuttgart.de/debian
mirror=http://ftp.cz.debian.org/debian/
# distro=jessie
distro=stretch
arch=armhf

passwd=root
timezone=Europe/Berlin

# Create partitions

parted -s $device mklabel msdos
parted -s $device mkpart primary fat32 4MB 256MB
parted -s $device mkpart primary ext4 256MB 100%

# get device names from sorted list (-x NAME) !!!!!
boot_dev=/dev/`lsblk -lno NAME -x NAME $device | sed '2!d'`
root_dev=/dev/`lsblk -lno NAME -x NAME $device | sed '3!d'`

# Create file systems

mkfs.vfat -v $boot_dev
mkfs.ext4 -F -j $root_dev

# Mount file system

mkdir -p $boot_dir $root_dir

mount $boot_dev $boot_dir
mount $root_dev $root_dir

# Copy files to the boot file system

cp $petadir/images/linux/image.ub $boot_dir

# Install Debian base system to the root file system

debootstrap --foreign --arch $arch $distro $root_dir $mirror

# Add missing configuration files and packages

cp /etc/resolv.conf $root_dir/etc/
cp /usr/bin/qemu-arm-static $root_dir/usr/bin/

mkdir -p $root_dir/usr/local/bin
mkdir -p $root_dir/usr/local/sbin

mkdir -p $root_dir/lib/modules

# TE audio for TE0726
# cp -av $petadir/build/tmp/sysroots/plnx_arm/lib/modules/4.9.0-xilinx-v2017.1/ $root_dir/lib/modules

# get Xilinx modules
startdir=`pwd`
cd $petadir/build/tmp/deploy/images/plnx-zynq7/
# gzip -dk --force petalinux-user-image-plnx_zynq7.cpio.gz
mkdir tmp
cd tmp
cpio -id < ../petalinux-user-image-plnx-zynq7.cpio
cp -av lib/modules/4.14.0-xilinx-v2018.2/ $root_dir/lib/modules
sync
cd ..
rm -rf tmp
# rm -f petalinux-user-image-plnx_zynq7.cpio
cd $startdir

X11DIR=$root_dir/usr/share/X11/xorg.conf.d
mkdir -p $X11DIR
cat << EOF_FBDEV > $X11DIR/99-fbdev.conf
Section "Device"
  Identifier "myfb"
  Driver "fbdev"
  Option "fbdev" "/dev/fb0"
EndSection
EOF_FBDEV
echo te-audio-codec >> $root_dir/etc/modules


chroot $root_dir <<- EOF_CHROOT
export LANG=C
export LC_ALL=C

/debootstrap/debootstrap --second-stage

cat <<- EOF_CAT > etc/apt/sources.list
deb $mirror $distro main contrib non-free
deb-src $mirror $distro main contrib non-free
deb $mirror $distro-updates main contrib non-free
deb-src $mirror $distro-updates main contrib non-free
deb http://security.debian.org/debian-security $distro/updates main contrib non-free
deb-src http://security.debian.org/debian-security $distro/updates main contrib non-free
EOF_CAT

cat <<- EOF_CAT > etc/apt/apt.conf.d/99norecommends
APT::Install-Recommends "0";
APT::Install-Suggests "0";
EOF_CAT

cat <<- EOF_CAT > etc/fstab
# /etc/fstab: static file system information.
# <file system> <mount point>   <type>  <options>           <dump>  <pass>
/dev/mmcblk0p2  /               ext4    errors=remount-ro   0       1
/dev/mmcblk0p1  /boot           vfat    defaults            0       2
EOF_CAT

cat <<- EOF_CAT >> etc/securetty

# Serial Console(s) for Xilinx Zynq-7000
ttyPS0
ttyPS1
EOF_CAT

echo zynq > etc/hostname

apt-get update
apt-get -y upgrade

apt-get -y install locales

sed -i "/^# en_US.UTF-8 UTF-8$/s/^# //" etc/locale.gen
locale-gen
update-locale LANG=en_US.UTF-8

echo $timezone > etc/timezone
dpkg-reconfigure --frontend=noninteractive tzdata

apt-get -y install openssh-server ca-certificates ntp ntpdate fake-hwclock \
  usbutils psmisc lsof parted curl wget vim ifplugd \
  python3 python3-numpy build-essential libfftw3-dev python3-scipy \
  xfonts-base tightvncserver xfce4-panel xfce4-session xfwm4 xfdesktop4 \
  xfce4-terminal thunar gnome-icon-theme \
  tcpdump ethtool net-tools picocom joe mc usbutils \
  xserver-xorg xinit xserver-xorg-video-fbdev \
  nodejs mousepad libcanberra-gtk-module
#   mono-devel nodejs

# enable root login via ssh
sed -i 's/^#PermitRootLogin.*/&\nPermitRootLogin yes/' etc/ssh/sshd_config

touch etc/udev/rules.d/75-persistent-net-generator.rules

touch etc/network/interfaces.d
cat <<- EOF_CAT > etc/network/interfaces.d/eth0
iface eth0 inet dhcp
EOF_CAT

cat <<- EOF_CAT > etc/default/ifplugd
INTERFACES="eth0"
HOTPLUG_INTERFACES=""
ARGS="-q -f -u0 -d10 -w -I"
SUSPEND_ACTION="stop"
EOF_CAT

apt-get clean

echo root:$passwd | chpasswd

service ntp stop

history -c
EOF_CHROOT

rm $root_dir/etc/resolv.conf
rm $root_dir/usr/bin/qemu-arm-static

sync

# Unmount file systems
umount -f $boot_dir $root_dir

# rmdir $boot_dir $root_dir
rm -rf $boot_dir $root_dir

losetup -d $device

sync

