#!/usr/bin/env python3

import os.path
import sys
import argparse
import datetime

if len(sys.path) == 0:
    print("cannot get path of script")
    exit(1)

script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
lib_dir = os.path.join(script_dir, "lib")
sys.path.append(lib_dir)

import os_museum_launcher
from os_museum_launcher import get_top_dir
from os_museum_launcher.parse_info import get_raw_info_from_file
os_museum_launcher.top_dir = os.path.dirname(script_dir)

parser = argparse.ArgumentParser(
		prog="snapshot_list",
		description="List snapshots for a machine config"
)
parser.add_argument("machine_config", nargs=1, help="The machine config to list snapshots for, specified as the base name only, without the containing directory or the _boot/_config suffix")
parser.add_argument("-r", "--root", nargs=1, help="Directory to use as an alternate collection root")
args = parser.parse_args()

root_dir = get_top_dir()
if args.root:
	root_dir = args.root[0]

snapshot_base_dir = os.path.join(root_dir, ".image_snapshots")

if not os.path.isdir(snapshot_base_dir):
	print("collection root %s does not contain a .image_snapshots directory" % (root_dir,), file=sys.stderr)

info_base_path = os.path.join(snapshot_base_dir, args.machine_config[0], "_info")
if not os.path.isdir(info_base_path):
	print("no snapshot directory found for VM %s" % (args.machine_config[0],), file=sys.stderr)
	exit(1)

snapshot_info = []
for snapshot in os.listdir(info_base_path):
	try:
		info = get_raw_info_from_file(os.path.join(info_base_path, snapshot))
	except Exception:
		print("invalid info found for snapshot %s" % (snapshot,), file=sys.stderr)
		exit(1)
	revision = info.get("machine_info_revision", "-")
	if revision == "-":
		revision = info.get("machine_revision", "-")
	snapshot_type = info.get("snapshot_type", "manual")
	try:
		snapshot_datetime = datetime.datetime.fromisoformat(snapshot)
		snapshot_datetime = snapshot_datetime.astimezone()
	except Exception:
		print("invalid snapshot timestamp %s" % snapshot)
		raise
		exit(1)
	snapshot_info.append("%s\t%s\t%s" % (snapshot_datetime.strftime("%FT%T"), revision, snapshot_type))

for string in snapshot_info:
	print(string)
