#!/usr/bin/python3
# -*- coding: utf-8 -*-

#	spec-msg : Create a custom/special message for the cve.basealt.ru page
#	Copyright (C) 2024-2026 Alexey Appolonov
#
#	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, see <http://www.gnu.org/licenses/>.

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

import argparse
import os
from cve_inform.err               import Error
from cve_basealt_spec_msg.io      import ReadPrevPost, ReadMsgFile, WriteToFile
from cve_basealt_spec_msg.parse   import GetVulIDs, GetRepoNames, GetProductNames
from cve_basealt_spec_msg.helpers import StripSlug, AddOneMicroSec, GenOutFilePath

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Parsing the arguments

argparser = argparse.ArgumentParser()
argparser.add_argument(
	'-p', '--prev_post',
	metavar='ABS_PATH', type=str, required=True,
	help=f'Name of the md file of the previous post (the created special post '
	'will be placed right after this file, it must exist in the "content" dir)'
	)
argparser.add_argument(
	'-m', '--msg_file_path',
	metavar='ABS_PATH', type=str, required=True,
	help=f'Absolute path of a text file containing the message'
	)
argparser.add_argument(
	'-t', '--title',
	metavar='QUOTED_STRING', type=str, required=True,
	help=f'Title of the message'
	)
args = argparser.parse_args()

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

prev_file_path = os.path.join('content', args.prev_post)
prev_date, prev_slug, err = ReadPrevPost(prev_file_path)
if err != None:
	Error(err)

slug = StripSlug(prev_slug)
date = AddOneMicroSec(prev_date)

txt, err = ReadMsgFile(args.msg_file_path)
if err != None:
	Error(err)

tags = []
for i, f in enumerate((GetProductNames, GetRepoNames, GetVulIDs)):
	t = sorted(f(txt))
	if i == 1 and t:
		slug += f'{"-" if slug and slug[-1] != "-" else ""}{"-".join(t)}-special'
	tags += t

out_txt = f'''Title: {args.title}
Slug: {slug}
Date: {date}
Tags: {', '.join(tags)}

{txt}'''

out_file_path = GenOutFilePath(prev_file_path, args.title)
err = WriteToFile(out_txt, out_file_path)
if err != None:
	Error(err)

exit(0)
