#!/bin/sh
set -x
# Hack to get around sysfs oddities
# sysfs is mounted but reflects the init namespace
# We also need sysfs to reflect the container namespace

# To do the above, crate a new mount point
mkdir $FREIGHT_CONTAINERFS/csys

# Then we need to modify the network-function script to use this location
sed -i -e"s/\/sys\//\/csys\//g" $FREIGHT_CONTAINERFS/etc/sysconfig/network-scripts/network-functions
sed -i -e"s/\/sys\//\/csys\//g" $FREIGHT_CONTAINERFS/etc/sysconfig/network-scripts/ifup-eth

# We also need to modify the script to remove the @dev garbage which is meaningless in a container
sed -i -e"s/\(.*ip -o link |.*\)/\1 | sed -e\"s\/@.*\/\/\"/" $FREIGHT_CONTAINERFS/etc/sysconfig/network-scripts/network-functions

cat >> $FREIGHT_CONTAINERFS/var/www/html/index.html << EOF
<!DOCTYPE html>
<html>
<head>
<title>You're first container!</title>
</head>
<body>

<h1>If you can read this, your container is running!</h1>
<p>You can now go on and start making your own containers.</p>

</body>
</html>

EOF

# Then touch /etc/sysconfig/network so the network service will function properly
touch $FREIGHT_CONTAINERFS/etc/sysconfig/network

# This is a script we cat out to run in the $FREIGHT_CONTAINERFS as a chroot
cat >> $FREIGHT_CONTAINERFS/post_install << EOF
#!/bin/sh

setfiles /etc/selinux/targeted/contexts/files/file_contexts /

#We need to setup the root password
echo redhat | passwd -f --stdin root

#Then we need to enable the web server
systemctl enable httpd

#And General networking
systemctl enable network

#Hack to setup fstab to mount contaienr sysfs properly
cp /etc/filesystems /etc/fstab
sed -i -e"1i \nodev	\/csys	sysfs	defaults	0 0" -e"1,$ d" /etc/fstab

#The root directory needs to be set readable/executable for all users
chmod 755 /

EOF

# make the chroot script executable
chmod 755 $FREIGHT_CONTAINERFS/post_install

# Go to the chroot dir
cd $FREIGHT_CONTAINERFS

# Run it in a a chroot jail
chroot . /post_install

# And remove it for clean up
rm -f $FREIGHT_CONTAINERFS/post_install

# Btrfs has a problem with sending snapshots that have data in pagecache
# Make sure everything is synced before taking the snapshot
sync $FREIGHT_CONTAINERFS/var/www/html/index.html




