#!/bin/sh

pkg="HT-N01_V1_5"
resize2fs /dev/mmcblk2p8
cd /root/
rm -rf `ls | grep -v lora`
rm -rf /root/.func
rm -rf /var/www/html/*

#############################
docker rm provision
docker rmi be41e1cc644b
docker rmi 92aacf86bb05
###########################

cd /tmp/
rm $pkg.tar.gz
wget https://heltec.krasnodar.one/download/HT-N01/$pkg.tar.gz
tar -zxvf $pkg.tar.gz

systemctl stop connman
systemctl disable connman
systemctl start  NetworkManager
systemctl enable  NetworkManager


cd HT-N01

dpkg -i dnsmasq.deb
dpkg -i ethtool_arm64.deb
dpkg -i picocom_3.1-2_arm64.deb
dpkg -i golang-cfssl.deb


cp -r .func /root/
cp -r html /var/www/
chown www-data:www-data -R /var/www/html
cp hostapd.conf /etc/hostapd/
cp apache2.conf /etc/apache2/
cp dnsmasq.conf /etc/
passwd << EOF
heltec.org
heltec.org
EOF

cp docker-compose /usr/bin/docker-compose
cp -f update_gwid.sh /root/lora/packet_forwarder/lora_pkt_fwd/
cp /var/www/html/conf/global_conf.json /root/lora/packet_forwarder/lora_pkt_fwd/
htpasswd -bc /etc/apache2/.htpasswd HT-N01 heltec.org

################################################################
if [ ! -f "/root/lora/packet_forwarder/lora_pkt_fwd/gwid" ]; then
  touch /root/lora/packet_forwarder/lora_pkt_fwd/gwid
  chmod a+rw /root/lora/packet_forwarder/lora_pkt_fwd/gwid
fi

cp -f lrgateway.service /etc/systemd/system/lrgateway.service
cp -f reset_pkt_fwd.sh /root/lora/packet_forwarder/lora_pkt_fwd/

systemctl stop lora-pkt-fwd2 
systemctl disable lora-pkt-fwd2 

if [  -f "/root/lora/packet_forwarder/lora_pkt_fwd/local_conf.json" ]; then
    rm /root/lora/packet_forwarder/lora_pkt_fwd/local_conf.json
fi

echo HT-N01 > /etc/hostname
 sed -i "s/heltec/HT-N01/g" /etc/hosts
sync
#########################################################################

if [ "$1" = "4G" ] || [ "$1" = "WIFI" ]
then
    echo $1 > /root/.func/config
fi

if [ "$2" = "4G" ] || [ "$2" = "WIFI" ]
then
    echo $2 >> /root/.func/config
fi

cp rc.local /etc/
cp clearlog.service /etc/systemd/system/
#cp watchdog.service /etc/systemd/system/  
cp clearlog.timer /etc/systemd/system/
cp wifi_ap.service /etc/systemd/system/
sync
sync
systemctl restart apache2
systemctl enable apache2
systemctl daemon-reload
#systemctl enable watchdog
systemctl enable wifi_ap
systemctl enable clearlog.timer
systemctl disable mqtt_demo
systemctl stop mqtt_demo
sync
systemctl enable lrgateway
systemctl restart lrgateway
# systemctl start watchdog
systemctl restart wifi_ap
systemctl start clearlog.timer
systemctl restart rc.local
sync

cd /tmp/
rm $pkg.tar.gz