#!/bin/bash

HOST=$(cat /etc/hostname)

# update packages
apt-get -y update

# indentifying OS name and version
apt-get -y install lsb-release less
OS_VERSION=$(lsb_release -sr)
OS_ID=$(lsb_release -si)

# use jessie and supress libc6 upgrade interractive questions on debian
if [[ ${OS_ID} = "Debian" ]]; then
#    sed -i 's/wheezy/jessie/g' /etc/apt/sources.list
    echo "libc6 libraries/restart-without-asking boolean true" | debconf-set-selections
    echo "libc6:armhf libraries/restart-without-asking boolean true" | debconf-set-selections
    # disable pi interractive config
    if [ -e /etc/profile.d/raspi-config.sh ]; then
        rm -f /etc/profile.d/raspi-config.sh
        sed -i /etc/inittab \
            -e "s/^#\(.*\)#\s*RPICFG_TO_ENABLE\s*/\1/" \
            -e "/#\s*RPICFG_TO_DISABLE/d"
        telinit q
    fi
fi
apt-get -y update
apt-get -yf install
apt-get -y install python-dev

# changing root password, so finish setup could be done through ssh under root
echo "root:syncloud" | chpasswd

#All boards should allow root ssh login for initial setup
sed -i "s/^PermitRootLogin .*/PermitRootLogin yes/g" /etc/ssh/sshd_config

# change ssh port to 22 for all cubieboards
if [[ ${HOST} = "Cubian" ]]; then
    sed -i "s/Port 36000/Port 22/g" /etc/ssh/sshd_config
fi

# https://github.com/syncloud/image/issues/39
if dpkg -l | grep python-requests; then
    apt-get -y remove python-requests
fi

# delete unnecessary files
if [[ ${HOST} == "raspberrypi" ]]; then

  rm -rf python_games
  apt-get purge -y x11-common midori lxde python3 python3-minimal
  apt-get purge -y lxde-common lxde-icon-theme omxplayer
  apt-get purge -y wolfram-engine

  apt-get autoremove --purge -y
  apt-get update -y

  #Do not upgrade for now as lsb_release -si starts returning non "Debian" value
  #which brakes pi owncloud installation, need to check
  #apt-get upgrade -y

  rm -Rf /etc/X11
  rm -Rf /etc/wpa_supplicant
  rm -Rf /usr/share/icons
  rm -Rf /home/pi/Desktop
  rm -f /home/pi/ocr_pi.png
fi

rm -rf /var/cache/apt/archives/*.deb
rm -rf /opt/Wolfram