#!/usr/bin/env python3
#-*- coding: utf-8 -*-
# clear && python3 /home/scripts_python/test_02.py

#--------------------------------------------------------------------------------------------------
import time
import pathlib
import string
from tempfile import mkstemp
from shutil import move, copymode
from os import fdopen, remove, rename

#--------------------------------------------------------------------------------------------------
My_WiFi_file_name	           = "/media/usb0/My_WiFi.txt"
My_WiFi_file_name_done         = "/media/usb0/My_WiFi_done.txt"
wpa_supplicant_conf_src_file   = "/etc/wpa_supplicant/wpa_supplicant.conf.txt"
wpa_supplicant_conf_dst_file_1 = "/etc/wpa_supplicant/wpa_supplicant.conf1"
wpa_supplicant_conf_dst_file_2 = "/etc/wpa_supplicant/wpa_supplicant.conf"

My_WiFi_file = pathlib.Path(My_WiFi_file_name)
My_WiFi_lines = ["","",""]

def replace(source_file, dest_file, old_string, new_string):
	
	#Create temp file
	fd, abs_path = mkstemp()
	with fdopen(fd,'w') as new_file:
		with open(source_file,'r') as old_file:
			for line in old_file:
				new_file.write(line.replace(old_string, new_string))
				
	#Copy the file permissions from the old file to the new file
	copymode(source_file, abs_path)

	#Move new file
	dest_file_path = pathlib.Path(dest_file)
	move(abs_path, dest_file_path)

def set_wpa_supplicant_conf() :
	try :
		if My_WiFi_file.exists ():
			My_WiFi_file_1 = open(My_WiFi_file_name,'r')
			My_WiFi_strings = My_WiFi_file_1.readlines()
			
			count = 0
			for My_WiFi_line in My_WiFi_strings :
				chaine_1 = My_WiFi_line.strip()
				chaine_1.replace(" ", "")
				My_WiFi_lines[count] = chaine_1.split("=")
				count += 1
			My_WiFi_file_1.close()
			
			if ( ( count == 2 ) and ( len(My_WiFi_lines[0]) == 2 ) and ( len(My_WiFi_lines[1]) == 2 ) ) :
				My_WiFi_lines[0][1] = My_WiFi_lines[0][1].strip()
				My_WiFi_lines[1][1] = My_WiFi_lines[1][1].strip()
				print(My_WiFi_lines[0][1])
				print(My_WiFi_lines[1][1])
				
				replace( wpa_supplicant_conf_src_file,   wpa_supplicant_conf_dst_file_1, 'My_Wifi_Network_SSID', My_WiFi_lines[0][1] )
				replace( wpa_supplicant_conf_dst_file_1, wpa_supplicant_conf_dst_file_2, 'My_Wifi_Network_PSK',  My_WiFi_lines[1][1] )

				remove(wpa_supplicant_conf_dst_file_1)
				rename(My_WiFi_file_name, My_WiFi_file_name_done)
				
				return True

				
			else :
				print ("Format de fichier incorrect !")
				return False
			
		else:
			print ("File not exist !")
			return False
			
	except :
		print ("exception !!!")
		return False
		

set_wpa_supplicant_conf()

