#! /bin/bash

# copyright Thomas Lange 2001-2016, lange@debian.org

error=0; trap 'error=$(($?>$error?$?:$error))' ERR # save maximum error code

if [ "$FAI_ACTION" = "dirinstall" ] || [ "$do_init_tasks" -eq 0 ] ; then
  :
else
  # check if mdadm has been forgotten
  if grep -q active /proc/mdstat 2>/dev/null; then
    if [ ! -d "$target/etc/mdadm" ]; then
	echo ERROR: Found Software RAID, but the mdadm package was not installed
	error=1
    fi
  fi

  usedm=$(dmsetup ls 2>/dev/null | grep -cEv '^live-rw|^live-base|^No devices found')
  if [ "$usedm" -ne 0 ]; then
    if [ ! -d "$target/etc/lvm" ]; then
	echo ERROR: Found lvm devices, but the lvm2 package was not installed
	error=1
    fi
  fi
fi

# remove backup files from cfengine, but only if cfengine is installed
if [ -x /usr/sbin/cfagent ] || [ -x "$target/usr/sbin/cfagent" ] ; then
    dirs="root etc var"
    for path in $dirs; do
        find "$target/$path" -print0 -maxdepth 20 -name \*.cfedited -o -name \*.cfsaved | xargs -r rm
    done
fi

[ "$FAI_DEBMIRROR" ] &&
  ainsl /etc/fstab "#$FAI_DEBMIRROR $MNTPOINT nfs ro 0 0"

# set bios clock
if [ "$do_init_tasks" -eq 1 ] ; then
    case "$UTC" in
       no|"") hwopt="--localtime" ;;
       yes)   hwopt="--utc"       ;;
    esac
    hwclock $hwopt --systohc || true
fi

# Make sure everything is configured properly
if ifclass DEBIAN ; then
        $ROOTCMD apt-get -f install
fi

if [ "$FAI_ACTION" = "install" ]; then
	lskernels=$(find "$target/boot/" -maxdepth 1 -name "vmlinu*")
	if [ ! -f "${lskernels%% *}" ]; then
		echo "ERROR: No kernel was installed. Have a look at shell.log" >&2
		error=1
	fi
fi

# copy sources.list
fcopy -iSM /etc/apt/sources.list


setrel() {

    # if release is not set, try to determine it

    if [ -n "$release" ]; then
	return
    fi
    if [ ! -f "$target/etc/os-release" ]; then
	return
    fi

    dists="jessie stretch buster bullseye bionic xenial trusty"
    for d in $dists; do
	if grep -iq "$d" "$target/etc/os-release"; then
	    release="$d"
	    break
	fi
    done
}

# if installation was done from CD, replace useless sources.list
setrel
if [ -f "$target/etc/apt/sources.list" ] && [ -n "$release" ]; then
    grep -q 'file generated by fai-cd' "$target/etc/apt/sources.list" && cat <<EOF > "$target/etc/apt/sources.list"
deb $apt_cdn/debian $release main contrib non-free
deb $apt_cdn/debian-security ${release}-security main contrib non-free
#deb [trusted=yes] http://fai-project.org/download $release koeln
EOF
    # if the package fai-server was installed, enable the project's repository
    if [ -f "$target/var/lib/dpkg/info/fai-server.list" ]; then
	sed -i -e '/fai-project.org/s/^#//' "$target/etc/apt/sources.list"
    fi
fi

# for ARM architecture, we may need the kernel and initrd to boot or flash the device
if ifclass ARM64; then
    cp -pv "$target/boot/vmlinuz*" "$target/boot/initrd*" "$FAI_RUNDIR"
fi

exit $error
