#!/bin/bash

# Check ran as root
if ! [ "$(id -u)" = "0" ]; then
    echo "Run this builder must be root or with sudo"
    exit 1
fi

USAGE=$(cat <<EOF
Live CD builder
Usage: live-build-astra [OPTIONS]

OPTIONS
     -h|--help display this help and exit
     -d <distribution> create liveCD of given distribution
     -r <url> URL for distribution repo
     -i <filename> ISO image(s) to use as a source of packages and other stuff
(without -d, -r and -i options programm will be try to build image for current distribution with first repo from sources.list)

Example-1: live-build-astra
Example-2: live-build-astra -d smolensk -i "/usr/local/tmp/smolensk-current.iso;/usr/local/tmp/devel-smolensk-current.iso"
Example-3: live-build-astra -d orel -r ftp://192.168.0.254/repo
EOF
)

usage () {
    echo "${USAGE}"
}

# Apply astra-changes (apt prevent this step in install/postinst/postrm)
rsync -a /usr/share/live-build-astra/build/ /usr/lib/live/build/
rsync -a /usr/share/live-build-astra/functions/ /usr/share/live/build/functions/

# Distribution and repo define
DISTRIB=""; REPO_1=""; REPO_2=""; IMAGE_LIST=""; WMARK=0
CLBR="/tmp/live-build-astra/sample_config"
LB_APPEND="boot=live net.ifnames=0 noautologin nox11autologin components username=astra-live locales=ru_RU.UTF-8,en_US.UTF-8 keyboard-layouts=us,ru keyboard-variants=, keyboard-options=grp:ctrl_shift_toggle,grp_led:scroll"
if [ -f "/etc/os-release" ]; then
  DISTRIB=`grep VARIANT_ID /etc/os-release | awk -F \= '{print $2}'`
fi
repo_line=`grep ^deb /etc/apt/sources.list | sed -n 1p`
REPO_1=`echo $repo_line | awk '{print $2}'`
if [ ${#DISTRIB} -eq 0 ]; then
  DISTRIB=`echo $repo_line | awk '{print $3}'`
fi
if [ $DISTRIB = "smolensk" ]; then
  repo_line=`grep ^deb /etc/apt/sources.list | sed -n 2p`
  REPO_2=`echo $repo_line | awk '{print $2}'`
fi

while getopts "hd:r:i:-:" opt
do
  case $opt in
    h)
        usage
        exit 0
        ;;
    d)
        DISTRIB="$OPTARG"
        ;;
    r)
        REPO_1="$OPTARG"
	;;
    i)
        IMAGE_LIST="$OPTARG"
        ;;
    -)
	case $OPTARG in
	  help) usage; exit 0;;
	  *) echo "Wrong opts.Try again."; exit 1;;
	esac
  esac
done

pushd /usr/share/debootstrap/scripts
ln -nfs sid ${DISTRIB}
popd

safe_exit() {
  killall webfsd
  apt-get remove --purge -y webfs
  umount -l /mnt/rand /mnt/sur_rand
}

# Mount iso images as local repo
safe_exit
if [ -d $CLBR ]; then rm -rf $CLBR; fi
mkdir -p /mnt/rand /mnt/sur_rand $CLBR
tar -xjvf /usr/share/live-build-astra/astra_templates.tar.bz2 -C $CLBR 
if [ ${#IMAGE_LIST} -ne 0 ]; then
  IMAGE_1=`echo $IMAGE_LIST | awk -F \; '{print $1}'`
  IMAGE_2=`echo $IMAGE_LIST | awk -F \; '{print $2}'`
  tool_pkg=`ls -l $CLBR/packages.binary | grep web | awk '{print $NF}'`
  WMARK=1; apt-get install -y "$CLBR/packages.binary/$tool_pkg"
  /usr/bin/webfsd -4 -i 127.0.0.2 -p 80 -r /mnt/rand/
  /usr/bin/webfsd -4 -i 127.0.0.2 -p 81 -r /mnt/sur_rand/
  if [ -f "/var/run/webfs/webfsd.pid" ]; then kill `cat /var/run/webfs/webfsd.pid`; fi
  mount $IMAGE_1 /mnt/rand; REPO_1="http://127.0.0.2/"
  if [ ${#IMAGE_2} -ne 0 ]; then mount $IMAGE_2 /mnt/sur_rand; REPO_2="http://127.0.0.2:81"; fi
fi

# Build processing
if [ ${#DISTRIB} -eq 0 -o ${#REPO_1} -eq 0 ];then
  echo "Invalid distribution name or repo name. Try again."
  exit 1
fi

if [ -d "/opt/workload" ]; then
  rm -rf /opt/workload
fi
mkdir -p /opt/workload /opt/live_CD
pushd /opt/workload
if [ ${#REPO_2} -eq 0 ]; then
  CONF_OPTS="--verbose --distribution ${DISTRIB} --parent-mirror-bootstrap ${REPO_1} --parent-mirror-chroot-security ${REPO_1} --parent-mirror-binary ${REPO_1} --security false --updates false --linux-flavours generic --initramfs live-boot --firmware-chroot false --firmware-binary false --archive-areas main --apt-source-archives false --apt-indices false --loadlin false --win32-loader false --debian-installer false --debian-installer-gui false --zsync false"
else
  CONF_OPTS="--verbose --distribution ${DISTRIB} --parent-mirror-bootstrap ${REPO_1} --parent-mirror-chroot-security ${REPO_1} --parent-mirror-binary ${REPO_1} --mirror-bootstrap ${REPO_2} --mirror-chroot-security ${REPO_2} --mirror-binary ${REPO_2} --security false --updates false --linux-flavours generic --initramfs live-boot --firmware-chroot false --firmware-binary false --archive-areas main --apt-source-archives false --apt-indices false --loadlin false --win32-loader false --debian-installer false --debian-installer-gui false --zsync false"
fi
lb config ${CONF_OPTS}
sed -e "s/APT_OPTIONS=\"--yes\"/APT_OPTIONS=\"--yes -oAPT::Get::Install-Suggests=false\"/" -i config/common
sed -e "s/^LB_BOOTAPPEND_LIVE=\"boot=live components quiet splash\"/LB_BOOTAPPEND_LIVE=\"${LB_APPEND}\"/" -i config/binary
sed -e "s/^Archive-Areas: main/Archive-Areas: main contrib non-free/" -i config/build

rsync -avu8 $CLBR/hooks/ config/hooks/
rsync -avu8 $CLBR/bootloaders config/
rsync -avu8 $CLBR/includes.chroot/ config/includes.chroot/
rsync -avu8 $CLBR/includes.binary/ config/includes.binary/
rsync -avu8 $CLBR/includes.source/ config/includes.source/
rsync -avu8 $CLBR/includes.bootstrap/ config/includes.bootstrap/
rsync -avu8 $CLBR/package-lists/ config/package-lists/
rsync -avu8 $CLBR/packages.binary/ config/packages.binary/

lb build | tee build.log

# Finalyze
if [ $? -ne 0 ]; then
  if [ $WMARK -ne 0 ]; then
    safe_exit
  fi
  rm -rf $CLBR
  echo "Build was failed. See build.log for details."
  exit 1
fi

find . -maxdepth 1 -name "*.iso" -exec mv -v {} /opt/live_CD/ \;
popd
pushd /opt/live_CD
rm -rf /opt/workload $CLBR
  if [ $WMARK -ne 0 ]; then
    safe_exit
  fi
ls -l
