#!/usr/bin/bash

if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

A=($#)

if [ "$A" == "0" ];then
    echo "This program should be called only from systemd"
    echo "Cowardly refusing to run ..."
    echo
    echo "Type -h,--help for additional info."
    exit 1
fi


case $1 in
    --help|-h)
        echo "Initial system setup from values obtained via firstboot."
        echo
        echo "Usage: $0 {-f}"
        echo
        echo "This program should be called only from systemd"
        echo "Cowardly refusing to run ..."
        exit 1
        ;;
    -f)
       force=1
       ;;
    *)
     echo "BAD arguments, type -h or --help for additional info."
     echo
     echo "This program should be called only from systemd"
     echo "Cowardly refusing to run ..."
     exit 1
     ;;
esac

if [ $force -ne "1" ];then
    echo "Wrong argument, see -h(--help) for additional info."
    echo
    echo "This program should be called only from systemd"
    echo "Cowardly refusing to run ..."
    exit 1
fi

# Config file written at installation time
cfgfile="/etc/sysconfig/locmap-firstboot"
logfile='/var/log/locmap.log'
script='/usr/bin/locmap --configure all'


if [ -e $cfgfile ];then
     lines=$(<$cfgfile)
     # Check ' LOCMAP_FIRSTBOOT_START ' value, is needed for locmap-firstboot systemd service.
     for line in $lines;do
         if [ $line == "LOCMAP_FIRSTBOOT_START=no" ];then
            # Exit safely..
            echo "[Exit] Running only at firstboot time."
            exit 0
         fi
     done
     sed -i -e 's/LOCMAP_FIRSTBOOT_START=yes/LOCMAP_FIRSTBOOT_START=no/g' $cfgfile
fi

# run locmap with plugin activated by cern-anaconda-addon
$script

exit 0
