#!/usr/bin/python3

import shutil
import os
import urllib.request
import json
import getpass
import sys
import subprocess

username = getpass.getuser()
userid = os.getuid()
installation_dir = "/home/" + username + "/.weather-get"

if userid == 0:
	print ("can't install the program using the root account,")
	print ("re-run the program using your own account...")
	sys.exit()

def create_counter_file():
	file = open ("counter", "w")
	file.write ("1")
	file.close()

def copy_files():
	print ("weather-get (beta) installation wizard")
	print ("copying core files...")
	shutil.copytree ("./files", installation_dir)
	
	print ("setting up paths...")
	file = open ("/home/" + username + "/.bashrc", "a+")
	file.write ("export PATH=$PATH:" + installation_dir)
	
def set_crontab():
	print ("setting up crontab...")
	subprocess.call ("crontab -l > backup_cron", shell=True)
	file = open ("backup_cron", "a+")
	file.write ("#weather-get\n")
	file.write ("*/10 * * * * " + installation_dir + "/weather-get\n")
	file.close()
	subprocess.call ("crontab < backup_cron", shell=True)
	subprocess.call ("rm backup_cron", shell=True)
	
def set_permissions():
	print ("setting permissions...")
	os.chmod (installation_dir + "/weather-get", 0o555)
	os.chmod (installation_dir + "/history", 0o777)
	os.chmod (installation_dir + "/weather", 0o777)
	os.chmod (installation_dir + "/location", 0o777)
	os.chmod (installation_dir + "/log", 0o777)

def geo_lookup():
	os.chdir(installation_dir)
	country = input("enter the name of your country ")
	city = input("enter the name of your city ")
	weather_url = 'http://api.wunderground.com/api/c4ee334a3234caff/geolookup/q/' + country + '/' + city + '.json'
	weather_api = urllib.request.urlopen (weather_url)
	json_input = weather_api.read()
	json_parsed = json.loads (json_input.decode('utf8'))
	try:
		api_error = json_parsed['response']['error']['description']
		print (api_error)
		geo_lookup()
	except:
		file = open ("location", "w")
		file.write (country + "\n")
		file.write (city)
		file.close()
		print ("updating current weather...")
		subprocess.call(installation_dir + "/weather-get", shell=True)
		print ("thats all for now, run 'weather-get -p' to get the current weather")

copy_files()
set_crontab()
set_permissions()
create_counter_file()
geo_lookup()

