use anyhow::{anyhow, Result};
use fastly::http::{header, StatusCode};
use fastly::{Error, Request, Response};
use regex::Regex;

const BACKEND_NAME: &str = "origin_0";

#[fastly::main]
fn main(req: Request) -> Result<Response, Error> {
    log_fastly::init_simple("my_log", log::LevelFilter::Info);
    fastly::log::set_panic_endpoint("my_log")?;

    // Get the request's `Referer` and `Host` headers.
    let referer_option = req.get_header_str(header::REFERER).map(|s| s.to_string());
    let request_host = req
        .get_header_str(header::HOST)
        .ok_or_else(|| anyhow!("Failed to get client request HOST header"))?
        .to_string();

    // Send the request to our backend.
    let resp = req.send(BACKEND_NAME)?;

    // Get the response's `Content-Type` header.
    let content_type = resp.get_header_str(header::CONTENT_TYPE);

    // Block the request if blocking conditions are met
    if let Some(referer_host) =
        get_hotlink_referer_host(referer_option, &request_host, content_type)
    {
        log::info!(
            "Block request, host:{}, referer:{}",
            request_host,
            referer_host
        );

        let block_resp = Response::from_body("Hotlinking this image is not allowed. Naughty!")
            .with_status(StatusCode::FORBIDDEN);
        Ok(block_resp)
    } else {
        Ok(resp)
    }
}

/// Return `Some(referer_host)` if we are going to serve a hot-linked image.
///
/// We detect hot-linking by checking if the backend response has an image content type,
/// and if the request had a `referer` header that did not match the same domain as the image's
/// own URL.
fn get_hotlink_referer_host(
    referer_option: Option<String>,
    request_host: &str,
    content_type_option: Option<&str>,
) -> Option<String> {
    // None blocking if there is no referer header,
    let referer = referer_option?;

    // None blocking if it is not a image content
    if !content_type_option?.starts_with("image/") {
        return None;
    }

    // This is an image content, referer header exists
    // Need to make sure referer matches the host header
    let referer_host_cap = Regex::new(r"^https?://?([^:/\s]+).*$")
        .unwrap()
        .captures(&referer)?;
    let referer_host = referer_host_cap.get(1)?.as_str();

    if referer_host == request_host {
        None
    } else {
        Some(referer_host.to_string())
    }
}