#!/bin/bash

# This script install the mender client on electrosense-based sensors
# Authors: Yago Lizarribar <yago.lizarribar@imdea.org>
# Year: 2022

set -e

# Variables
MENDER_DIR="/data/mender"
MENDER_RUN="/var/lib/mender"
DEVICE_TYPE="unknown"
MENDER_CONF_DIR="/etc/mender"
MENDER_CONF_FILE="/etc/mender/mender.conf"
MENDER_CONN_CONF_FILE="/etc/mender/mender-connect.conf"
MENDER_IDENTITY_DIR="/usr/share/mender/identity"
MENDER_IDENTITY_SCR="/usr/share/mender/identity/mender-device-identity"

# Updating
install_dependencies() {
    # Remove unattended upgrades
    sudo apt purge unattended-upgrades
    
    # Get predependencies
    sudo apt-get update
    sudo apt-get install -q -y apt-transport-https ca-certificates curl gnupg-agent software-properties-common
}

# Mender setup functions
mender_setup() {
    # Mender directory creation
    if [ ! -d "$MENDER_DIR" ] 
    then
        echo "Creating directory in $MENDER_DIR"
        sudo mkdir $MENDER_DIR
    else
        echo "Directory already exists"
    fi
    
    # Create symlink to mender runtime directory
    if [ -L "$MENDER_RUN" ]
    then
        echo "Symlink already exists"
    else
        echo "Creating symlink in $MENDER_RUN to $MENDER_DIR"
        sudo ln -sf $MENDER_DIR $MENDER_RUN
    fi
}

# Repository setup
repo_setup() {

    # Add repo key
    curl -fLsS https://downloads.mender.io/repos/debian/gpg | sudo apt-key add -
    
    # Remove installations from apt (if any)
    sudo sed -i.bak -e "\,https://downloads.mender.io/repos/debian,d" /etc/apt/sources.list
    
    # Add newer repo
    echo "deb [arch=armhf] https://downloads.mender.io/repos/debian stable main" | sudo tee /etc/apt/sources.list.d/mender.list > /dev/null
}

# Check device type
device_type_check() {
    MODEL_TMP_STRING=$(grep Model /proc/cpuinfo)
    if [ -z "$MODEL_TMP_STRING" ]
    then
        echo "Could not get model info..."
    else
        NUMBER=$(echo "$MODEL_TMP_STRING" | awk '{print $5}')
        DEVICE_TYPE="raspberrypi$NUMBER"
    fi
    
    echo "device_type=$DEVICE_TYPE" | sudo tee /data/mender/device_type > /dev/null
}

# Mender configuration
mender_conf() {
    
    # Mender directory creation
    if [ ! -d "$MENDER_CONF_DIR" ] 
    then
        echo "Creating directory in $MENDER_CONF_DIR"
        sudo mkdir -p $MENDER_CONF_DIR
    else
        echo "Directory already exists"
    fi
    
    # Mender conf file
    {
echo -e '{
    "HttpsClient": {},
    "Security": {},
    "DeviceTypeFile": "/var/lib/mender/device_type",
    "DBus": {
        "Enabled": true
    },
    "UpdatePollIntervalSeconds": 600,
    "InventoryPollIntervalSeconds": 14400,
    "RetryPollIntervalSeconds": 300,
    "Servers": [
        {
            "ServerURL": "https://mender.electrosense.org"
        }
    ]
}'
    } | sudo tee $MENDER_CONF_FILE > /dev/null
    echo "Created mender configuration file on $MENDER_CONF_FILE"
    
    # Mender connect file
    {
echo -e '{
  "ShellCommand": "/bin/bash",
  "User": "electrosense"
}'
    } | sudo tee $MENDER_CONN_CONF_FILE > /dev/null
    echo "Created connect configuration file on $MENDER_CONN_CONF_FILE"
}

# Set mender identity
mender_device_identity() {
    
    # Mender identity directory
    if [ ! -d "$MENDER_IDENTITY_DIR" ] 
    then
        echo "Creating directory in $MENDER_IDENTITY_DIR"
        sudo mkdir -p $MENDER_IDENTITY_DIR
    else
        echo "Directory already exists"
    fi
    
    {
echo -e "#!/bin/sh

# Script that provices the identity of the sensor to the mender backend
#
# This script collects the MAC address of the eth0 interface, as well as, the 
# CPU serial as read from /proc/cpuinfo. The identity data is output in the
# following format:
#
# mac=00:01:02:03:04:05
# cpuid=1112233
#
# Author(s): Yago Lizarribar <yago.lizarribar@imdea.org>
# Year: 2022
# 
# This script is a modification of the sample identity script provided by mender
# For more information on identity files/scripts please refer to:
# https://docs.mender.io/development/client-installation/identity
#

set -ue

SCN=/sys/class/net
min=65535
arphrd_ether=1
ifdev=

# find iface with lowest ifindex, skip non ARPHRD_ETHER types (lo, sit ...)
for dev in \$SCN/*; do
    if [ ! -f \"\$dev/type\" ]; then
        continue
    fi

    iftype=\$(cat \$dev/type)
    if [ \$iftype -ne \$arphrd_ether ]; then
        continue
    fi

    # Skip dummy interfaces
    if echo \"\$dev\" | grep -q \"\$SCN/dummy\" 2>/dev/null; then
        continue
    fi

    idx=\$(cat \$dev/ifindex)
    if [ \$idx -lt \$min ]; then
        min=\$idx
        ifdev=\$dev
    fi
done

if [ -z \"\$ifdev\" ]; then
    echo \"no suitable interfaces found\" >&2
    exit 1
else
    echo \"using interface \$ifdev\" >&2
    # grab MAC address
    echo \"mac=\$(cat \$ifdev/address)\"

    # grab CPU info
    id=\$(grep Serial /proc/cpuinfo | awk '{print \$3}')
    echo \"cpuid=\$id\"
fi"
    } | sudo tee $MENDER_IDENTITY_SCR > /dev/null

    sudo chmod +x $MENDER_IDENTITY_SCR
    echo "Created identity file on $MENDER_IDENTITY_SCR"
}

# Install Mender
mender_install() {
    sudo apt update
    # In case there are previous configuration files, we can force to use them without user interaction
    sudo apt install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" mender-client mender-connect
}

#######################################################################################
# Run all functions
I=1
echo "-------------------- Setting Mender for Electrosense sensors --------------------"
echo "--------------------"
echo "STEP $I: Mounting as Read-Write"
sudo mount -o remount,rw / ; sudo mount -o remount,rw /boot # We need to mount as read write
I=$((I+1))
echo "--------------------"
echo "STEP $I: Installing Dependencies"
install_dependencies
I=$((I+1))
echo "--------------------"
echo "STEP $I: Set Up Mender Directories"
mender_setup
I=$((I+1))
echo "--------------------"
echo "STEP $I: Set Up Mender Repository"
repo_setup
I=$((I+1))
echo "--------------------"
echo "STEP $I: Installing Mender"
mender_install
I=$((I+1))
echo "--------------------"
echo "STEP $I: Checking Device Type"
device_type_check
I=$((I+1))
echo "--------------------"
echo "STEP $I: Creating Configuration Files"
mender_conf
I=$((I+1))
echo "--------------------"
echo "STEP $I: Creating Identity Script"
mender_device_identity
I=$((I+1))
echo "--------------------"
echo "STEP $I: Rebooting"
sudo reboot
