#!/bin/bash

prep_install (){
    if ! [ -f /opt/firstrun_prep_install ]
    then
        touch /opt/firstrun_prep_install
        cp /usr/share/vim/vimrc /root/.vimrc
        cp /usr/share/vim/vimrc /home/wps/.vimrc
        sed -i 's/"syntax on/syntax on/g;s/"set mouse=a/set mouse=v/g' /root/.vimrc
        sed -i 's/"syntax on/syntax on/g;s/"set mouse=a/set mouse=v/g' /home/wps/.vimrc
        echo "deb [allow-insecure=yes arch=i386 trusted=yes] http://stationsrepo/debian parkid multiverse" > /etc/apt/sources.list.d/repo.list
        apt-get -yq install gnupg curl net-tools ntpdate
        apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 0xB1998361219BD9C9
        curl -O https://cdn.azul.com/zulu/bin/zulu-repo_1.0.0-2_all.deb
        apt-get install -y ./zulu-repo_1.0.0-2_all.deb
        apt-get update
        apt-get install zulu8-jdk zulu8-jre-headless -y
        rm -f zulu-repo_1.0.0-2_all.deb
    #    apt-get install software-properties-common ntpdate net-tools -y
    #    apt-add-repository 'deb http://security.debian.org/debian-security stretch/updates main'
    fi
}


clean_install (){
    prep_install
    echo "Running apt update.."
    apt-get update 1>/dev/null
    echo "Station packages available for install:"
    apt-cache search parkid |grep station |grep -vE "test|master"
    echo "** use apt-get install <package>"
}

restore (){
    prep_install
    echo "Running apt update.."
    apt-get update 1>/dev/null
    #install
    #vpn client?
    if [ -f /root/backup/pkgs/vpn-client ]
    then
        apt-get install vpn-client -f 
    fi
    package=$(find /root/backup/ -type f -name "station*.xml" | awk -F "/" '{print $NF}' |sed 's/.xml//g')
    count_package=$(find /root/backup/ -type f -name "station*.xml" | awk -F "/" '{print $NF}' |sed 's/.xml//g' |wc -l)
    if [ ${count_package} -gt 1 ] 
    then 
        echo "To much xml backups"
        echo "Please remove xmls from /root/backup and run the script again"
        exit
    fi
    apt-get install ${package} -y
    cp $(find /root/backup/ -type f -name "station*.xml") /var/opt/${package}/
    for database in $(find /root/backup/ -type f -name "station*db")
    do
         cp $database /var/opt/${package}/database/
    done
    #ontwikkeling loopt achter, daarom jdk-8 ( moet naar zulu toe )
#    apt-get install openjdk-8-jre-headless openjdk-8-jre -y
    service station restart
    if [ -f /root/backup/pkgs/stationwebui ]
    then
        apt-get install chromium xinput -y
        cd /tmp/
        apt download stationwebui
        dpkg --ignore-depends=chromium-browser -i stationwebui_2.27.40.598_all.deb 
    fi
}

case $1 in
     prep_install)
          prep_install;;
     clean_install)
          clean_install;;
     restore)
          restore;;
     *)
          echo clean_install or restore ;;
esac

