#!/usr/bin/env bash

SELF="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
. $SELF/config

set -e

if [[ -z $HOSTNAME_OVERRIDE ]]; then
    IP=$(ip addr show | fgrep inet | fgrep $IP_PREFIX | fgrep -v secondary | sed 's|^.*inet \([^/]*\)/.*|\1|')
    FULLHOST=$(nslookup $IP | fgrep name | sed -r 's/^.*name.*=\s+(.*)\..*$/\1/')
    HOSTNAME=$(echo $FULLHOST | sed 's/\..*//')
else
    HOSTNAME=$HOSTNAME_OVERRIDE
fi

if ! [[ $HOSTNAME = $(hostname) ]]; then
    echo "Changing hostname to $HOSTNAME" >&2
    echo $HOSTNAME > /etc/hostname
fi

export PERL5LIB=$SELF:$PERL5LIB
if [[ $1 = "install" ]]; then
    ln -sf /usr/share/zoneinfo/Europe/Prague /etc/localtime
    cat >> /etc/locale.gen <<EOF
cs_CZ.UTF-8 UTF-8
sk_SK.UTF-8 UTF-8  
en_US.UTF-8 UTF-8  
EOF
    locale-gen
    echo 'LANG=en_US.UTF-8' > /etc/locale.conf

    systemctl enable dhcpcd.service
    systemctl enable sshd.service

    mkdir -p /root/.ssh
    echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCyTqSTbfhzJUlAV3/WQPefOz/nX0xfGgBbb9mMxwXNm3OKpTLaSJZZ78aUvucCqbiWhWQKCKlUqMsaWCqHLIL5kFDgDRcfGhF8ERCjIG7TCPs1zPPoFVL8hvGeMmWsHgvm8pKjPFCp/NxjTDx3RmLzVyP1z8rLwD3X1xC2bRSETuRwwOIKLEJhzNSQ1EchTNRTH0CuMqVZHdQLVDP6Tdqo7WV61znELRW5ZPw7BPJU216+He7AziIGcLbv06JbuFyFsoZ+8dmH20rs/CwOnicFH/P44yOZmB+JWVzBosKkG8JliM/nzaru7aPPQe/7XIsOQ5iymm31WAK112htIy3N xstill@xstill-lenovo" >> /root/.ssh/authorized_keys

    $SELF/pdsconfig $HOSTNAME
    pacman -Syyuu --noconfirm
fi

pacman-key --populate
$SELF/pdsusers
$SELF/pdspkgs $HOSTNAME
$SELF/pdsconfig $HOSTNAME
systemctl daemon-reload
$SELF/pdssrv $HOSTNAME

echo "Regenerating grub..." >&2
grub-mkconfig -o /boot/grub/grub.cfg

if [[ $1 = "install" ]] && test -b $2; then
    grub-install --target=i386-pc $2
fi
