// Copyright (C) 2022 Denis 'GNUtoo' Carikli <GNUtoo@cyberdimension.org>
//
// 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 <https://www.gnu.org/licenses/>.

package main

import (
	"fmt"
	"net/http"
	"os"
)

var instance = "https://archive.softwareheritage.org/api/1/"

func help(progname string) {
	fmt.Println("Usage: ")
	fmt.Println("\t" + progname +
		" <URL>  # Backup the git repository at URL")
	fmt.Println("\t" + progname + " --help # Prints this help")
}

func handle_http_response(url string, http_code int,
	http_string string) (code int) {
	switch http_code {
	case 200:
		fmt.Println("[ OK ] " + url)
	case 400:
		fmt.Println("[ !! ] " +
			"An invalid visit type or origin url has been provided")
	case 403:
		fmt.Println("[ !! ] The provided origin url is blacklisted")
	case 404:
		fmt.Println("[ !! ] " +
			"No save requests have been found for a given origin")
	default:
		fmt.Println("[ !! ] Error", http_string)
	}

	return http_code
}

func start_archive(url string) int {
	resp, err := http.Post(instance+"origin/save/git/url/"+url+"/",
		"application/json", nil)
	if err != nil {
		panic(err)
	}
	handle_http_response(url, resp.StatusCode, resp.Status)

	defer resp.Body.Close()

	return resp.StatusCode
}

func check_archive(url string) int {
	resp, err := http.Get(instance + "origin/save/git/url/" + url + "/")
	if err != nil {
		panic(err)
	}
	handle_http_response(url, resp.StatusCode, resp.Status)

	defer resp.Body.Close()

	return resp.StatusCode
}

func archive(url string) {
	var ret int

	ret = start_archive(url)
	if ret == 200 {
		check_archive(url)
	}
}

func main() {
	if len(os.Args) != 2 {
		help(os.Args[0])
		os.Exit(64)
	} else if os.Args[1] == "--help" {
		help(os.Args[0])
		os.Exit(0)
	}
	archive(os.Args[1])
}
