#! /usr/bin/python3
# Copyright (C) 2018-2020 Merspieler, merspieler _at_ airmail.cc
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import os
import sys

argc = len(sys.argv)
i = 1
first = True
while i < argc:
	if sys.argv[i] == "-h" or sys.argv[i] == "--help":
		print("usage: split-world.py <file> [OPTIONS]")
		print("Handles job asignments and keeps track of the status")
		print("")
		print("  <file>            Is the worldwide osm file")
		print("OPTIONS")
		print("  -h, --help        Shows this help and exit")
		sys.exit(0)
	else:
		if first:
			world_file = sys.argv[i]
		else:
			print("Unknown option " + sys.argv[i])
			sys.exit(1)
	i += 1

config_path = os.path.dirname(os.path.realpath(__file__)) + "/osmium-config/"
prefix = "osmium-cut-world-step-"
state4 = ['nw', 'ne', 'sw', 'se']
state2 = ['s', 'n']

os.system("mkdir -p output")

def run_cut(path, step, name, start_file=None):
	if start_file != None:
		print("Splitting world in 4...")
		ret = os.system("osmium extract -c " + path + name + ".json " + start_file + " --overwrite")
		if ret == 0:
			os.system("mv n-pole.osm.pbf output/")
			os.system("mv s-pole.osm.pbf output/")
	else:
		print("Building: " + name + "...")
		os.system("osmium extract -c " + path + str(step) + "-" + name + ".json " + name + ".osm.pbf --overwrite")
		os.system("rm " + name + ".osm.pbf")

con_pre = config_path + prefix
run_cut(con_pre, 1, "1", world_file)
for i in range(0, len(state4)):
	run_cut(con_pre, 2, state4[i])
	for j in range(0, len(state4)):
		run_cut(con_pre, 3, state4[i] + "-" + state4[j])
		for k in range(1, 4):
			run_cut(con_pre, 4, state4[i] + "-" + state4[j] + "-" + str(k))
			for l in range(0, len(state2)):
				run_cut(con_pre, 5, state4[i] + "-" + state4[j] + "-" + str(k) + "-" + state2[l])