#!/usr/bin/python
# -*- coding: utf-8 -*-
#Datei fetch_config
#holt neue Scripts vom FTP-Server und ersetzt bestehende Scripts damit


import os
#setze Rechte für alle Files
os.system("sudo chmod a+rwx /home/pi/setRWX.py")
import setRWX
setRWX.set_rwx()

import stat

#hole Datum
import time
date=time.strftime("%Y %m %d %H:%M")

#hole Seriennummer des Raspebrry
import get_serial
myserial=get_serial.getserial()
    
#Pfad auf dem FTP-Server, wo die config-Files abgelegt sind
ftp_path='config/'
#hier sind die Scripts gespeichert
directory='/home/pi/'

#username
username='raspberry@egonline.ch'

#Password
password='d9z665vZuZnQ'

#FTP-Server
server='egonline-test.ch'


#schreibe Info zu fetch_config in info_file. Lösche alle vorhergehenden Einträge in info_file
import config_info_file
info_directory = config_info_file.info_directory
info_filename = config_info_file.info_filename

with open(info_directory+"/"+info_filename, "w") as text_file:
    text_file.write(date+": try to fetch config version 20170420"+"\n")

rewrite_cronjobs = "false"

import ftplib
session=ftplib.FTP(server, username, password)
#go to config- directory on FTP server
session.cwd(ftp_path)
#check if folder with serial_nr exists
if myserial in session.nlst():
    session.cwd(myserial)

    #get list of all filenames on FTPServer
    filenames=session.nlst()   
    
    for filename in filenames:
        #check if file has ending .py
        file_ending=filename[-2:]        
        py_ending="py"
        if py_ending==file_ending:
            #set file permissions to read, write and execute permissions
            if os.path.exists(directory+filename):
                os.system("sudo chmod a+rwx "+directory+filename)
            #fetch the file
            session.retrbinary('RETR '+filename, open(directory+filename, 'wb').write)
            #set file permissions to read, write and execute permissions
            os.system("sudo chmod a+rwx "+directory+filename)
            #reminder, that cronjobs must be resetted afterwards
            if filename == "cronjobs.py":
                rewrite_cronjobs = "true"
            #write name of fetched file to info.txt
            with open(info_directory+"/"+info_filename, "a") as text_file:
                text_file.write(date+": fetched "+directory+filename+"\n")

#close FTP Session
session.quit 

#get list of all filenames in directory pi
pi_filenames=os.listdir(directory)
for pi_filename in pi_filenames:
    #check if file has ending .pyc
    pi_file_ending=pi_filename[-3:]
    pyc_ending="pyc"
    if pyc_ending==pi_file_ending:
        #delete file
        os.remove(directory+pi_filename)

#write new cronjobs in cronlist and reboot afterwards
if rewrite_cronjobs == "true":
    #os.system("sudo apt install python3-pip")    
    crontab_list = os.system("crontab /home/pi/cronjobs.py")



